JSP entry to mastery

JSP

1, Introduction to Jsp

JSP (full name: Java Server Pages) is a java server page. Is a dynamic Web technology standard. JSP deployed on the Web server can respond to the request sent by the client, dynamically generate Web pages of HTML, XML or other format documents according to the request content, and then return them to the requester.
JSP technology takes Java language as the script language to provide services for users' HTTP requests, and can deal with complex business requirements together with other Java programs on the server. Its essence is a simplified Servlet.

The essence of jsp is Servlet; It is mainly used for data presentation

2, Create a JSP page

As shown in the figure below: click and enter the page name.

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-U0Hl69dF-1651660782261)(img/image-20210627221130019.png)]

3, jsp implementation principle

Implementation principle of accessing jsp for the first time:

When you visit a JSP page for the first time, you will first translate the JSP into a JSP name_ jsp.java source file, and then compile it into bytecode file, give it to the jvm to run, and then output the static content.

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8YQjtfFd-1651660782262)(img/img1.png)]

Note: the process of translating jsp into java files is completed by the server, and users can't interfere.

Second access jsp operation principle

The second execution will skip the two processes of translation and compilation, directly execute the bytecode file and output the response content.

[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-0T0oDZEs-1651660782263)(img/img2.png)]

The essence of jsp is a servlet. The reason is that after compiling into a java file, the generated java file is basically consistent with the servlet class. The static content is output by the response object in the servlet and can be viewed in the virtual workspace.

The relationship and difference between jsp and servlet

Inheritance diagram of java file generated by jsp:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-GLeh2nOY-1651660782263)(img/img3.png)]

Contact:

​ jsp : jsp -> HttpJspBase -> HttpServlet

​ Custom servlet - > httpservlet

According to the inheritance diagram, the interfaces inherited or implemented are the same, but the specific implementation will be different.

Difference: (note)

  1. jsp is the main data presentation, while servlet is the main data processing to control the page Jump.
  2. jsp is a simplified servlet, which requires the server to dynamically generate java classes. Servlet itself is a java class.
  3. jsp uses html as a template, which contains the static content of the front end, while servlet is java, which can't contain the static content of the front end.
  4. jsp is mainly responsible for dynamically generating pages from the front-end content using servlet features, while servlet is responsible for all functions of servlet, which is relatively more comprehensive.
  5. There are nine built-in objects in jsp, but there is no concept of built-in objects in servlet.

4, Composition of jsp

  1. Front end content, including html, css and javaScript
  2. java code
  3. Instructions in jsp
  4. Dynamic Label
  5. Notes <% -- Notes content –% >

5, java code

jsp takes Java as the scripting language, so java code can be written in jsp. There are three forms of Java code in jsp. They are Java declaration, java script and Java expression.

1. java declaration

The declaration of java is the member variable or method created in the class outside the jsp method.

Syntax: <%! Java declaration% >

2. java script in jsp:

The essence of java script in jsp is the Java code fragment written in jsp. The location of java script corresponds to the service method in the Java code generated by jsp.

Syntax: <% java script;% >

3. java expression in jsp:

The java expression in jsp is used to output content to the page. The position of the expression is in the service method, and the parameter in the print() method is a position.

Syntax: <% = expression:% >

Note: there is no need to add a semicolon after a variable or expression.

example:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

  hello world!!!
<%--    about jsp Medium java statement,It is equivalent to writing code at the position of member variables in the class, It is mainly used to declare global variables , Create method --%>
    <%!
        public int num = 10; // global variable
        // Declare a method
        public void method(){
            System.out.println(num);
        }
    %>
    <%!
        int sum = 10 + 20;
    %>

    <%-- jsp Medium java script, Quite service Method  --%>
    <%
        response.getWriter().print(sum);
        method();
    %>
    <%
        int a = 10;
        int b = 20;
    %>
    <%
        int su = a + b;
        System.out.println("The sum of the two numbers is: a + b : " + su);
    %>

<%--    jsp in java The expression is equivalent to service Method  response.getWriter().print(sum); The method is print Parameters in method--%>
<%=su%>
<%="I am java expression"%>
</body>
</html>

jsp source code:

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/9.0.53
 * Generated at: 2021-09-16 08:27:06 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class first_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {


        public int num = 10; // global variable
        // Declare a method
        public void method(){
            System.out.println(num);
        }
    

        int sum = 10 + 20;
    
  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private static final java.util.Set<java.lang.String> _jspx_imports_packages;

  private static final java.util.Set<java.lang.String> _jspx_imports_classes;

  static {
    _jspx_imports_packages = new java.util.HashSet<>();
    _jspx_imports_packages.add("javax.servlet");
    _jspx_imports_packages.add("javax.servlet.http");
    _jspx_imports_packages.add("javax.servlet.jsp");
    _jspx_imports_classes = null;
  }

  private volatile javax.el.ExpressionFactory _el_expressionfactory;
  private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public java.util.Set<java.lang.String> getPackageImports() {
    return _jspx_imports_packages;
  }

  public java.util.Set<java.lang.String> getClassImports() {
    return _jspx_imports_classes;
  }

  public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
    if (_el_expressionfactory == null) {
      synchronized (this) {
        if (_el_expressionfactory == null) {
          _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
        }
      }
    }
    return _el_expressionfactory;
  }

  public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
    if (_jsp_instancemanager == null) {
      synchronized (this) {
        if (_jsp_instancemanager == null) {
          _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
        }
      }
    }
    return _jsp_instancemanager;
  }

  public void _jspInit() {
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {

    if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
      final java.lang.String _jspx_method = request.getMethod();
      if ("OPTIONS".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        return;
      }
      if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP Only allowed GET,POST or HEAD. Jasper Also allow OPTIONS");
        return;
      }
    }

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("    <title>Title</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\r\n");
      out.write("  hello world!!!\r\n");
      out.write("\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("\r\n");
      out.write("    ");
      out.write("\r\n");
      out.write("    ");

        response.getWriter().print(sum);
        method();
    
      out.write("\r\n");
      out.write("    ");

        int a = 10;
        int b = 20;
    
      out.write("\r\n");
      out.write("    ");

        int su = a + b;
        System.out.println("The sum of the two numbers is: a + b : " + su);
    
      out.write("\r\n");
      out.write("\r\n");
      out.write('\r');
      out.write('\n');
      out.print(su);
      out.write('\r');
      out.write('\n');
      out.print("I am java expression");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>\r\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

6, JSP core

Jsp In addition to the above html,css,js,jquery,java In addition to the code, it can also include JSP Related instructions, mainly used to set the whole JSP Page related properties, such as web page coding and scripting language.

1. Three instructions

① page instruction
<%@ page Attribute name="value" Attribute name="value" %> Control the whole jsp Configuration information of the page
				language="java" Supported languages
				contentType="text/html; charset=UTF-8" Content type
				pageEncoding="UTF-8" Encoding format of the page
				import="java.util.List,java.util.ArrayList" Import jar
				autoFlush="true" auto refresh
				errorPage="03-error.jsp" If the current page throws an exception, jump to the specified page
				session="true" This object can be used directly in the current page
				isELIgnored="false" Ignore EL expression
② include instruction
Page inclusion means that one page can contain the content of another page and can be loaded normally.
Syntax:<%@ include file="Included page name %>
Case:
top.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>head</title>
</head>
<body>
    <div>
        <h1>Top of page</h1>
    </div>
</body>
</html>

body.jsp Page code (including top.jsp and footer.jsp): 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Page body</title>
</head>
<body>
    <%-- Include other written pages on this page
    effect: Realize page reuse
     This kind of inclusion becomes a static inclusion:
       This way of inclusion is to integrate the included pages into the included pages first,Then translate into java file.
--%>
    <%@ include file="top.jsp"%>
    <div>Page body main</div>
    <%@ include file="footer.jsp"%>
</body>
</html>
footer.jsp Page code:
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div>
        <h3>Content at the bottom of the page</h3>
    </div>
</body>
</html>

Demonstration effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-88Cvixqj-1651660782265)(img/image-20210916171339507.png)]

include The main function of the instruction: it can extract the public part of the page and make each page contain this public page. First, it is to reduce the amount of code and second, it is easy for subsequent maintenance.
③ taglib instruction
Use later JSTL Standard label library.
Syntax:<%@ taglib prefix="prefix" uri="Path to import external label Library" %>

2. Six actions (understanding)

Function: JSP action tag uses XML syntax format tags to control the behavior of Servlet engine. Using JSP actions, you can dynamically insert files, reuse JavaBean components, redirect users to other pages, and generate HTML code for Java plug-ins.

1. <jsp:forward></jsp:forward> Request forwarding
   <jsp:forward page="01-login.jsp"></jsp:forward>
2. <jsp:include ></jsp:include> Partial forwarding also becomes dynamic inclusion
   <jsp:include page="Include page address.jsp"></jsp:include>
3. <jsp:useBean></jsp:useBean>
	<%-- 3. Create entity class object --%>
    <jsp:useBean id="users01" class="com.ujiuye.bean.Users"></jsp:useBean>
4. <jsp:setProperty />
   <%-- 4. Assignment in entity class object --%>
   <jsp:setProperty property="username" name="users01" value="Wang erxiao"/>		
5. <jsp:getProperty />
   <%-- 5. Gets the property value in the object --%>
  <jsp:getProperty property="username" name="users01"/>

Code example:

User Entity class:
package com.ujiuye.bean;

public class User {
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
jsp Page code:
Request forwarding:
<jsp:forward page="verifyCode?name=12345"></jsp:forward>
Page contains:
<%--
  Created by IntelliJ IDEA.
  User: dzm
  Date: 2021-09-16
  Time: 17:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Page body</title>
</head>
<body>
<%-- Translation before inclusion, First translate the included pages into java file,The method is introduced in the include page,Only at runtime will the included pages be included--%>
    <%--  You can pass parameters to the included page through this instruction --%>
    <jsp:include page="top.jsp">
        <jsp:param name="demo" value="Li Si"/>
    </jsp:include>
    <div>Page body main</div>
    <jsp:include page="footer.jsp"></jsp:include>

</body>
</html>


bean Usage of:
<%--
  Created by IntelliJ IDEA.
  User: dzm
  Date: 2021-09-16
  Time: 17:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<jsp:useBean id="user1" class="com.ujiuye.bean.User"></jsp:useBean>
<jsp:setProperty name="user1" property="username" value="Li Si"></jsp:setProperty>
full name: <jsp:getProperty name="user1" property="username"/>
<jsp:setProperty name="user1" property="password" value="123456"></jsp:setProperty>
password: <jsp:getProperty name="user1" property="password"/>

</body>
</html>

Demonstration effect:

[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 bhgtwplc-1651660782265) (IMG / image-20210916174951885. PNG)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-fic4HDrf-1651660782266)(img/image-20210916174558972.png)]

Interview question: what is the difference between dynamic inclusion and static inclusion?
1,Different writing methods:
Static inclusion is an instruction inclusion<%@include file="***"%>
Dynamic inclusion is JSP Action label contains<jsp:include page="***"></jsp:include>
2,Different compilation methods:
Static inclusion: in the compilation process, the included pages are first integrated into the included pages and then compiled. So there's only one file .Include before translate
 Dynamic inclusion: the included pages and included pages in the compilation process are compiled, and the content is passed after running servlet integration,Translation before inclusion
3,Parameter transfer:
Static inclusion cannot pass parameters to included pages
 Dynamic inclusion can be used jsp:param Tags pass parameters to included pages
4,Operating efficiency:
As a static page, including a fast; Dynamic contains multiple pages and runs slowly.

3. Nine built-in objects

Built in object: also known as implicit object, in jsp It has been initialized and encapsulated for us. It does not need to be created by programmers. The objects that can be used directly are built-in objects.   

7, Meanings of nine built-in objects:

type Built in object name effect
PageContext pageContext Setting page scope can obtain page information, save the number of pages, etc. Scope current page
HttpServletRquest request The scope of the request is the same as that of the request in the servlet.
HttpSession session The server session object is also a scope object.
ServletContext application The server object is also a scope object, which can be used to store data that needs to be consistently retained to the server.
HttpServletResponse response The response object can set the response information, and the response in the Servlet is an object
JSPWrite inherits PrintWriter out It is used to output the response content to the client and set the data in the response body.
ServletConfig config Setting and obtaining the initialization configuration information of jsp is equivalent to ServletConfig in Servlet.
this<=> object page Equivalent to this
Exception pageContext.getException() Used to set or get the error information of the page.

Object details:

1.application Object can save information in the server until the server is shut down, otherwise application The information stored in the object will be valid throughout the application. The type of the object is SevletContext Type, whose life cycle is tomcat The server is created at startup and destroyed at shutdown. Its scope of action is the whole Web Application.

2.request Object is javax.servlet.HttpServletRequest Object of type. This object represents the request information of the client and is mainly used to accept the request information through HTTP Data transferred to the server by the protocol. request The scope of the object is a request.

3.response Object is javax.servlet.HttpServletRsponse Object of type. This object represents the response information of the client, mainly JSP The object information processed by the container is returned to the client.

4.config The main function of the object is to obtain the configuration information of the server. adopt pageConext Object getServletConfig() Method can get a config Object. Be a Servlet During initialization, the container passes some information through config Object passed to this Servlet.  Developers can web.xml The file is a file in the application environment Servlet Procedures and JSP The page provides initialization parameters.

5.page: current jsp An instance of a page, equivalent to this keyword.

6.session: Session object. session Object is an object automatically created by the server related to user requests. The server generates one for each user session Object, which is used to save the user's information and track the user's operation status. Its scope is one session.

7.exception Object is used to display exception information only when it contains isErrorPage="true" Can only be used in the general page JSP Using this object in a page will not compile JSP Documents. excepation Object and Java Like all objects in the system, it has the inheritance structure provided by the system. exception Object defines almost all exceptions. stay Java In the program, you can use try/catch Keyword to handle exceptions; If in JSP An exception that is not caught in the page will be generated exception Object and put exception Object transfer to page In the error page set in the instruction, and then deal with the corresponding error in the error page exception Object.

8.out Object used in Web Output information in the browser and manage the output buffer on the application server. JSP Medium out Object is JspWriter Type.

9.pageContext Object is used to obtain parameters in any range, through which you can obtain JSP Page out,request,reponse,session,application And other objects. pageContext The creation and initialization of objects are completed by the container. You can get the root directory of the project and getXXX()Get other built-in objects.

Exception object instance:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--errorPage="error.jsp" Set the position of the current page to receive the error page if an exception occurs ,
isErrorPage="false" Indicates that the page is not an error page,jsp The default page is not an error page--%>
<%@ page errorPage="error.jsp"  isErrorPage="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
     <%
         int num = 10 / 0;
     %>
</body>
</html>

Page receiving exception information:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--  Indicates that the current page is dedicated to receiving and displaying error messages --%>
<%@ page isErrorPage="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h2>Error page</h2>
    <%
        Exception exception1 = pageContext.getException();
    %>
    <%=exception1.getMessage()%>
</body>
</html>

8, Four scopes

In order to transfer and share data among pages, requests and users, JSP provides four different scopes: pageContext, request, session and application. These scopes specify the scope of data transfer and sharing and the survival time of data.

Scope details:

1.application Scope
     If you put variables in application In, it means that its scope is application,Its effective scope is the whole application. The whole application refers to from the start of the application to the end of the application. We didn't say "from server startup to server shutdown", because a server may deploy multiple applications. Of course, if you shut down the server, all the above applications will be shut down. application Variables in the scope have the longest survival time. If they are not deleted manually, they can always be used.

application Information on the scope is passed through ServletContext The main methods provided are as follows:
Object getAttribute(String name)  //Obtain information from application;
void setAttribute(String name, Object value)  //Set information to the application scope.

2.session Scope
     session The scope is easy to understand. The same browser accesses the server multiple times, and passing information between these multiple accesses is session Scope. If you put variables in session In, it means that its scope is session,Its valid range is the current session. The so-called current session refers to the process from the user opening the browser to the user closing the browser. This process may contain multiple request responses. In other words, as long as the user does not close the browser, the server has a way to know that these requests are initiated by one person. The whole process is called a session( session),The variables put into the session can be used in all requests of the current session. 
 session Yes HttpSession The main methods provided by the interface are as follows:

Object HttpSession.getAttribute(String name)   //Get information from session.
void HttpSession.setAttribute(String name, Object value)//Save information to the session.
HttpSession HttpServletRequest.getSession()  //Gets the object of the session where the current request is located.

	session The start time of is easy to judge. It sends the first message from the browser HTTP The session is considered to have started upon request. However, it is difficult to judge the end time, because the server will not be notified when the browser is closed, so it can only be judged by the following method: if the client does not respond within a certain time, the session is considered to be over. Tomcat The default value of is 30 minutes, but this value can also be passed HttpSession of setMaxInactiveInterval()Method to set:
void setMaxInactiveInterval(int interval);
	If you want to actively end the session, for example, when the user clicks the "logout" button, you can use HttpSession of invalidate()Method to force the end of the current session: void invalidate()
3.request Scope
     One HTTP The processing of the request may require multiple Servlet Cooperation, and these Servlet Information can be passed between in some way, but this information is invalid after the request is completed. request Variables in can span forward Two pages before and after. But as long as the page is refreshed, they are recalculated. If you put variables in request In, it means that its scope is request,Its valid range is the current request cycle. The so-called request cycle refers to the period from http The whole process from the initiation of the request to the end of the server processing and the return of the response. May be used in this process forward Jump multiple ways jsp Page, in which you can use this variable.

Servlet Information sharing between is through HttpServletRequest Interface is implemented by two methods:
void setAttribute(String name, Object value)//Save the object value in the request scope with name as the name.
Object getAttribute(String name) //Get the information of the specified name from the request scope.
     JSP Medium doGet(),doPost()The first parameter of the method is HttpServletRequest Object that uses this object setAttribute()Method to save the information. Then, after setting the information, how to transfer the information to other users Servlet And? This requires RequestDispatcher Interfaced forward()Method, which forwards the request to other users Servlet. 
	RequestDispatcher ServletContext.getRequestDispatcher(String path) //Obtain the Dispatcher for forwarding, and the path is the Servlet for forwarding.
   void RequestDispatcher.forward(ServletRequest request, ServletResponse response)//Forward request and response
     Therefore, only the current Servlet First pass setAttribute()Method, and then use forward()Method to jump to the Servlet By using getAttribute()Method can realize information transmission.

4.pageContext Scope
	page The scope of the object is limited to the current page requested by the user page The reference to the object will be released after the response is returned to the client, or after the request is forwarded elsewhere. page As long as the page jumps, the variables in the are destroyed. If you put variables in pageContext In, it means that its scope is page,Its valid range is only at the current time jsp On the page. From putting variables into pageContext Start, to jsp You can use this variable at the end of the page.

The current page stores the data in the four scopes and obtains the data in the scope:

Code example:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--        Scope is the current page,If you switch or jump to another page,Waiting data in the scope will be destroyed --%>
<%--        request Scope, The scope is a request, The data stored in the scope can only be obtained by jumping through request forwarding  --%>
<%--  session Represents a session, By default, the life cycle of a session is browser shutdown,End of session.
        session Session object belonging to server, The reason why the data can not be obtained is that it is used to identify the user JSESSIONID Destroyed,
        On server session The default save time is 30 minutes    --%>
<%--    Application scope object application  -> ServletContext The scope of this scope is,
           Application lifecycle,Server shutdown,Waiting for data destruction in scope ,The life cycle of the entire application run    --%>
    <%

        pageContext.setAttribute("page", "Page scope object!!");
        request.setAttribute("request","request Scope");

        session.setAttribute("session","session Scope object");

        application.setAttribute("application","Application scope object");
    %>

    <p>
        page Scope: <%=pageContext.getAttribute("page")%>
    </p>
    <p>
        request Scope: <%=request.getAttribute("request")%>
    </p>
    <p>
        session Scope: <%=session.getAttribute("session")%>
    </p>
    <p>
        application Scope: <%=application.getAttribute("application")%>
    </p>
</body>
</html>

Demonstration effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mxzbaDJV-1651660782267)(img/image-20210917102820030.png)]

According to the demonstration effect, the values in the four scopes can be obtained without page Jump

In one Add the jump to which the request is forwarded at the end of the JSP page Jump to two JSP page, the code is as follows

[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-J8ItjMgq-1651660782268)(img/image-20210917103034820.png)]

two.jsp code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>
        page Scope: <%=pageContext.getAttribute("page")%>   
    </p>
    <p>
        request Scope: <%=request.getAttribute("request")%> 
    </p>
    <p>
        session Scope: <%=session.getAttribute("session")%> 
    </p>
    <p>
        application Scope: <%=application.getAttribute("application")%> 
    </p>
</body>
</html>

Demonstration effect:

[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-Li7vnDVK-1651660782268)(img/image-20210917103150679.png)]

According to the demonstration effect, it can be seen that the data in the page scope cannot be obtained, because the data in the page scope can only be obtained on the current page; The data in the request scope can be obtained because the jump forwarded by the request belongs to the same request, all can be obtained, and the session belongs to a session. It can be obtained by default as long as the browser is not closed or switched Application is the whole application life cycle

Put one The request renewal in JSP is changed to redirection, as shown in the following figure:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--        Scope is the current page,If you switch or jump to another page,Waiting data in the scope will be destroyed --%>
<%--        request Scope, The scope is a request, The data stored in the scope can only be obtained by jumping through request forwarding  --%>
<%--  session Represents a session, By default, the life cycle of a session is browser shutdown,End of session.
        session Session object belonging to server, The reason why the data can not be obtained is that it is used to identify the user JSESSIONID Destroyed,
        On server session The default save time is 30 minutes    --%>
<%--    Application scope object application  -> ServletContext The scope of this scope is,
           Application lifecycle,Server shutdown,Waiting for data destruction in scope ,The life cycle of the entire application run    --%>
    <%

        pageContext.setAttribute("page", "Page scope object!!");
        request.setAttribute("request","request Scope");

        session.setAttribute("session","session Scope object");

        application.setAttribute("application","Application scope object");
    %>

    <p>
        page Scope: <%=pageContext.getAttribute("page")%>
    </p>
    <p>
        request Scope: <%=request.getAttribute("request")%>
    </p>
    <p>
        session Scope: <%=session.getAttribute("session")%>
    </p>
    <p>
        application Scope: <%=application.getAttribute("application")%>
    </p>
<%-- Request forwarding to realize page Jump--%>
    <%
//        request.getRequestDispatcher("two.jsp").forward(request,response);
        response.sendRedirect("two.jsp");
    %>
</body>
</html>

<%--
  Created by IntelliJ IDEA.
  User: dzm
  Date: 2021-09-17
  Time: 10:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>
        page Scope: <%=pageContext.getAttribute("page")%>
    </p>
    <p>
        request Scope: <%=request.getAttribute("request")%>
    </p>
    <p>
        session Scope: <%=session.getAttribute("session")%>
    </p>
    <p>
        application Scope: <%=application.getAttribute("application")%>
    </p>
</body>
</html>

Demonstration effect:

It is suggested that the image can be saved directly in the external link (rpg-63imj, 16img-171imj) (if there is an external link, it is suggested that the image can be saved directly in the external link)

According to the demonstration effect, the data in the request scope cannot be obtained, because the redirection does not belong to a request, so the data in the request cannot be obtained However, no matter how you jump, it is a session. As long as you don't close the browser or switch browsers to access it, it belongs to a session

Switch the browser or close the browser to visit two JSP, the effect is as follows:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-3UXsm165-1651660782270)(img/image-20210917103919403.png)]

Depending on the effect, switching the browser or closing the browser to revisit will reopen a session and the number in the session will disappear

In the early stage of shutting down or restarting the service, the application data will also disappear

Scope size sort:
from small to large: pageContext<request<session<application

9, EL expression

https://baike.so.com/doc/6751385-6965950.html

① Introduction
EL(Expression Language) To make JSP It's easier to write. The inspiration of expression language comes from ECMAScript and XPath Expression language, which provides JSP The method of simplifying the expression in Jsp The code is more simplified.
effect: simplify jsp,To replace jsp Medium java code,bring jsp It looks more beautiful and concise.
el Expressions mainly obtain data from the four scopes.
② Function
It's a kind of JSP A simple way to get data from a page(Only data can be obtained, but data cannot be set)By:
stay JSP Any static part of the page can be accessed through: ${expression}To get the value of the specified expression
 It includes the following ways:
${Binding name} obtain javaBean Object or other types of data
${Binding name.Attribute name} obtain javaBean Corresponding attribute name in
${Binding name[Index value]} Get the corresponding value in the collection or array
${Binding name["key"]} adopt key Get the value of in Map Corresponding in value value

You can also el Do some simple operations inside the expression:   

[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-GwQWYp6J-1651660782271)(img/wps1-16317092576851.jpg)]

Code example:

<%--
  Created by IntelliJ IDEA.
  User: dzm
  Date: 2021-09-17
  Time: 10:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>el Operation of expression</title>
</head>
<body>

    <h3>arithmetic operation </h3>
    + ${10 + 20} - ${30-10} % ${23%3}
    <h3>Logical operation</h3>
    && ${10 > 2 && 20 > 3}  || ${10 < 3 || 10 > 6}

    <h3>Comparison operation</h3>
    == ${10 == 5}
    <%
        pageContext.setAttribute("money", 1000);
    %>
    ${money > 100}
    ${money != 0}
    ${money >= 10000}
<%--    el If the value obtained is null Don't show--%>
    ${abc}

<h3>Null value judgment</h3>

${demo != null} false
${empty money} false
    10 30 5 <br>
${10> 30 ? (10 > 5 ? 10 : 5) : (30 > 5 ? 30 : 5)}

</body>
</html>

Demonstration effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ofrnwl-1651660782271) (IMG / image-20210917111201846. PNG)]

③ Principle
	Retrieve the corresponding binding name from the four scope objects in turn. If it is obtained from one object, it will not be retrieved from other objects. Otherwise, it will continue to retrieve. If it is not found, it will return an empty string instead of an empty string null
	If: ${user.name}take as an example
EL The expression will be based on name go User Look for this in the class name of get Method, which will automatically name Initial capital plus get Prefix, once a matching method is found, El The expression will think that this is the property to be accessed and return the value of the property.
So, want to pass EL Expression to get the value of an object property, then this property must have a corresponding get method.
You can improve the retrieval speed by specifying four scope objects, as follows:
application-->applicationScope
session-->sessionScope
request-->requestScope
pageContext-->pageScope
 For example:
${requestScope.user} It means going directly request Object user Value corresponding to binding name
④ Case
Get separately javaBean,javaBean attribute,Map Value, List,Value of array type
 Code example:
