2011-03-17 61 views
0

當我嘗試登錄使用我的登錄jsp時,它不檢查mysql數據庫。有什麼建議?無法使用JSP和TOMCAT連接MYSQL數據庫7

我的登錄JSP ------------->

JSP

<table border="0" cellpadding="0" cellspacing="0" width=0% style="font-size: 8pt;"> 

<%if (session.getAttribute("userName")==null) {%> 
    <form method="post" action="/web/login.do"> 
     <input type="hidden" name="option" value="login"> 
     <tr> 
      <td>Login:</td> 
      <td><input name="u_id" type="text" id="u_id" size="20"></td> 
     </tr> 
     <tr> 
      <td>Password:</td> 
      <td><input name="u_pw" type="password" id="u_pw" size="20"> 
      </td> 
     </tr> 
     <tr> 
      <td></td> 
      <td> 
      <a href="/web/index.jsp">Home</a> | 
      <a href="/web/register.jsp">Register</a> | 
      <input type="submit" value="Log In"> 
      </td> 
     </tr> 
    </form> 
<%} 
else { 
    String username=session.getAttribute("username").toString();%> 
    <tr><td>Login: <b><%=userName%></b></td></tr> 
    <tr><td> 
     <a href="/web/index.jsp">Home</a> | 
     <a href="/web/cart/cart.jsp">Cart</a> | 


<% if (session.getAttribute("login").toString() {%> 
     <a href="/web/index.jsp">Admin Portal</a> 
<%  } 
     | 
     <a href="/web/log.do?option=logout">Logout</a> 
    </td></tr> 
<%}%> 

</table> 
</div> 

我的WEB XML -------------- --------->

<?xml version="1.0" encoding="ISO-8859-1"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    version="2.4"> 

    <servlet> 
     <servlet-name>LoginLogout</servlet-name> 
     <servlet-class>LoginLogoutServlet</servlet-class> 
    </servlet> 


    <servlet-mapping> 
      <servlet-name>LoginLogout</servlet-name> 
      <url-pattern>/login.do</url-pattern> 
     </servlet-mapping> 

    </web-app> 

My Context XML --------------> 

Context docBase="web" path="/web" workDir="work\Catalina\localhost\web" 
    Resource name="jdbc/myDB" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" password="" maxIdle="2" maxWait="5000" username="root" url="jdbc:mysql://localhost:3306/mydb?autoReconnect=true" maxActive="4"/ 
</Context> 

My LoginLogout Servlet ---------------------> 
Java 

import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.*; 
import java.util.*; 

public class LoginLogoutServlet extends HttpServlet { 
    /** 
    *This method handles the request passed in from the interface using POST method. 
    */ 
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { 
     login(req,res); 
    } 
    /** 
    *This method handles the request passed in from the interface using GET method. 
    */ 
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { 
     doPost(req,res); 
    } 
    /** 
    *This method handles the login and logout of User. 
    */ 
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ 
     response.setContentType("text/html"); 
     PrintWriter out = response.getWriter(); 
     ArrayList ex = new ArrayList(); 
     String option = request.getParameter("option"); 
     String uid = null; 
     String pw = null; 

     if(option.equalsIgnoreCase("login")){ 
      uid = request.getParameter("u_id"); 
      pw = request.getParameter("u_pw"); 

      UserDAO user = null; 
      ArrayList userDB = null; 

      try { 
       user = new UserDAO(); 
       userDB = user.retrieve(); 
      }catch(Exception e){ 
       ex.add(e); 
      } 

      boolean ufound = false; 

      HttpSession session = request.getSession(); 
      if(ex.size()==0 && !uid.equals("") && !pw.equals("")){ 
       //checks for staff in the database 
       for(int i = 0; i < userDB.size(); i++){ 
        User s = (User)userDB.get(i); 
        String login = s.getUserName(); 
        String password = s.getPassword(); 
        if((uid.trim().equalsIgnoreCase(login)) && (pw.trim().equalsIgnoreCase(password))){ 
         ufound = true; 
         session.setAttribute("userName",uid); 
        } 
       } 

       /*//checks for User in the database 
       for(int i = 0; i < userDB.size(); i++){ 
        User c = (User)userDB.get(i); 
        String email = c.getEmailAddr(); 
        String password = c.getPasswd(); 
        if((uid.equalsIgnoreCase(email)) && (pw.equalsIgnoreCase(password))){ 
         ufound = true; 
         session.setAttribute("userName",uid); 
         session.setAttribute("login","customer"); 
         session.setAttribute("customerObj",c); 
         //assign shopping cart to customer 
         session.setAttribute("ShoppingCart", new ArrayList()); 

         //checks which page did the customer login from 
         if(request.getRequestURI().equals("main.html")){ 
          //display main page 
          //RequestDispatcher rd = request.getRequestDispatcher("main.html"); 
         }else{ 
          //RequestDispatcher rd = request.getRequestDispatcher("shoppingcart.html"); 
         } 
        } 
       }*/ 
      }else{ 
       ex.add(new Exception("Please complete all fields!")); 
      } 
      if(!ufound){ 
       ex.add(new Exception("No such User found!")); 
       request.setAttribute("userName","notFound"); 
       request.setAttribute("login","notFound"); 
      }if(ufound){ 
       session.setAttribute("login","User"); 
      } 
      try { 
       user.close(); 
      }catch(Exception e){ 
       ex.add(e); 
      } 
     }else if(option.equalsIgnoreCase("logout")){ 
      HttpSession session = request.getSession(); 
      String login=(String) session.getAttribute("login"); 
      if(login.equals("User")){ 
       session.removeAttribute("userName"); 
       //request.setAttribute("Remove","removedStaff"); 
      }else if(login.equals("customer")){ 
       session.removeAttribute("userName"); 
       session.removeAttribute("cart"); 
       //request.setAttribute("Remove","removedCust"); 
      } 
      session.invalidate(); 
     } 

     //assign request attributes for jsp output 
     request.setAttribute("option",option); 
     request.setAttribute("exceptions",ex); 
     RequestDispatcher view=null; 
     response.sendRedirect("/web"); 
     out.close(); 
    } 
} 

用戶DAO。

import java.sql.*; 
import javax.sql.DataSource; 
import javax.naming.*; 
import java.util.*; 

/** 
*This class allows eStoreServlet to communicate with the database, myDB, through connection pooling. 
*This class handles the CRUD operations of the Users entity. 
*/ 
public class UserDAO{ 
    private DataSource ds; 
    private Connection con; 

    /** 
    *Constructor gets a connection from connection pool. 
    */ 
    public UserDAO() throws Exception{ 
     try { 
      Context ctx = new InitialContext(); 
      if(ctx == null) 
       throw new Exception("Can't create initial context"); 
      if(ds == null) 
       ds = (DataSource) ctx.lookup(eSpaceStatic.daoDS_name); 
      con = ds.getConnection(); 
     } catch (NamingException e){ 
      e.printStackTrace(); 
      throw new Exception(e+": User"+eSpaceStatic.daoEM_cp); 
     } 
    } 

    /** 
    *Method to add a User to the database. 
    *@param c This is the User object. 
    *@return Returns an int, if -1, means User is not added to the database. Otherwise, the id of the User will be returned. 
    */ 
    public int add(User c) throws Exception{ 
     int result = 0; 
     try{ 
      PreparedStatement stmt = con.prepareStatement("insert into User(name, username, password) values(?,?,?)"); 

      stmt.setString(1, c.getName()); 
      stmt.setString(2, c.getUserName()); 
      stmt.setString(3, c.getPassword()); 

      int rownum = stmt.executeUpdate(); 

      if(rownum == 0){ 
       result = -1; 
      }else{ 
       ResultSet rs = stmt.getGeneratedKeys(); 
       if(rs.next()){ 
        result = rs.getInt(1); 
       } 
      } 
      stmt.close(); 
     }catch(SQLException se){ 
      throw new SQLException(se+": Item"+eSpaceStatic.daoEM_add); 
     } 
     return result; 
    } 


    /** 
    *Method to retrieve all User from the database. 
    *@return Returns an arraylist which contains all the User objects. 
    */ 
    public ArrayList retrieve() throws Exception { 
     ArrayList cl = null; 
     try{ 
      cl = new ArrayList(); 
      Statement st = con.createStatement(); 
      ResultSet rs = st.executeQuery("Select * from User"); 
      if(rs!=null){ 
       while(rs.next()){ 
        User c = new User(); 
        c.setUserId(rs.getInt("userId")); 
        c.setName(rs.getString("name")); 
        c.setUsername(rs.getString("username")); 
        c.setPassword(rs.getString("password")); 
        cl.add(c); 
       } 
      } 
      st.close(); 
     } 
     catch(SQLException se){ 
      System.out.println(se+": User"+eSpaceStatic.daoEM_rtr); 
     } 
     return cl; 
    } 

    /** 
    *Method to retrieve a User from the database. 
    *@param userId This is the User Id. 
    *@return Returns a User object. 
    */ 
    public User retrieve(int userId) throws Exception { 
     User ret = null; 
     try{ 
      Statement st = con.createStatement(); 
      ResultSet rs = st.executeQuery("Select * from User where userId = "+userId); 
      if(rs!=null){ 
       while(rs.next()){ 
        User c = new User(); 
        c.setUserId(rs.getInt("userId")); 
        c.setName(rs.getString("name")); 
        c.setUsername(rs.getString("username")); 
        c.setPassword(rs.getString("password")); 
       } 
      } 
      st.close(); 
      rs.close(); 
     } 
     catch(SQLException se){ 
      throw new Exception(se+": "+eSpaceStatic.daoEM_cp); 
     } 
     return ret; 
    } 

