[jsp] basic knowledge summary

Keywords: Java JSP

1._JSP

1.1._ What is JSP

JSP (Java Server Pages) is a dynamic resource on the Java Web server side. It plays the same role as HTML pages, displaying data and obtaining data.

1.2._jsp composition

JSP = HTML + Javascript + JSP action tag (including EL expression)

1.3._jsp script

It's essentially Java code snippets

Classification:

  • <%...% >: Java statement
  • <% =...% >: Java expression out.print(...);
  • <%!...%>: Java defined class members

Built in objects (objects that can be used without creating):

  • out object can be used in JSP pages without creation. Its function is to output to the client;
  • <% =...% > has the same function as out.print(). They are both output to the client
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jsptest</title>
</head>
<body>
<h1>JSP demonstration</h1>
    <%
        // Java statement
        String s1 = "hello jsp";
        // It is not output to the client, but printed on the server-side console
        System.out.println(s1);
    %>
    <!-- Output to client browser -->
    Output variables:<%=s1 %><br/>
    output int Type constant:<%=100 %><br/>
    output String Type constant:<%="Hello" %><br/>
    use HTML Direct output constant<span>100</span>
</body>
</html>

In a JSP, mu lt iple <%...% > can be used together

1.4._JSP principle

JSP is a special Servlet (view the compiled JSP source code) class. When the JSP page is accessed for the first time, the container (Tomcat) will first compile the JSP into a Servlet, and then execute the Servlet. So JSP is actually a Servlet.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Fn75nh2q-1635576279684)(asset/img/05_jsp/JSP implementation principle - 1631331036343. PNG)]

The Servlet generated by JSP is stored in the work directory of tomcat. It is the "real body" of JSP. Let's open it and take a look at the content to understand the "real body" of JSP. Work in the following directory

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG uzgetskh-1635576279686) (asset / img / 05_jsp / image-20210911113731059. PNG)]

You will find that the static information in JSP (such as < HTML >) is printed in the "real body" using out.write()! This static information is output to the client as a string.

1.5._JSP comments

<% --... -- >% >, which will be ignored when JSP is compiled into. java, that is, JSP comments. You can use html comments in JSP pages: <! --... -- >, However, this annotation exists in. java compiled from JSP. It will not be ignored and will be sent to the client browser.

2._jsp instruction

JSP instructions are used to set attributes related to the entire JSP page.

Syntax format: instruction format: <% @ instruction name attr1 = "" attr2 = ""% >.

Generally, JSP instructions are placed at the top of JSP files, but this is not necessary.

Common instructions:

  • Page: defines the dependent attributes of the page, such as script language, error page, cache requirements, etc;
  • Include: include other documents;
  • taglib: import the definition of tag library, which can be user-defined tags.

2.1._page instruction

The page instruction is the most commonly specified attribute with the most attributes. The page instruction has no required attributes and is optional, such as <% @ page% >. It is OK to give no attributes.

About pageEncoding and contentType:

  • pageEncoding
    • Specifies the encoding of the current JSP page
    • This code is for the server. The server needs to know the code used by the current JSP, otherwise the server cannot compile the JSP into a java file correctly
    • This code only needs to be consistent with the real page code
  • contentType
    • Sets the encoding of the response character stream
    • Set content type response header
  • Whether pageEncoding or contentType of the page instruction, their default values are ISO-8859-1. ISO-8859-1 cannot display Chinese. Therefore, if Chinese exists in the JSP page, these two attributes must be set
  • Relationship between the two
    • When only one of pageEncoding and contentType appears, the value of the other is the same as the value that appears.
    • If neither appears, the value of both attributes is ISO-8859-1.

Import attribute: corresponds to the import statement in java code, which is used to import packages.

2.2._include instruction

  • The include instruction represents static inclusion, that is, the purpose is to combine multiple JSPS into one JSP file.
  • The include directive has only one attribute: file, which specifies the page to include
  • a. The include instruction used in the JSP page contains b.jsp. When compiling a.jsp, the two files will be combined into one file and then compiled into. java.

2.3._taglib instruction

Learn how to use jstl tags, which will be discussed later

3._ Nine built-in objects of JSP

3.1._ Brief description

JSP built-in objects: 9 objects that can be used without creating in JSP.

The nine built-in objects are as follows:

  • out(JspWriter): equivalent to response.getWriter(), which is used to send text data to the client
  • config(ServletConfig): corresponds to the ServletConfig in the "real body"
  • Page (actual type of current JSP): the "this" of the current JSP page, that is, the current object
  • pageContext(PageContext): page context object, which is the last domain object not mentioned
  • exception(Throwable): this object can only be used in the error page
  • request(HttpServletRequest): the object of the HttpServletRequest class (note)
  • response(HttpServletResponse): the object of the HttpServletResponse class (note)
  • application(ServletContext): the object of the ServletContext class (note)
  • session(HttpSession): that is, the object of HttpSession class can not be used in every JSP page. If <% @ page session = "false"% > is set in a JSP page, it means that this page cannot use session

Usage

  • Rarely used: config, page, exception
  • Not every JSP page can use: exception, session

3.2._pageContext

Main functions:

  • Domain object function
  • Proxy other domain object functions
  • Get other built-in objects

3.2.1._ Domain object function

Indicates that the current page, like other domain objects, has a common method:

  • void setAttribute(String name, Object value)
  • Object getAttribute(String name)
  • void removeAttribute(String name)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test Page Domain object</title>
</head>
<body>
    <%
        //Store data in the page field
        pageContext.setAttribute("name", "zhangsan");
    %>

    <%
        //Get data from the page field
        System.out.println(pageContext.getAttribute("name"));
    %>
</body>
</html>

3.2.2._ Proxy other domain objects

You can use pageContext to access data from request, session and application objects, "one up to four"

void setAttribute(String name, Object value, int scope): adds data to the specified range

Object getAttribute(String name, int scope): get the data of the specified range

void removeAttribute(String name, int scope): removes data in the specified range

pageContext.setAttribute("x", "X");
pageContext.setAttribute("x", "XX", PageContext.REQUEST_SCOPE);
pageContext.setAttribute("x", "XXX", PageContext.SESSION_SCOPE);
pageContext.setAttribute("x", "XXXX", PageContext.APPLICATION_SCOPE);

Object findAttribute(String name): find the data named name in page, request, session and application successively. If found, stop searching. This indicates that if there are data with the same name in this range, the page range has the highest priority

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
    <%
    
        pageContext.setAttribute("key", "page_value");
        request.setAttribute("key", "request_value");
        session.setAttribute("key", "session_value");
        application.setAttribute("key", "app_value");
    %>
    
    <%
        //Global search
        String value = (String)pageContext.findAttribute("key");
        out.print(value);
    %>
</body>
</html>

3.2.3._ Get other built-in objects

A pageContext object is equal to all built-in objects, i.e. 1 when 9. This is because you can use the pageContext object to get the other eight built-in objects.

JspWriter getOut(): get out built-in object

ServletConfig getServletConfig(): get config built-in object

Object getPage(): get the built-in object of page

ServletRequest getRequest(): get the request built-in object

ServletResponse getResponse(): get the response built-in object

HttpSession getSession(): get session built-in object

ServletContext getServletContext(): get the application built-in object

Exception getException(): get exception built-in object

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        //Get application object
        System.out.println(pageContext.getServletContext().getContextPath());
    %>
</body>
</html>

4._JSP action tag (understand)

Action tags are used to simplify Java scripts. JSP action tags are built-in action tags in JavaWeb. They are defined action tags that we can use directly.

4.1._include label

Syntax: < jsp: include page = "relative URL address" / >

Function: contains other JSP pages

Different from the include instruction:

  • The include instruction is included at the compilation level, that is, the current JSP and the included JSP are combined into a JSP, and then compiled into a Servlet;
  • The include action tag is included at the run level, that is, the current JSP and the included JSP will generate servlets respectively, and then complete the Servlet containing another JSP when executing the Servlet of the current JSP. It is the same as the include() method of RequestDispatcher.

Included JSP: a.jsp

Import other pages in this interface
<jsp:include page="a.jsp" />  

The forward tag is used to request forwarding! The forward tag has the same function as the RequestDispatcher.forward() method

5._EL expression

EL: Expression Language. It can be used directly in JSP pages. Starting from JSP 2.0, instead of JSP scripts, non Java developers can also use it.

  • It is used to replace the scope object. getAttribute("name") and display the data obtained from the scope;
  • EL is used instead of <% =...% >, and <% =...% > represents output.