<%@ page import="com.ujiuye.bean.User" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Get data from scope</title>
</head>
<body>
    <h3>Simple type data acquisition</h3>
    <% pageContext.setAttribute("name", "demo");
    %>
    ${name}
     <h3>javabean Data in</h3>
    <%
        pageContext.setAttribute("us", new User("Zhang San","16723456"));
    %>

    ${us}
    ${us.username}
    ${us.getPassword()} | ${us.password}

    <h3>Array or List aggregate</h3>
    <%
        String[] arr = {"Send Wukong","Zhu Bajie","Jordan","Baoqiang"};
        pageContext.setAttribute("demo", arr);
    %>
    <p>
        ${demo}
        ${demo[0]}
        ${demo[1]}
        ${demo[2]}
        ${demo[3]}
    </p>
    <hr>
    <%
        List<User> uList = new ArrayList<>();
        uList.add(new User("Emerald flower","12345"));
        uList.add(new User("lotus","345675"));
        uList.add(new User("Xi Shi","9999"));
        uList.add(new User("army officer's hat ornaments","12345"));
        pageContext.setAttribute("list", uList);
    %>

    ${list}
   <p> ${list.get(0).username} ${list[0].password}</p>
   <p> ${list[1].username} ${list[1].password}</p>
   <p> ${list[2].username} ${list[2].password}</p>
   <p> ${list[3].username} ${list[3].password}</p>

    <h3>map Data in collection</h3>

<%
    Map<String,String> map = new HashMap<>();
    map.put("key1","Xi Mengqing");
    map.put("key2","Edison");
    map.put("key3","Jiang Jinfu");
    map.put("key4","Wu Zhang");
    pageContext.setAttribute("map", map);
%>

${map}
${map['key1']}
    ${map.key2}
    ${map.key3}
    ${map.key4}
</body>
</html>

Demonstration effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-FLEDmD7F-1651660782272)(img/image-20210917113413657.png)]

Examples with the same value stored in the four scopes:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Default value order in four scopes</title>
</head>
<body>
<%

    pageContext.setAttribute("demo", "Page scope object!!");
    request.setAttribute("name","request Scope");

    session.setAttribute("name","session Scope object");

    application.setAttribute("name","Application scope object");
%>
<%-- If the name of the data stored in the scope is the same,The default value order is to search according to the scope from small to large --%>
${name}

from pageContext Value in scope: ${pageScope.demo} <br>
from request Value in scope: ${requestScope.name} <br>
from session Value in scope: ${sessionScope.name} <br>
application: ${applicationScope.name} <br>

</body>

effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-LsTNrsYC-1651660782273)(img/image-20210917141907616.png)]

If the name of the data stored in the scope is the same,The default value order is to search according to the scope from small to large,Display directly after searching,Do not continue the search successively,If you need to restrict the value from each scope, you can specify the name of the scope,Example above.

10, JSTL tag library

Rookie tutorialhttps://www.runoob.com/jsp/jsp-jstl.html

① Introduction
JSTL(JavaServer Pages Standard Tag Library,JSP Standard label Library)It is a continuously improving open source system JSP Tag library. It is mainly provided to JavaWeb Developers a standard generic label that developers can use to replace JSP On page Java Code, so as to improve the readability of the program and reduce the difficulty of program maintenance.
It should be noted that: jstl Where values need to be obtained, they should be matched EL Expression to use
② Use
1) Import
jstl.jar  standard.jar Two bags
2) Introduce
Bring the tag library into the page
<%-- Import label Library --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
3) Common labels
1.<%--Declare variable label--%>
<c:set var="name" value="Liuyan"></c:set>
    var:Declared variable name
    value:Value of variable

2.<%--Output label--%>
<c:out value="${name}" ></c:out>
value:The value of the variable to output,Need to pass el Expression acquisition

3.<%--Delete declared variable--%>
<c:remove var="name"></c:remove>
var:Delete the name of the variable to be deleted

4.<%--if Single branch label--%>
<c:if test="${empty name}">test if Branch label 1</c:if>
test:When the value is true The value inside the label is displayed when it is displayed, otherwise it is not displayed

5.<%--choose Multi branch label--%>
<c:choose>
   <c:when test="${1>2}">Label content of the first condition</c:when>
   <c:when test="${3>2}">Label content of the second condition</c:when>
   <c:otherwise>Label content that does not meet the above conditions</c:otherwise>
</c:choose>
When when Tagged test The value of is true When, the label content is displayed, otherwise, it is not displayed when multiple when All labels are true When, the first value is displayed as true of when Label content, if above when All labels are false Then display otherwise Label content
 be careful:
   when At least one label appears
   otherwise At most one label appears
6.<%--Traversal label of a collection or array--%>
<c:forEach items="" var="" >

</c:forEach>
items:To traverse a collection or array object, you need to pass el Expression acquisition
var: Cyclic variable,It can be understood as the custom name of each value or object in a collection or array

Core tag code example:

<%@ page import="com.ujiuye.bean.User" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>jstl Use example</title>
</head>
<body>
    <%-- jstl Store data in session In scope
    var Name of variable
    value Is the value of the data in the scope
    scope : Scope name, such as page(default) request  session application
    --%>
    <c:set var="demo" value="123456" scope="session"></c:set>
<%--     Used to output the data stored in the scope value The value of the attribute is the name of the data stored in the scope--%>
    <c:out value="${demo}"></c:out>  ${demo}
<%--     Can pass value Direct output content --%>
    <c:out value="Output content"></c:out>

<%--    remove Used to remove data from the scope
var Variable name in scope, scope Scope name
--%>
<c:remove var="demo" scope="session"></c:remove>
${demo}
    <hr>
<%-- if Tags can be judged --%>
<c:set var="money" value="10000"></c:set>
<%-- If attribute test The range of values is true ,The contents of the label will be output,If yes false The content in the tag will not be executed   --%>
<c:if test="${money > 1000}">
    You have money!!
