2017-05-13 115 views
0

我想構建一個登錄面板,但是當我嘗試從控制器(LoginController)調用模型內部的一個方法(CustomerDbUtil)時,它會拋出異常。我對JSP有點新,而且我無法調試它。與控制檯輸出沿着代碼如下所示:我的servlet拋出異常

登錄形式

<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(Controller類)

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) 

如果我錯過了一些東西,或做不是有點錯了,我不知道。請幫忙。提前致謝! :)

+0

我懷疑你的customerDbUtil不屬性連接,因此在調用時它是空的。在這一行 - > theCustomer = customerDbUtil.selectCustomer(username,md5); //在此語句中引發Exception。 – user3138997

+0

@ user3138997 ...但我的eclipse不會彈出單個警告或錯誤,例如找不到方法或其他東西。 –

+0

這是一個運行時異常,而不是編譯錯誤。嘗試初始化customerDbUtil。 CustomerDbUtil customerDbUtil = new customerDbUtil(datasource); (我的錯誤最初我以爲這是一個Spring MVC) – user3138997

回答

0

您可以將spring bean注入到您的servlet中。

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