5.1._EL expression application (get basic type, string)

${scope.name} gets the data in a specific scope;

${name} gets the data in the scope and finds it level by level (pageContext, request, session, application)

Differences between EL and JSP scripts

  • <% = request. Getattribute()% > null returned if not found
  • ${requestScope.name} was not found and returned ''
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el preliminary</title>
</head>
<body>
    <%
        //Always store data String in the request field
        pageContext.setAttribute("name", "Bob");
        request.setAttribute("name", "Zhangsan");
        request.setAttribute("age", 10);
        session.setAttribute("name", "Jim");
        application.setAttribute("name", "Lucy");
    %>

    <%-- use EL Expression gets the data in a field and displays it on the web page
        Scope xxxScope
     --%>
    <p>${requestScope.name}</p>
    <p>${requestScope.age}</p>
    <hr/>
    <%--
        Global search
            If there is no limit xxxScope,Will follow pageContext,request,session,application Find in the order of
     --%>
    <p>${name}</p>
    <hr/>
    <%--
        JSP Scripts and EL Differences between expressions
     --%>
    <p><%=request.getAttribute("abc")%></p>
    <p>${requestScope.abc}</p>
    <hr/>
</body>
</html>

5.2._EL expression application (get reference type)

When using EL to obtain the object call properties in the scope, you can only access the get method of the object, which must comply with the naming convention definition

Create entity class

/**
 * Represents the entity class of Person
 */
public class Person {
    private Integer id;
    private String name;
    private Integer age;

    //set,get
    //toString
}

EL expression demo

<%@ page import="com.qf.entity.Person" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el Expressions handle complex types</title>
</head>
<body>
    <%
        Person p = new Person();
        p.setId(100);
        p.setName("Tom");
        p.setAge(20);

        Person p1 = new Person();
        p1.setId(200);
        p1.setName("zs");
        p1.setAge(21);
        //Store the Person object in the domain
        request.setAttribute("person", p);

        int[] arr = {1, 2, 100, 50};
        request.setAttribute("arr", arr);

        List<String> names = new ArrayList<>();
        names.add("zs");
        names.add("ls");
        names.add("ww");
        request.setAttribute("names", names);

        List<Person> persons = new ArrayList<>();
        persons.add(p);
        persons.add(p1);
        request.setAttribute("persons", persons);

        Map<String, Object> map = new HashMap<>();
        map.put("name", "zs");
        map.put("addr", "qd");
        request.setAttribute("map", map);
    %>
    <%--
        adopt EL The expression displays the properties in the object on the page
        Premise: the attribute must have a corresponding set and get method
     --%>
    <p>${requestScope.person.id}</p>
    <p>${requestScope.person.name}</p>
    <p>${requestScope.person.age}</p>
    <hr/>
    <%--
        int[]
            1 2 100 1000
        List<String>
            "111" "222" "333"
        List<Person>
        Map<String, Object>
    --%>
    <%--
        adopt EL Expression displays the elements in the array on the page
    --%>
    <p>${requestScope.arr[3]}</p>
    <hr/>
    <%--
        adopt EL The expression displays the elements in the collection on the page, and the simple type (basic data type) is stored in the collection + String)
    --%>
    <p>${names[2]}</p>
    <hr/>

    <%--
        adopt EL Expressions display collections on the page(List, Map)The elements in the collection are complex types (except String Reference data type other than type)
    --%>
    <p>${persons[0].id}</p>
    <p>${persons[0].name}</p>
    <p>${persons[0].age}</p>
    <hr/>
    <p>${map.name}</p>
    <p>${map.addr}</p>
    <p>${map["addr"]}</p>
    <hr/>
</body>
</html>

5.3. _elexpression operator

Operatordescribe
.Access a Bean property or a mapping entry
[]Access the elements of an array or collection
+plus
-Minus or negative
*ride
/ or divexcept
% or modTake mold
== or eqTest for equality
!= or neIs the test unequal
< or ltTest for less than
> or gtTest for greater than
<= or leTest whether it is less than or equal to
>= or geTest whether it is greater than or equal to
&& or andTest logic and
|| or orTest logic or
! or notTest inversion
emptyTest for null values
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el_operator</title>
</head>
<body>
    <%
        request.setAttribute("num", 15);
        request.setAttribute("name", "");
    %>

    <%-- el operator --%>
    <p>${num + 1}</p>
    <p>${num - 1}</p>
    <p>${num * 10}</p>
    <p>${num / 10}</p>
    <p>${num div 10}</p>
    <p>${num % 3}</p>
    <p>${num mod 3}</p>
    <hr/>
    <p>${num == 15}</p>
    <p>${num eq 15}</p> <%-- eq equals --%>
    <p>${num != 15}</p>
    <p>${num ne 15}</p><%-- ne not equals --%>
    <p>${num lt 20}</p><%-- lt less than --%>
    <p>${num gt 20}</p><%-- gt great than --%>
    <hr/>
    <p>${true or false}</p>
    <hr/>
    <p>${empty name}</p>
</body>
</html>

About empty keyword

<% 
    String s1="";
    pageContext.setAttribute("s1", s1);
    String s2=null;
    pageContext.setAttribute("s2", s2);
    String s3="abcdefg";
    pageContext.setAttribute("s3", s3);
    List list1 = new ArrayList();
    pageContext.setAttribute("list1", list1);
%>
<!-- empty As long as the key content is"empty"Just return true -->
${empty s1}<br>
${empty s2}<br>
${empty s3}<br>
${empty list1}<br>

5.4. Implicit objects of El

EL expression language defines 11 implicit objects

Implicit Object describe
pageScopepage scope
requestScoperequest scope
sessionScopesession scope
applicationScopeapplication scope
paramParameter of request object, string
paramValuesParameter of request object, string collection
headerHTTP header, string
headerValuesHTTP header, string collection
initParamContext initialization parameters
cookieCookie value
pageContextpageContext field object of the current page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--
        When accessing a location on the server
        agreement://Host name: Port http://localhost:8080
        Project Name: it cannot be written in the actual development - ""Move"
        Location of resources
    --%>
    <%--<a href="/el_jstl/loginServlet?username=bob">Sign in</a>--%>
    <a href="${pageContext.request.contextPath}/loginServlet?username=bob">Sign in</a>
</body>
</html>

6._JSTL

6.1. Existing problems

EL is mainly used to obtain data from the scope. Although operation judgment can be made, the result is a result for display;

EL has no process control, such as judgment;

EL can only do a single point of access to a collection, and cannot implement traversal operations, such as loops.

6.2. What is JSTL

JSTL (Java Server Pages standardized tag library, i.e JSP standard tag library )By JCP (Java community processes), which mainly provides Java Web developers with a standard general tag library, which is maintained by Apache's Jakarta team. Developers can use these tags to replace the tags on JSP pages Java Code, so as to improve the readability of the program and reduce the difficulty of program maintenance.

JSTL is apache's extension to El expressions (that is, JSTL depends on EL), and JSTL is a tag language;

It is not a built-in tag of JSP and needs to be imported when used

6.3. _roleof JSTL

Logical operation can be performed on the data obtained by EL;

Cooperate with EL to display the data.

6.4. How to use JSTL

  1. Import the Jar package, standard.jar and jstl.jar;
  2. Introduce tag library <% @ taglib URI in JSP page=“ http://java.sun.com/jsp/jstl/core " prefix="c">

6.5. _jstlcore label

6.5.1. Input and output

out tag

  • value: can be a string constant or an EL expression
  • Default: when the content to be output is null, the value specified by default will be output
<!-- Output string aaa -->
<c:out value="aaa"/> 
<!-- Output domain properties aaa,Among them and ${aaa}identical -->
<c:out value="${aaa}"/> 
<!-- If ${aaa}Does not exist, then output xxx character string -->
<c:out value="${aaa}" default="xxx"/>

set tag

<!-- Create a file named a,Value is hello Domain properties for, range: pageContext -->
<c:set var="a" value="hello"/> 
<!-- Range is session -->
<c:set var="a" value="hello" scope="session"/> 

remove tag

<!-- Delete named a Domain properties for -->
<c:remove var="a"/> 
<!-- delete page Domain named a Domain properties for -->
<c:remove var="a" scope="page"/> 

case

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>jstl Input and output</title>
</head>
<body>
    <%--
        JSTL
        enhance EL Expression function to realize complex logical operation
     --%>
    <%-- output --%>
    <p><c:out value="hello world"/></p>
    <p>hello world</p>
    <hr/>
    <%-- Define variables
        int age = 10;
        Store data in the domain object. By default page Stored in domain
        scope:Specify the field in which the data is stored
     --%>
    <c:set var="name" value="Zhangsan" />
    <p>${pageScope.name}</p>

    <c:set var="age" value="10" scope="application" />
    <p>${age}</p>
</body>
</html>

6.5.2. Branch structure

if tag

<!-- When the condition is true Execute label body content when -->
<c:if test="${condition}"> 
    hello
</c:if>

choose tag

<!--
    Equivalent to:
        if() {
        } esle if() {
        } esle if() {
        } else if() {
        } else {
        }
-->
    <c:choose>
        <c:when test="${score >= 80}">
            <p>excellent</p>
        </c:when>
        <c:when test="${score >= 70}">
            <p>good</p>
        </c:when>
        <c:when test="${score >= 60}">
            <p>pass</p>
        </c:when>
        <c:otherwise>
            <p>fail,</p>
        </c:otherwise>
    </c:choose>

6.5.3. Cycle structure

forEach label

<!-- 
    var: Cyclic variable
    begin: Set the loop variable to start with.
    end: Set the loop variable to the end of the.
    step: Set step size! Equivalent to java Medium i++,or i+=2. step The default is 1
-->
<c:forEach var="i" begin="1" end="10" step="1">
    ${i}
</c:forEach>


<!--
    Used to output arrays and collections
    items: Specifies who to loop, which can be an array or a collection
    var: Assign a value to each element in an array or collection var Specified variable

    have access to varStatus To create a loop state variable
        count: Number of loop elements
        index: Subscript of circular element
        first: Is it the first element
        last: Is it the last element
        current: Current element
-->
<c:forEach items="${strs }" var="str">
    ${str }<br/>
</c:forEach>

7._MVC design pattern

7.1._ Classic MVC

MVC is an architecture mode in software engineering and a software design idea. It divides data operation, page display and business logic into three levels (modules), which are completed independently and called each other. MVC is not unique to Java. Now almost all B/S architectures adopt MVC mode. The three levels are as follows:

  • View: view is the interface that users see and interact with, such as HTML (static resources), JSP (dynamic resources), etc;
  • Controller: the controller controls the processing logic of the request, processes the request, and is responsible for process jump (forwarding and redirection);
  • Model: a representation and Simulation of the objective world (business simulation, object simulation).

advantage:

  • Low coupling: the correlation between modules is not strong, and it is not inseparable with a specific implementation;
  • High maintainability: Based on low coupling, functional modules at different levels can be flexibly replaced and plugged;
  • High reusability: the same database operation can serve different business processes. Take the data as an independent module to improve reusability.

7.2._ Java Web classic three-tier framework

WEB layer: contains JSP, Servlet and other WEB related content

Business layer: the business layer does not contain Java Web API, it only cares about business logic

Data layer: encapsulates the access details of the database and performs the most fine-grained operations of addition, deletion, modification and query

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-POp5EsXH-1635576279689)(asset/img/05_jsp/image-20210909162304967.png)]

Call relationship: web layer call - business layer (Service) - data layer (Dao) - DB

  • Business processing from front to back
  • Development should be carried out from the back to the front

About business:

  • transfer accounts
  • Combination of DAO layer methods

be careful:

  • Java Web API s should not appear in the business layer (Service). The business layer code is reusable and can even be applied to non web environments;
  • Do not use JDBC related API s in the business layer;
  • As an entity class, JavaBeans run through the web layer, business layer and data layer, and data interaction is carried out between each layer through JavaBeans or combinations of JavaBeans.

7.3._ Upgrade login case based on Java Web three-tier architecture

preparation:

  • Database and table building
  • New project
  • Copy the Jar package to the WEB-INF lib directory of the project
  • Prepare the jdbc configuration file and place it under src
  • The JdbcUtils utility class is placed under the utils package.

7.3.1._ Database and table building

The SQL statement is as follows

CREATE DATABASE webtest;
USE webtest;

DROP TABLE IF EXISTS user;
CREATE TABLE user  (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(20),
  password varchar(20),
  PRIMARY KEY (id)
);