</c:if>
<c:if test="${money <= 1000}">
    The poor eat the earth!!
</c:if>
    <hr>
<%--Multiple choice structure choose -> when -> otherwise--%>
<c:set var="score" value="77"></c:set>
<c:choose>
<%--    If test The value of the property is true,The contents of the label are output,as long as qianmiad There is a satisfaction,You won't go back,
If all the previous conditions return false, Will be executed otherwise Content in label --%>
    <c:when test="${score >= 90}">You are excellent</c:when>
    <c:when test="${score >= 80}">Good. Keep going</c:when>
    <c:when test="${score >= 60}">Your efforts</c:when>
    <c:otherwise>No!!</c:otherwise>
</c:choose>

    <hr>
<h3>iterator  foreach</h3>
    <%
        List<User> uList = new ArrayList<>();
        uList.add(new User("Emerald flower","12345"));
        uList.add(new User("lotus","345675"));
        uList.add(new User("Xi Shi","9999"));
        uList.add(new User("army officer's hat ornaments","12345"));
        uList.add(new User("Lv Bu","12345"));
        uList.add(new User("brutal militarist who dictated policy in declining years of the Han dynasty","12345"));
        uList.add(new User("Cao thief","12345"));
        uList.add(new User("Traitor","12345"));
        pageContext.setAttribute("list", uList);
    %>
<%--
items Used to set the collection to be traversed,Mainly need to use el Receive data from collection
var Each object iterated out
step All increments per iteration,The default is plus 1
begin The starting position of the index when traversing
end  End position of index during traversal
varStatus Traverse the state of the variable ,combination index You can get the index of the traversed object,combination count You can count the number of traversed objects
--%>

<c:forEach items="${list}" var="use" step="2" begin="1" varStatus="stat" end="5">
    <p>${stat.index}  ${stat.count}  ${use} ${use.username} ${use.password}</p>
</c:forEach>

<c:forEach var="num" end="10" begin="0">
    ${num} &nbsp;&nbsp;&nbsp;&nbsp;
</c:forEach>

</html>

Demonstration effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2HzqSZGD-1651660782273)(img/image-20210917152831320.png)]

Use of formatting and function tag libraries:

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fun" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:set var="date" value="<%=new Date()%>"></c:set>
    ${date}
    <hr>
    <fmt:formatDate value="${date}" pattern="yyyy-MM-dd hh:mm:ss"></fmt:formatDate>
    <c:set var="glod" value="12.5363733"></c:set>
<%--     Number formatting --%>
    <fmt:formatNumber value="${glod}" pattern="000.0000" ></fmt:formatNumber>
    <fmt:formatNumber value="${glod}" pattern="####.###" ></fmt:formatNumber>

    <c:set value="Once had a sincere relationship,Come to me,I got it,If God is giving me a chance,I would say,Fuck off!!" var="desc"></c:set>
    <br>
    <c:out value="${fun:length('Once had a sincere relationship,Come to me,I got it')}"></c:out> <br>
    <c:out value="${fun:substring(desc, 0, 21)}"></c:out>...
    <br>
    <c:if test="${fun:contains(desc, 'feeling')}">Good feelings</c:if>
    <c:if test="${fun:contains(desc, 'aa')}">Not good</c:if>

</body>
</html>

effect:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-0NheC4fm-1651660782274)(img/image-20210917160053788.png)]

Project hierarchy:

The dao of the persistence layer is responsible for dealing directly with the database and adding, deleting, modifying and checking the data

Business logic layer service belongs to the middle layer connecting persistence layer and interface layer. It is used to handle the calling relationship, logic processing and data transmission between each other

The interface (view) layer deals directly with users and is used to present content to users

Benefits: low coupling and high cohesion

MVC Architecture:

M is the abbreviation of Model, called Model layer, which is mainly used for data encapsulation Corresponding to JavaBeans, usually in entity / pojo / bean

V is the abbreviation of View. It is the View layer, corresponding to jsp, front-end content, and the interface directly presented to users

C is the abbreviation of Controller, which is the control layer. It is mainly used to control the acquisition of data in the view, the call of business logic layer methods and the jump of pages

Use package names in the project to reflect the hierarchy:

Package name specification:

com. ujiuye. Corresponding package name of controller control layer

com.ujiuye.service business logic layer

com.ujiuye.dao data interaction layer

com.ujiuye.bean/entity/model model layer

com.ujiuye.util various tools

The project structure is shown in the figure below:

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-jjDMUWgr-1651660782275)(img/image-20210917162420204.png)]

User login

analysis:

  1. The user of the front-end page enters the user name and password and submits it to the control layer
  2. The control layer obtains the data submitted by the User, submits it to the business logic layer for processing, returns the queried User object, and performs page Jump
  3. The business logic layer obtains the data transmitted by the control layer and queries the user information according to the user name and password
  4. The data interaction layer queries and returns user information

Front page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>land</title>
</head>
<body>
<p>${mes}</p>
<form action="user" method="get">
    <input type="hidden" name="method" value="login">
    full name: <input type="text" name="username"> <br>
    password: <input type="password" name="pwd"> <br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

Control layer:

package com.ujiuye.controller;

import com.ujiuye.bean.User;
import com.ujiuye.service.UserService;

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;
import java.util.List;

@WebServlet("/user")
public class UserServlet  extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       
		// Get the data transmitted by the front end
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");

        // Hand over the acquired data to the business logic layer for processing
        UserService us = new UserService();
        // Call method to get result
        User user = us.getUserByNameAndPassword(username,pwd);

        // Control page Jump
        if(user != null){// Indicates that your login was successful

            resp.sendRedirect("show?method=show");
        }else{ // Login failed
            req.setAttribute("mes", "Wrong user name or password");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
   
}

