简体   繁体   中英

Unable to connect MYSQL database using JSP and TOMCAT 7

When i try to login using my login jsp it doesn't check with mysql database. Any advice?

My login 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>

My 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();
    }
}

User 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 Class

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.";
}

Edit: I should have asked this from the very beginning:

When i try to login using my login jsp it doesn't check with mysql database

How do you know that your code "does not check with mysql database"

Any advice?

Yes.

  • Separate login and logout into two servlets. It will make your code easier to understand and test
  • Instead of reading all users into ArrayList (UserDAO.retrieve()), add a method to UserDAO that takes login and password and checks them against your DB. This way if you are not able to login, you will know exactly where to look for the probelem
  • Do not store passwords in plain text. Just don't do that.
  • Use JSTL in your JSP. action="/web/login.do" can be replaces with . The name of your context can change and JSTL will take care of that.

Shouldn't your datasource context look be java:comp/env/jdbc/myDB instead of eSpaceStatic.daoDS_name . Catch the SQL exception as well when doing your JNDI lookup stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM