The first experiment of Java EE

Experiment 1 Servlet and JSP technology -- the first user login module

1, Basic experiment -- Servlet and JSP basic development

(1) Experimental purpose

  1. Master the concept of HttpServlet, related API s and development steps;
  2. Master the basic syntax of JSP technology;
  3. Master the use method of each implicit variable of JSP;
  4. Master the integration of Servlet and JSP to develop simple user login function;

(2) Basic knowledge and principles

  1. Servlet is a Java technology solution for Web application design. It aims to expand the capability of Web server. It is created and managed by servlet container (such as Tomcat).
  2. JSP (Java Server Pages) pages are Web pages that contain java code and HTML tags. It is a Web page composed of JSP tags and HTML tags, which is mainly used for user interaction.

(3) Experiment contents and steps

  1. Download IDEA and create Java Web project (java15 and Tomcat 9.0.45 are used in this experiment)

  2. Configure tomcat

  3. Create database (user login table required)

  4. Create database connection

    Import jar package

    Configure connection pool

    <?xml version="1.0" encoding="utf-8" ?>
    <Context reloadable="true">
        <Resource
                name="jdbc/zzy_first"
                type="javax.sql.DataSource"
                maxActive="4"
                maxIdle="2"
                username="root"
                maxWait="5000"
                driverClassName="com.mysql.cj.jdbc.Driver"
                password="1138154255"
                url="jdbc:mysql://localhost:3306/zzy_first?serverTimezone=GMT%2B8&amp;useSSL=false"
                removeAbandoned="true"
                removeAbandonedTimeout="1"
        />
    </Context>
    
  5. Write login JSP file

    <%--
      Created by IntelliJ IDEA.
      User: YIYI
      Date: 2021/9/18
      Time: 10:50
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Login interface</title>
    </head>
    <body>
    <form method="post" action="loginservlet" onsubmit="return check()">
        <table>
            <tr>
                <td>user name:</td>
                <td> <input type="text" name="id" id = "username"> </td>
            </tr>
            <tr>
                <td>password:</td>
                <td><input type="password" name="pwd" id = "password"></td>
            </tr>
        </table>
        <input type="submit" value="Submit" name="Submit">
    </form>
    <script language="JavaScript">
        function check(){
            var id = document.getElementById("username").value;
            var pwd = document.getElementById("password").value;
            if(id === ""){
                alert("Please fill in the user name!");
                return false;
            }
            if(pwd === "" || pwd.length < 6){
                alert("Password format error!");
                return false;
            }
            return true;
        }
    
        window.onload = function load(){
            var error='<%=request.getAttribute("message")%>'
            if(error != 'null')
                alert(error);
        }
    </script>
    </body>
    </html>
    
  6. Create UserBean

    package zzy.Login.Bean;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
        private String id;
        private String pws;
    
        public User() {
        }
    
        public User(String id, String pws) {
            this.id = id;
            this.pws = pws;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getPws() {
            return pws;
        }
    
        public void setPws(String pws) {
            this.pws = pws;
        }
    }
    
    
  7. Create Servlet

    package zzy.Login.Controller;
    
    import zzy.Login.Bean.User;
    import zzy.Login.Dao.UserDao;
    
    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.servlet.http.HttpSession;
    import java.io.IOException;
    import java.util.ArrayList;
    
    @WebServlet(name = "LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String id = request.getParameter("id");
            String pwd = request.getParameter("pwd");
            User user = new User(id, pwd);
            boolean flag = false;
            if(id.equals("1138154255") && pwd.equals("1138154255")){
                flag = true;
            }
            RequestDispatcher rd = null;
            if(flag){
                HttpSession session = request.getSession();
                session.setAttribute("id", id);
                session.setAttribute("pwd", pwd);
                rd = request.getRequestDispatcher("index.jsp");
            }
            else{
                rd = request.getRequestDispatcher("login.jsp");
                request.setAttribute("message", "Wrong user name or password!");
            }
            rd.forward(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
  8. Configure Servlet mapping address

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 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_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>LoginServlet</servlet-name>
            <servlet-class>zzy.Login.Controller.LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>LoginServlet</servlet-name>
            <url-pattern>/loginservlet</url-pattern>
        </servlet-mapping>
    </web-app>
    

2, Improving experiment -- MVC scheme of Servlet and JSP integration

(1) Experimental purpose

  1. Master the key points of JavaBeans writing;
  2. Master the three elements of MVC design pattern: model, view and controller;
  3. Be able to skillfully use MVC mode in Web application design.

(2) Basic knowledge and principles

  1. MVC mode divides the interactive application into three parts: Model, View and Controller;
  2. Model refers to the object model abstracted from the real world, which is the reflection of application logic. The model encapsulates the data and data operation, and is the place for actual data processing and calculation.
  3. View is the interface between application and user. It is responsible for showing the application to the user and the state of the display model.
  4. The Controller is responsible for the interaction between views and models, and controls the response, response mode and process to user input. It is mainly responsible for two actions: distributing user requests to the corresponding model; Reflect the changes of the model to the view in time.
  5. MVC design pattern separates business logic from display logic, making the code clearer and better maintainability.

(3) Experiment contents and steps

  1. Modify login.jsp to add identity selection

    <form method="post" action="loginservlet" onsubmit="return check()">
        <table>
            <tr>
                <td>user name:</td>
                <td> <input type="text" name="id" id = "username"> </td>
            </tr>
            <tr>
                <td>password:</td>
                <td><input type="password" name="pwd" id = "password"></td>
            </tr>
            <tr>
                <td>Status:</td>
                <td>
                    <select name="type">
                        <option value = "student">student</option>
                        <option value = "administrators">administrators</option>
                    </select>
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" name="Submit">
    </form>
    
  2. Modify the user model UserBean and add the user type attribute

    package zzy.Login.Bean;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
        private String id;
        private String pws;
        private String type;
        public User() {
        }
    
        public User(String id, String pws, String type) {
            this.id = id;
            this.pws = pws;
            this.type = type;
        }
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getPws() {
            return pws;
        }
    
        public void setPws(String pws) {
            this.pws = pws;
        }
    }
    
    
  3. Modify the controller LoginServlet. When the user type is "Administrator", the user name is "Zjut" and the password is "Zjut2019061333" to successfully log in. Otherwise, return to the login interface.

    package zzy.Login.Controller;
    
    import zzy.Login.Bean.User;
    import zzy.Login.Dao.UserDao;
    
    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.servlet.http.HttpSession;
    import java.io.IOException;
    import java.util.ArrayList;
    
    @WebServlet(name = "LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            String id = request.getParameter("id");
            String pwd = request.getParameter("pwd");
            String type = request.getParameter("type");
            User user = new User(id, pwd, type);
            boolean flag = false;
            if((id.equals("1138154255") && pwd.equals("1138154255") && type.equals("student")) || (id.equals("Zjut") && pwd.equals("Zjut201906061333") && type.equals("administrators"))){
                flag = true;
            }
            RequestDispatcher rd = null;
            if(flag){
                HttpSession session = request.getSession();
                session.setAttribute("id", id);
                session.setAttribute("pwd", pwd);
                rd = request.getRequestDispatcher("index.jsp");
            }
            else{
                rd = request.getRequestDispatcher("login.jsp");
                request.setAttribute("message", "Wrong user name or password!");
            }
            rd.forward(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    

3, Expanding experiment -- JDBC and DAO design pattern

(1) Experimental purpose

  1. Master the basic SQL statements of database operation;
  2. Master the basic steps of connecting to the database;
  3. Master the method of using JDBC to manipulate the basic API of database;
  4. Master DAO design mode;
  5. Master the integration of MVC design pattern and DAO design pattern in a project;
  6. Further understand the correspondence between MVC design model and real entities;
  7. Understand the advantages of separating business logic from data access logic in DAO design pattern.

(2) Basic knowledge and principles

  1. JDBC (Java Data Base Connectivity) is a Java API for executing SQL statements. It provides unified access to a variety of relational databases. It is composed of a group of classes and interfaces written in Java language. JDBC provides a benchmark for building more advanced tools and interfaces, enabling database developers to write database applications.
  2. DAO (Data Access Object) design pattern encapsulates all access operations to data sources in a public API interface, which defines all transaction methods that will be used in the application. When program developers need to interact with data sources, they can use this interface directly without manipulating the database.

(3) Experiment contents and steps

  1. Create database zzy_first

    CREATE TABLE user(
        id varchar(20) primary key,
        pwd varchar(20) not null,
        type varchar(20) not null
    );
    
  2. Import mysql driver jar package

  3. Configure data source connection pool

    <?xml version="1.0" encoding="utf-8" ?>
    <Context reloadable="true">
        <Resource
                name="jdbc/zzy_first"
                type="javax.sql.DataSource"
                maxActive="4"
                maxIdle="2"
                username="root"
                maxWait="5000"
                driverClassName="com.mysql.cj.jdbc.Driver"
                password="1138154255"
                url="jdbc:mysql://localhost:3306/zzy_first?serverTimezone=GMT%2B8&amp;useSSL=false"
                removeAbandoned="true"
                removeAbandonedTimeout="1"
        />
    </Context>
    
  4. Create Dao

    BaseDao:

    package zzy.Login.Dao;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    import java.sql.Connection;
    
    public class BaseDao {
        static DataSource dataSource;
        public BaseDao() {
            try {
                if(dataSource == null){
                    Context context = new InitialContext();
                    dataSource = (DataSource)context.lookup("java:comp/env/jdbc/zzy_first");
                }
            }catch (NamingException ne){
                System.out.println("Exception:" + ne);
            }
        }
        public static Connection getConnection() throws Exception{
            return dataSource.getConnection();
        }
    }
    
    

    UserDao:

    package zzy.Login.Dao;
    
    import zzy.Login.Bean.User;
    
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Stack;
    
    public class UserDao extends BaseDao{
        private Connection conn = null;
        public UserDao(){
            try{
                conn = dataSource.getConnection();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        public void close(){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    
        public boolean Login(String id, String pwd, String typer){
            String sql = "SELECT *\n" +
                    "FROM user\n" +
                    "WHERE id = ? AND psw = ? AND typer = ?";
            try {
                PreparedStatement pstat = conn.prepareStatement(sql);
                pstat.setString(1, id);
                pstat.setString(2, pwd);
                pstat.setString(3, typer);
                ResultSet rst = pstat.executeQuery();
                if(rst.next()){
                    return true;
                }
                return false;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return false;
        }
    
        public boolean Register(String id, String pwd, String typer){
            String sql = "insert into user\n" +
                    "    VALUES (?, ?, ?)";
            try {
                PreparedStatement pstat = conn.prepareStatement(sql);
                pstat.setString(1, id);
                pstat.setString(2, pwd);
                pstat.setString(3, typer);
                int lines = pstat.executeUpdate();
                if(lines != 0){
                    return true;
                }
                return false;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return false;
        }
    }
    
    
  5. Modify LoginServlet

    package zzy.Login.Controller;
    
    import zzy.Login.Bean.User;
    import zzy.Login.Dao.UserDao;
    
    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.servlet.http.HttpSession;
    import java.io.IOException;
    import java.util.ArrayList;
    
    @WebServlet(name = "LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            String id = request.getParameter("id");
            String pwd = request.getParameter("pwd");
            String type = request.getParameter("type");
            User user = new User(id, pwd, type);
            UserDao userDao = new UserDao();
            boolean flag = userDao.Login(id, pwd, type);
            RequestDispatcher rd = null;
            if(flag){
                HttpSession session = request.getSession();
                session.setAttribute("id", id);
                session.setAttribute("pwd", pwd);
                rd = request.getRequestDispatcher("index.jsp");
            }
            else{
                rd = request.getRequestDispatcher("login.jsp");
                request.setAttribute("message", "Wrong user name or password!");
            }
            rd.forward(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
  6. Create registration JSP

    <%--
      Created by IntelliJ IDEA.
      User: YIYI
      Date: 2021/9/18
      Time: 22:13
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Registration page</title>
    </head>
    <body>
    <form method="get" action="registerservlet" onsubmit="return check()">
        <table>
            <tr>
                <td>user name:</td>
                <td> <input type="text" name="id" id = "username"> </td>
            </tr>
            <tr>
                <td>password:</td>
                <td><input type="password" name="pwd" id = "password"></td>
            </tr>
            <tr>
                <td>Enter the password again:</td>
                <td><input type="password" name="pwd" id = "password2"></td>
            </tr>
            <tr>
                <td>Status:</td>
                <td>
                    <select name="type">
                        <option value = "student">student</option>
                        <option value = "administrators">administrators</option>
                    </select>
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" name="Submit">
    </form>
    <script language="JavaScript">
        function check(){
            var id = document.getElementById("username").value;
            var pwd = document.getElementById("password").value;
            var pwd2 = document.getElementById("password2").value;
            if(id === ""){
                alert("Please fill in the user name!");
                return false;
            }
            if(pwd === "" || pwd.length < 6){
                alert("Password format error!");
                return false;
            }
            if(pwd !== pwd2){
                alert("The two passwords are inconsistent!");
                return false;
            }
            return true;
        }
    </script>
    </body>
    </html>
    
    
  7. Create registration Servlet

    package zzy.Login.Controller;
    
    import zzy.Login.Bean.User;
    import zzy.Login.Dao.UserDao;
    
    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 java.io.IOException;
    
    @WebServlet(name = "RegisterServlet")
    public class RegisterServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            String id = request.getParameter("id");
            String pwd = request.getParameter("pwd");
            String type = request.getParameter("type");
            User user = new User(id, pwd, type);
            UserDao userDao = new UserDao();
            boolean flag = userDao.Register(id, pwd, type);
            RequestDispatcher rd = null;
            if(flag){
                request.setAttribute("message", "login was successful!");
                rd = request.getRequestDispatcher("login.jsp");
            }
            else{
                request.setAttribute("message", "login has failed!");
                rd = request.getRequestDispatcher("login.jsp");
            }
            rd.forward(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
    
  8. Configure RegisterServlet mapping address

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 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_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>LoginServlet</servlet-name>
            <servlet-class>zzy.Login.Controller.LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>LoginServlet</servlet-name>
            <url-pattern>/loginservlet</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>RegisterServlet</servlet-name>
            <servlet-class>zzy.Login.Controller.RegisterServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>RegisterServlet</servlet-name>
            <url-pattern>/registerservlet</url-pattern>
        </servlet-mapping>
    </web-app>
    

4, Experimental results

  1. Enter the login interface

  2. Register a student account

  3. If there is an error, enter

    • Insufficient digits

    • The two passwords are different

  4. login was successful

  5. Login succeeded

5, Experimental summary and harvest

Through this experiment, I have well reviewed the knowledge of java web course last semester, and helped myself review quickly by viewing the previous Java Web projects, which plays a good role in the next learning of Java EE.

Keywords: Java Struts Tomcat mvc intellij-idea

Added by sloppstack on Sat, 02 Oct 2021 00:04:10 +0300