Business logic layer:

package com.ujiuye.service;

import com.ujiuye.bean.User;
import com.ujiuye.dao.UserDao;

import java.util.List;

/**
 * Business logic layer
 */
public class UserService {
    /**
     * Query user information according to user name and password
     * @param username
     * @param pwd
     * @return
     */
    public User getUserByNameAndPassword(String username, String pwd) {
        if(username != null && username.trim() != "" && pwd != null && pwd.trim() != ""){
            UserDao ud = new UserDao();
            return ud.getUserByNameAndPassword(username,pwd);
        }
        return null;
    }

}

Data interaction layer

package com.ujiuye.dao;

import com.ujiuye.bean.User;
import com.ujiuye.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    // Create a database operation object and pass the data source
    private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());

    /**
     * Complete data query
     * @param username
     * @param pwd
     * @return
     */
    public User getUserByNameAndPassword(String username, String pwd) {
        String sql = "select * from user where username = ? and password = ? ";
        User user = null;
        try {
            user = queryRunner.query(sql, new BeanHandler<>(User.class), username, pwd);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
        return user;
    }

}

Display user information

Control layer code:

package com.ujiuye.controller;

import com.ujiuye.bean.User;
import com.ujiuye.service.UserService;

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;
import java.util.List;

@WebServlet("/show")
public class ShowServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // Get all user information and pass it to show JSP page
        UserService userService = new UserService();
        List<User> userList =  userService.selectAllUser();

        // Page Jump, consideration when selecting scope object 1 Whether the data can be obtained 2 Memory utilization
        req.setAttribute("ulist",userList);
        req.getRequestDispatcher("show.jsp").forward(req,resp);

    }
}

Business logic layer:

 /**
     * Get all user information
     * @return User information list
     */
    public List<User> selectAllUser() {
        UserDao ud = new UserDao();
        return ud.selectAllUser();
    }

Data interaction layer:

 public List<User> selectAllUser() {
        String sql = "select * from user";
        List<User> uli = null;
        try {
            uli = queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return uli;
    }

Front page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1" cellspacing="0" width="600px" align="center">
    <tr>
        <th>number</th>
        <th>user name</th>
        <th>password</th>
        <th>full name</th>
        <th>Telephone</th>
        <th>birthday</th>
        <th>operation</th>
    </tr>

    <c:forEach items="${ulist}" var="user">
        <tr>
            <td>${user.uid}</td>
            <td>${user.username}</td>
            <td>${user.password}</td>
            <td>${user.name}</td>
            <td>${user.telephone}</td>
            <td>${user.birthday}</td>
            <td><a href="user?uid=${user.uid}">delete</a></td>
        </tr>
    </c:forEach>

</table>
</body>
</html>

Control layer integration code example:

package com.ujiuye.controller;

import com.ujiuye.bean.User;
import com.ujiuye.service.UserService;

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;
import java.util.List;

@WebServlet({"/user","/show"})
public class UserServlet  extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
        switch (method){
            case "login": login(req,resp); break; // User login
            case "show": show(req,resp); break; // User login
        }

//        if(uri.contains("/usermanager_war_exploded/user")){
//            login(req,resp); //  User login
//        }else if(uri.contains("/usermanager_war_exploded/show")){
//           show(req,resp);
//        }



    }

    private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("show");
        // Get all user information and pass it to show JSP page
        UserService userService = new UserService();
        List<User> userList =  userService.selectAllUser();

        // Page Jump, consideration when selecting scope object 1 Whether the data can be obtained 2 Memory utilization
        req.setAttribute("ulist",userList);
        req.getRequestDispatcher("show.jsp").forward(req,resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        // Get the data transmitted by the front end
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");

        // Hand over the acquired data to the business logic layer for processing
        UserService us = new UserService();
        // Call method to get result
        User user = us.getUserByNameAndPassword(username,pwd);

        // Control page Jump
        if(user != null){// Indicates that your login was successful

            resp.sendRedirect("show?method=show");
        }else{ // Login failed
            req.setAttribute("mes", "Wrong user name or password");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}

hod");
String uri = req.getRequestURI();
System.out.println("uri = " + uri);
switch (method){
case “login”: login(req,resp); break; // User login
case “show”: show(req,resp); break; // User login
}

// if(uri.contains("/usermanager_war_exploded/user")){
// login(req,resp); // User login
// }else if(uri.contains("/usermanager_war_exploded/show")){
// show(req,resp);
// }

}

private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("show");
    // Get all user information and pass it to show JSP page
    UserService userService = new UserService();
    List<User> userList =  userService.selectAllUser();

    // Page Jump, consideration when selecting scope object 1 Whether the data can be obtained 2 Memory utilization
    req.setAttribute("ulist",userList);
    req.getRequestDispatcher("show.jsp").forward(req,resp);
}

private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Get the data transmitted by the front end
    String username = req.getParameter("username");
    String pwd = req.getParameter("pwd");

    // Hand over the acquired data to the business logic layer for processing
    UserService us = new UserService();
    // Call method to get result
    User user = us.getUserByNameAndPassword(username,pwd);

    // Control page Jump
    if(user != null){// Indicates that your login was successful

        resp.sendRedirect("show?method=show");
    }else{ // Login failed
        req.setAttribute("mes", "Wrong user name or password");
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }
}

}

Tags: Java Web Development

Posted by matthiasone on Wed, 04 May 2022 16:21:55 +0300