    /** 
    *Method to update a User in the database. 
    *@param c This is the User object. 
    *@param userId This is the User id. 
    *@return Returns a boolean. If true, User is updated. If false, User is not updated. 
    */ 
    public boolean update(User c, int userId) throws Exception { 
     boolean updated = false; 
     try{ 
      PreparedStatement pstmt = con.prepareStatement("update User set (name = ?, username = ?, password = ?) where userId = ?"); 
      pstmt.setString(1, c.getName()); 
      pstmt.setString(2, c.getUserName()); 
      pstmt.setString(3, c.getPassword()); 
      pstmt.setInt(4, userId); 

      int rownum = pstmt.executeUpdate(); 
      updated = rownum!=0; 
      pstmt.close(); 
     }catch(SQLException se){ 
      System.out.println(se+": User"+eSpaceStatic.daoEM_rtr); 
     } 
     return updated; 
    } 

    /** 
    *Method to delete a User in the database. 
    *@param userId This is the User Id. 
    *@return Returns a boolean. If true, User is deleted. If false, User is not deleted. 
    */ 
    public boolean delete(int userId) throws Exception { 
     boolean deleted=false; 
     try { 
      PreparedStatement ps=con.prepareStatement("delete from User where userId= ?"); 
      ps.setInt(1,userId); 
      ps.executeUpdate(); 

      deleted=true; 
     } 
     catch (SQLException se) { 
      System.out.println(se+": User"+eSpaceStatic.daoEM_del); 
     } 
     return deleted; 
    } 

    /** 
    *Method to close connection. 
    */ 
    public void close() throws SQLException{ 
     con.close(); 
    } 
} 

eSpaceStatic類

public class eSpaceStatic { 
    public static String daoDS_name="java:comp/env/jdbc/myDB"; 
    public static String daoEM_cp="Could not look up connection pool."; 
    public static String daoEM_rtr=" could not be retrieved."; 
    public static String daoEM_add=" could not be added."; 
    public static String daoEM_del=" could not be deleted."; 
    public static String daoEM_cnf=" could not be found."; 
} 
+1

我在這裏沒有看到任何數據庫交互代碼?您需要使用JDBC連接到數據庫,最好使用由容器管理的JNDI數據源。 – trojanfoe 2011-03-17 09:04:56

+0

Trojanfoe我已經在meta-inf文件夾中使用上下文XML。哪裏不對了?上下文docBase =「web」path =「/ web」workDir =「work \ Catalina \ localhost \ web」 資源名稱=「jdbc/myDB」type =「javax.sql.DataSource」driverClassName =「com.mysql.jdbc。 Driver「password =」「maxIdle =」2「maxWait =」5000「username =」root「url =」jdbc:mysql:// localhost:3306/mydb?autoReconnect = true「maxActive =」4「/ – Err012 2011-03-17 09:37:50

+0

I沒有看到從數據源獲取數據庫連接並使用它的代碼。 – trojanfoe 2011-03-17 09:48:15

回答

1

編輯:我要問這個從一開始:

當我嘗試使用我的登錄登錄JSP不使用MySQL查詢數據庫

你怎麼知道你的代碼「不檢查智慧h mysql數據庫「

有什麼建議嗎?

是的。

  • 單獨登錄和註銷到兩個servlet中。它會讓你的代碼更容易理解和測試
  • 而不是讀取所有用戶到ArrayList(UserDAO.retrieve()),向UserDAO添加一個方法,它需要登錄名和密碼並根據你的數據庫進行檢查。通過這種方式,如果您無法登錄,您將確切知道在哪裏尋找probelem
  • 不要以純文本格式存儲密碼。只是不要那樣做。
  • 在JSP中使用JSTL。 action =「/ web/login.do」可以替換。您的上下文的名稱可能會更改,JSTL將處理此問題。
+0

現在的問題是我無法連接到我的數據庫使用jsp n tomcat。任何實際解決方案而不是改變? – Err012 2011-03-17 09:41:41

+0

可以發佈UserDAO.retrieve()代碼?我所有的建議都旨在獲得「實用的解決方案」。當前代碼「吞噬」所有異常,很難調試甚至理解。如果您重構它,您將能夠更快找到問題。 – 2011-03-17 16:15:49

+0

你的代碼中有太多的地方會出現一些錯誤的地方(數據庫連接,用戶存儲的表格,用戶出門的方式等等),很難指出真正的原因。即使對你來說也很難。嘗試重寫代碼,使其不那麼「只寫」。這將幫助您本地化您的問題的來源 – 2011-03-17 16:37:21

0

您的數據源上下文看起來不應該是java:comp/env/jdbc/myDB而不是eSpaceStatic.daoDS_name。在執行JNDI查找時抓住SQL異常。

+0

我不認爲這很重要。 eSpaceStatic.daoDS_name只是一個常量,在我看來這種情況下捕獲異常實際上會有所幫助 – 2011-03-18 10:35:37