INSERT INTO user VALUES (1, 'zhangsan', '123456');
INSERT INTO user VALUES (2, 'lisi', '123456');

Corresponding entity class User

public class User {
    private Integer id;
    private String username;
    private String password;
    
    //set and get
    //toString
}

7.3.2._Dao layer

Dao layer interface

import com.qfedu.entity.User;
import java.sql.SQLException;

public interface UserDao {
    User findByUsernameAndPassword(String username, String password) throws SQLException;
}

Dao layer interface implementation class

import com.qfedu.dao.UserDao;
import com.qfedu.entity.User;
import com.qfedu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User findByUsernameAndPassword(String username, String password) throws SQLException {
        String sql = "select * from user where username=? and password=?";
        Object[] params = {username, password};

        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        User user = qr.query(sql, new BeanHandler<User>(User.class), params);
        return user;
    }
}

7.3.3._Service layer

Service layer interface

import com.qfedu.entity.User;

public interface UserService {
    User login(String username, String password);
}

Service layer implementation class object

import com.qfedu.dao.UserDao;
import com.qfedu.dao.impl.UserDaoImpl;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public User login(String username, String password) {
        User user = null;
        try {
            user = userDao.findByUsernameAndPassword(username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return user;
    }
}

7.3.4._servlet

Servlet for login authentication

import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get login information
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");

        HttpSession session = request.getSession();
        //The verification code entered by the user is compared with the generated verification code
        String generateCode = (String)session.getAttribute("generateCode");
        //Ignoring case is strong
        if(generateCode.equalsIgnoreCase(code)) {
            //validate logon
            User user = userService.login(username, password);

            if(user != null) {
                //Put the successfully logged in user information in the Session
                session.setAttribute("username", "admin");
                request.getRequestDispatcher("/success.jsp").forward(request, response);
            } else {
                request.setAttribute("errorMsg", "The user name or password is incorrect. Please log in again");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } else {
            request.setAttribute("errorMsg", "Verification code error, please login again...");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Servlet used to generate verification code

import cn.dsna.util.images.ValidateCode;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CodeServlet", value = "/CodeServlet")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Generate verification code
        ValidateCode codeImg = new ValidateCode(200, 30, 4, 5);
        String code = codeImg.getCode();
        System.out.println(code);

        //Store the generated verification code in the session
        request.getSession().setAttribute("generateCode", code);

        //Send to browser
        codeImg.write(response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Servlet used to log out

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LogoutServlet", value = "/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Disable session
        request.getSession().invalidate();
        //Redirect to login.jsp
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

7.3.5._ Related pages

Login page login.jsp

Note that jquery is introduced in this page to implement the click refresh verification code. If jquery cannot run successfully, delete the out directory and try again.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<head>
    <title>Sign in</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
            //Click the verification code picture to refresh the verification code
            $("#codeImg").click(function () {
                var date = new Date();
                $("#codeImg").prop("src", "${pageContext.request.contextPath}/CodeServlet?timeStamp=" + date.getTime());
            });
        });
    </script>
</head>
<body>
<p style="color: red;">${errorMsg}</p>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
    <fieldset style="width: 300px;">
        <legend>User login</legend>
        <p>
            <label>account number</label>
            <input type="text" name="username" placeholder="enter one user name" />
        </p>
        <p>
            <label>password</label>
            <input type="password" name="password" placeholder="Please input a password" />
        </p>
        <p>
            <label>Verification Code</label>
            <input type="text" name="code" placeholder="Please enter the verification code" />
            <img id="codeImg" src="${pageContext.request.contextPath}/CodeServlet" alt="Verification Code" />
        </p>
        <p>
            <button type="submit">Sign in</button>
            <button type="reset">Reset</button>
        </p>
    </fieldset>
</form>
</body>
</html>

Success page success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
    <c:choose>
        <c:when test="${not empty username}">
            <p>welcome ${username}</p>
            <p><a href="${pageContext.request.contextPath}/LogoutServlet">cancellation</a></p>
        </c:when>
        <c:otherwise>
            <p>You haven't logged in yet, please login first<a href="${pageContext.request.contextPath}/login.jsp">Sign in</a></p>
        </c:otherwise>
    </c:choose>
</body>
</html>

Posted by Residue on Sat, 30 Oct 2021 23:57:51 -0700