我的servlet正在抛出异常

时间:2017-05-13 08:43:20

标签: java jsp servlets

我正在尝试构建一个登录面板,但是当我尝试从控制器(LoginController)调用模型(CustomerDbUtil)中的方法时,它会抛出异常。我对JSP有点新,我无法调试它。代码和控制台输出如下所示:

登录表单

    <form action="LoginController" method="POST" id="login-form">

        <header class="text-center">
            <h2 class="font-light">Login</h2>
        </header>

        <input type="hidden" name="command" value="LOAD">

        <label>Username : </label>
        <input type="text" name="username" placeholder="Username" class="form-control" required /><br>

        <label>Password : </label>
        <input type="password" name="password" placeholder="Password" class="form-control" required /><br>

        <input type="submit" value="Login" class="btn btn-primary" /><br><br>

        <span style="color:black">New users</span> <a href="user-register.jsp">Register here</a>

    </form>

LoginController (控制器类)

package com.loginpanel.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class LoginController
 */

@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Resource(name="jdbc/login_module")
    DataSource datasource;
    private CustomerDbUtil customerDbUtil;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            // Get the form data 
            String username = request.getParameter("username");
            String md5 = md5(request.getParameter("password"));

            Customer theCustomer = validate(username, md5); 

        } catch (Exception e) {
            throw new ServletException(); // Throws this exception
        }

    }


    private Customer validate(String username, String md5) throws Exception {

        Customer theCustomer;
        System.out.println("inside validate"); // Gets printed in the console

        try {

            theCustomer = customerDbUtil.selectCustomer(username, md5); // Throws Exception at this statement
            System.out.println("inside try"); // Not printed in the console

            if(theCustomer==null) {
                return null;
            } 

        } catch(Exception e) {
                throw new ServletException();
        }
        return theCustomer;

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Redirect back to the login page as the url does not support direct page access
        RequestDispatcher dispatcher = request.getRequestDispatcher("./");
        request.setAttribute("message", "You need to login first");
        dispatcher.forward(request, response);

    }



    // Hash the string to MD5
    private String md5(String str) throws Exception {

        String plainText = str;
        StringBuffer hexString = new StringBuffer();

        if(plainText!=null) {
            MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
            mdAlgorithm.update(plainText.getBytes());

            byte[] digest = mdAlgorithm.digest();

            for (int i = 0; i < digest.length; i++) {
                plainText = Integer.toHexString(0xFF & digest[i]);

                if (plainText.length() < 2) {
                    plainText = "0" + plainText;
                }

                hexString.append(plainText);
            }
        }
        return hexString.toString();
    }

}

CustomerDbUtil (型号)

package com.loginpanel.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import javax.sql.DataSource;


public class CustomerDbUtil {
    private DataSource dataSource;

    public CustomerDbUtil(DataSource theDataSource) {
        dataSource = theDataSource;
    }

    public boolean addCustomer(Customer theCustomer) throws Exception {

        // Declare the DB objects
        Connection con = null;
        PreparedStatement myStmt = null;
        boolean isExecuted = false;

        try{
            // Get the connection 
            con = dataSource.getConnection();

            // Write the SQL for adding a student
            String sql = "INSERT INTO customers ( "
                    + " first_name, last_name, username, md5, country) "
                    + "VALUES (?, ?, ?, ?, ?)";

            // Prepare the statement
            myStmt = con.prepareStatement(sql);

            // Add the params
            myStmt.setString(1, theCustomer.getCustomerFirstName());
            myStmt.setString(2, theCustomer.getCustomerLastName());
            myStmt.setString(3, theCustomer.getUsername());
            myStmt.setString(4, theCustomer.getMd5());
            myStmt.setString(5, theCustomer.getCountry());

            // Execute the SQL statement
            if(myStmt.execute()){
                isExecuted = true;
            } else {
                isExecuted = false;
            }

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // Clear the JDBC objects
            close(con, myStmt, null);
        }
        return isExecuted;
    }


    public Customer selectCustomer(String user, String md) throws Exception {

        Customer theCustomer = null;

        // Get the connection
        Connection con = null;
        PreparedStatement myStmt = null;
        ResultSet myRs = null;

        System.out.println("What??");

        try {

            con = dataSource.getConnection();

            // Write the SQL statement
            String sql = "SELECT * FROM login_module.customers WHERE username = ? AND md5 = ?";

            // Prepare the statement
            myStmt = con.prepareStatement(sql);

            // Add the parameters
            myStmt.setString(1, user);
            myStmt.setString(2, md);

            // Execute the query
            myRs = myStmt.executeQuery();

            System.out.println("Hello");

            // Fetch the student details
            if(myRs.next()) {
                int customerId = myRs.getInt("customer_id");
                String firstName = myRs.getString("first_name");
                String lastName = myRs.getString("last_name");
                String user_name = myRs.getString("username");
                String md5 = myRs.getString("md5");
                String country = myRs.getString("country");

                // Create a customer object
                theCustomer = new Customer(customerId, firstName, lastName, user_name, md5, country);

            } else {
                throw new Exception("Could not find the customer");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(con, myStmt, myRs);
        }

        return theCustomer;

    }


    public void close(Connection conn, Statement stm, ResultSet rs) throws Exception{

        try{
            // Close the objects
            if(conn!=null) {
                conn.close();
            }
            if(stm!=null) {
                stm.close();
            }
            if(rs!=null) {
                rs.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

    public List<Customer> getCustomers() throws Exception{

        List<Customer> listCustomer = new ArrayList<>();

        Connection con = null;
        Statement myStmt = null;
        ResultSet myRs = null;

        try {

                // Get the connection
                con = dataSource.getConnection();

                // Create SQL statements
                String sql = "SELECT * FROM login_module.customers";

                // Prepare the statement
                myStmt = con.createStatement();

                // Execute the statement and store it into the ResultSet
                myRs = myStmt.executeQuery(sql);

                // Fetch the data one-by-one and add it to the list
                while(myRs.next()){
                    int id = myRs.getInt("customer_id");
                    String firstName = myRs.getString("first_name");
                    String lastName = myRs.getString("last_name");
                    String username = myRs.getString("username");
                    String md5 = myRs.getString("md5");
                    String country = myRs.getString("country");


                    Customer theCustomer = new Customer (id, firstName, lastName, username, md5, country);

                    // Add it to the list
                    listCustomer.add(theCustomer);

                }

            } catch ( Exception e ) {
                e.printStackTrace();
            } finally {

                // Close the connection objects
                close(con, myStmt, myRs );

            }

            // Return the list
            return listCustomer;


    }

}

错误日志

inside validate
May 13, 2017 7:24:00 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.loginpanel.web.LoginController] in context with path [/loginpanel] threw exception [null] with root cause
javax.servlet.ServletException
    at com.loginpanel.web.LoginController.doGet(LoginController.java:38)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1504)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1460)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

我不知道我是否错过了某些东西或者做错了。请帮忙。提前致谢! :)

1 个答案:

答案 0 :(得分:0)

您可以将spring bean注入您的servlet。

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContex t(getServletContext());
InterfaceType bean = (InterfaceType)context.getBean("BeanName");