23 August 2016

Login với mysql và setAttribute, getAttribute trong Jsp & Servlet Java NetBeans

http://localhost:8084/DemoConnectDB/login.jsp
SELECT * FROM manager.contact;
http://localhost:8084/DemoConnectDB/LoginServlet


Add library mysql-connector-java-x.x.x-bin.jar
C:\Program Files\MySQL\Connector.J 5.1
Database mysql workbench
class: DBUtils.java
Java 2016
public class DBUtils {

    private static Connection conn;
    private static String DRIVER = "com.mysql.jdbc.Driver";
    private static String URL = "jdbc:mysql://localhost:3306/manager";
    private static String USER = "root";
    private static String PASS = "1234567";

    public static Connection getConnection() {
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USER, PASS);
        } catch (Exception e) {
            System.out.println(e);
        }
        return conn;
    }
}
class: Contact.java
Java 2016
public class Contact {

    private String id;
    private String name;
    private String phone;

    public Contact(String id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

}
class: ContactDAO.java
Java 2016
public class ContactDAO {

    public boolean getContact(String id, String name) {
        try {
            Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM manager.`contact` where id = ? AND name = ?");
            preparedStatement.setString(1, id);
            preparedStatement.setString(2, name);
            ResultSet rs = preparedStatement.executeQuery();
            if (rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public ArrayList<Contact> getAll() {
        ArrayList<Contact> list = new ArrayList();
        try {
            Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM manager.contact");
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String phone = rs.getString("phone");
                Contact ct = new Contact(id, name, phone);
                list.add(ct);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
Servlet: LoginServlet.java
Java 2016
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");

        ContactDAO DAO = new ContactDAO();

        //Vidu set value va add vao list
        ArrayList list = new ArrayList();
        Contact ct = new Contact("003", "test1 setAttribute va getAttribute", "0983888666");
        Contact ct1 = new Contact("004", "test2 setAttribute va getAttribute", "0123999888");
        list.add(ct);
        list.add(ct1);

        if (DAO.getContact(id, name)) {
            //Vidu ve setAttribute va getAttribute demo list
            request.setAttribute("lit", list);
            RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
            //Di den url home.jsp
            rd.forward(request, response);
        } else {
            request.setAttribute("ERR", "Loi");
            RequestDispatcher rd1 = request.getRequestDispatcher("erro.jsp");
            rd1.forward(request, response);
        }
    }

}
web.xml
Java 2016
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
login.jsp
Java 2016
<%@page import="model.Contact"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page</title>
    </head>
    <body>
        <div style="width:20%;margin: auto;">
        <h1 color="green">Login Page</h1>
        <div style="color:red">
            <%
                String errMsg = (String) request.getAttribute("ERR");
                if (errMsg != null && !"".equals(errMsg)) {
                    out.print(errMsg);
                }
            %>
        </div>  
        <form action="LoginServlet" method="POST">
            ID:<br> <input type="text" name="id" value="" /><br>
            Name:<br> <input type="text" name="name" value="" /><br>
            <input type="submit" value="Login" />
        </form>
    </div>
</body>
</html>
home.jsp
Java 2016
<%@page import="dao.ContactDAO"%>
<%@page import="model.Contact"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home Page</title>
    </head>
    <body align="center">
        <h1>Home Page</h1>
        <h2>Welcome to <%=request.getParameter("name")%> </h2>
        <h3>Get value vs getAttribute </h3>
        <table border="1" width="30%" align="center">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Phone</th>
            </tr>
        <%
            ArrayList<Contact> list = (ArrayList) request.getAttribute("lit");
            for (Contact c : list) {
        %>
            <tr>
                <td><%=c.getId()%></td>
                <td><%=c.getName()%></td>
                <td><%=c.getPhone()%></td>
            </tr>
        <%}%>
        </table>


        <h3>Get value database</h3>
        <table border="1" width="30%" align="center">
        <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Phone</th>
        </tr>
        <%
            ArrayList<Contact> list1 = new ContactDAO().getAll();
            for (Contact c1 : list1) {
        %>
        <tr>
                <td><%=c1.getId()%></td>
                <td><%=c1.getName()%></td>
                <td><%=c1.getPhone()%></td>
        </tr>
        <%}%>
        </table>
    </body>

</html>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang