Servlet of Jsp and Servlet

1, Servlet basic usage

  servlet is a Java application running on the web server. It is written in Java language and has the advantages of Java language. The difference between servlet and Java program is that servlet object mainly encapsulates the processing of HTTP requests, and its operation needs the support of servlet container (tomcat). Servlet application plays a very important role in Java Web application, and it is also very powerful in the processing function of web requests.

   the creation of Servlet is very simple. Create a common Java class to make this class inherit the HttpServlet class, rewrite the doGet() or doPost() method of the parent class as needed, and then register the Servlet object by manually configuring the web.xml file to tell the Web container which request calls which Servlet object for processing.

   the Servlet configuration is contained in the web.xml file, which is mainly set through the following two steps.

<!--statement Servlet-->
<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>cn.hxzy.MyServlet</servlet-class>
</servlet>
<!--mapping Servlet-->
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/my</url-pattern>
</servlet-mapping>

   declare a Servlet object. In the web.xml file, declare a Servlet object through the < Servlet > tag. There are two main sub elements under this tag, namely < Servlet name > and < Servlet class >, where the < Servlet name > element is used to specify the name of the Servlet, which can be a user-defined name< The Servlet class > element is used to specify the full location of the Servlet object, including the package name and class name of the Servlet object.

    after declaring the Servlet object in the web.xml file, you need to map the URL to access the Servlet. This operation is configured with the < Servlet mapping > tag< The Servlet mapping > tag contains two sub elements, < Servlet name > and < URL pattem >. The < Servlet name > element corresponds to the < Servlet name > element in the < servletl > tag and cannot be named arbitrarily< The URL patterm > element is used to map access URLs.

  case: implement the login process of jsp page with Servlet

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(rep, resp);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");        
        if ("admin".equals(name) && "123".equals(pwd)){
            request.getSession().setAttribute("user",login);
            response.sendRedirect("index.jsp");
        }else {
            response.sendRedirect("login.jsp");
        }
    }
}

  case: Servlet responds to HTML string directly to browser

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.io.PrintWriter;

public class TestServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        writer.write("<h1>hello world!</h1>");
    }
}

   Servlet is a Java program running on the Web application server using the Java Servlet interface. Its function is very powerful. It can not only process the business logic in HTTP requests, but also output HTML code to display the specified page. JSP is a dynamic Web page technology based on Servlet specification. In JSP pages, business logic can also be written to process HTTP requests, and pages can also be edited through HTML code. In terms of implementation function, Servlet and JSP seem to be the same, but there are some differences in essence, which are mainly reflected in the following aspects.

   1. Different roles: JSP pages can coexist HTML code and Java code, while Servlet needs to play an intermediate role between customer request and business processing. Only by calling fixed methods can dynamic content be output as static HTML. Therefore, JSP has the role of display layer.
   2. Different programming methods: there are great differences between Servlet and JSP in programming methods. Using Servlet to develop Web applications needs to follow Java standards, while JSP needs to follow certain script language specifications.
   3.Servlet needs to be compiled and run: the servlet can run only after the Java compiler is compiled. If the servlet is not recompiled after writing or modification, it cannot run in the Web container. On the contrary, JSP is managed by JSP Container, and its editing process is automatically compiled by JSP Container. Therefore, no matter whether the JSP file is created or modified, it can run without compiling it.
   4. Different speeds: because JSP pages are managed by JSP Container, JSP Container will automatically compile them every time dynamic JSP pages with different contents are executed. Therefore, its efficiency is lower than that of Servlet. After the Servlet is compiled, it does not need to be compiled again. It can directly obtain and output dynamic content. When the content in the JSP page does not change, the JSP Container will not compile the JSP again after the compilation of the JSP page is completed.

   note: if Chinese garbled code occurs in the response process, you need to set response.setCharacterEncoding("UTF-8"); And response.setContentType("text/html;charset=UTF-8"); For the request method, click the a tab to jump, or directly enter the address in the browser address bar and press enter. Such a request method is get request. A post request is usually submitted by a form, and the form specifies that the request method is post or ajax request.

practice:

1. Registration verification exercise: create project demo3 and write a registration module. The registration page register.jsp contains username, password, repsssword and telephone. After submitting, go to the servlet. The servlet determines whether the password and repassword are the same and the phone number is 11 digits. If they all meet the requirements, "registration succeeded" will be displayed. Otherwise, "the password is inconsistent with the confirmed password or the mobile phone number is illegal" will be displayed.

Reference code:

register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>register</title>
</head>
<body>
<form action="register" method="post">
    <input name="username">
    <br>
    <input name="password">
    <br>
    <input name="repassword">
    <br>
    <input name="telephone">
    <br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

RegisterServlet

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String telephone = request.getParameter("telephone");
        if (repassword != null && repassword.equals(password) && telephone != null && telephone.length() == 11) {
            response.getWriter().write("<h1>login was successful</h1>");
            return;
        }
        response.getWriter().write("<h1>The password is inconsistent with the confirmed password or the mobile phone number is illegal</h1>");
    }
}

2, Redirection and forwarding

   redirection means that the currently accessed resource does not have permission. After the operation is successful, the browser needs to jump to the specified jsp or servlet. This jump is because the background returns a response header with code 302 and tells the browser the jump address in the response header. Browser active jump. Redirection can be done using the following syntax:

response.sendRedirect("login.jsp");

   forwarding describes the relationship between jsp and servlet. The logic of forwarding is as follows. When we visit a jsp page, there is no relevant data display on the page, so our request points to the address of the servlet. The servlet calls relevant components to obtain data, and then stores the data in the request, The jsp page renders the data in the request into an html page with data. This is the programming idea of high cohesion and low coupling proposed by java. Request forwarding can be completed using the following syntax:

request.getRequestDispatcher("index.jsp").forward(request, response);

Note: the browser address does not change during forwarding. During redirection, the browser sends two requests, so it cannot store data in the request.

Case: forwarding value

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;

public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("id", 12);
        request.setAttribute("name", "Zhang San");
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>INDEX</title>
</head>
<body>
<p>id: <%=request.getAttribute("id")%>
</p>
<p>name: ${name}
</p>
</body>
</html>

Case: login form backfill

login.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>LOGIN</title>
</head>
<body>
<form action="login">
    <input name="name" type="text"
           value="${name}">
    <input name="password" type="text"
           value="<%=request.getAttribute("password")==null?"":request.getAttribute("password")%>">
    <input type="submit" value="Submit">
</form>
</body>
</html>

servlet

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;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        if ("123".equals(password)) {
            request.getSession().setAttribute("userInfo", name);
            response.sendRedirect("index.jsp");
            return;
        }
        request.setAttribute("name", name);
        request.setAttribute("password", password);
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
}

practice:

1. Create project demo4, write an index.jsp page, enter the radius of the circle and submit it to a Servlet with a post request. The Servlet determines the radius. If it is null or < = 0, it redirects to the index.jsp page. If it is > 0, it forwards to the success.jsp page and displays its area and perimeter.

Reference code:

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home page</title>
</head>
<body>
<form action="check" method="post">
    <input name="number">
    <input type="submit" value="Submit">
</form>
</body>
</html>

CheckServlet

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/check")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String number = request.getParameter("number");
        if (number != null && number != "") {
            try {              
                int i = Integer.parseInt(number);
                if (i > 0) {
                    request.setAttribute("area", Math.PI * i * i);
                    request.setAttribute("perimeter", Math.PI * i * 2);
                    request.getRequestDispatcher("success.jsp").forward(request, response);
                    return;
                }                
            } catch (Exception e) {
            }
        }
        response.sendRedirect("index.jsp");
    }
}

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Calculation succeeded</title>
</head>
<body>
<p>Perimeter:<%=request.getAttribute("perimeter")%></p>
<p>Perimeter: ${perimeter}</p>
<p>the measure of area: ${area}</p>
</body>
</html>

3, Lifecycle and creation timing

  the Servlet life cycle can be defined as the whole process from creation to destruction. The following is the procedure followed by the Servlet:

After the initialization of 1.Servlet, the init () method is called.
   2.Servlet calls doGet() or doPost() method to process the client's request.
The destroy() method is called before 3.Servlet destroys.
   4. Finally, the Servlet is garbage collected by the JVM garbage collector.
  in some extracurricular books, service() is usually used to respond to requests. service() is the most important method in GenericServlet class. Every time a client sends a request to the server, the server will call this method. Programmers override this method and add their own code to this method to realize the response to customers. The method parameters and usage of service() are the same as doGet() and doPost().

  note: when inheriting the HttpServlet class and rewriting the three methods of service(), doPost() and doGet(), java will only execute the service() method, while the other two methods will not be executed.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {
    @Override//Processing get requests
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override//Processing post requests
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override//Destroy call
    public void destroy() {
        super.destroy();
    }

    @Override//Initialization call
    public void init() throws ServletException {
        super.init();
    }
}

  the above code shows the code structure of a Servlet object. The MyServlet class is declared as a Servlet object by inheriting the HttpServlet class. This class contains four methods. init() and destroy() are the methods called by Servlet initialization and end of life cycle. The other two methods are the methods provided by Servlet for processing different HTTP request types. Their functions are shown in the notes.
  when creating a Servlet, you can also specify the creation time

<servlet>
    <servlet-name>secondServlet</servlet-name>
    <servlet-class>com.hw.javaweb.SecondServlet</servlet-class>
    <!-- Can specify Servlet Time to be created -->
    <load-on-startup>2</load-on-startup>
</servlet>

  load on startup: you can specify the time when the servlet is created. If it is negative, it is created on the first request. If it is 0 or positive, the instance will be created when the current WEB application is loaded by the servlet container, and the smaller the value, the earlier it will be created.

4, Fuzzy mapping

   the same servlet can be mapped to multiple URL s, that is, the setting value of the < servlet name > sub element of multiple < servlet mapping > elements can be the registered name of the same servlet. Servlet matching is divided into exact matching and fuzzy matching.

Exact match
<servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>userAddServlet</servlet-name>
    <url-pattern>/user/add</url-pattern>
</servlet-mapping>
Fuzzy matching
<servlet-mapping>
    <servlet-name>allServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>userAllServlet</servlet-name>
    <url-pattern>/user/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>actionServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>


Reference code:

Configure mapping:

<servlet-mapping>
    <servlet-name>findById</servlet-name>
    <url-pattern>/findById/*</url-pattern>
</servlet-mapping>

Get parameters:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    String[] split = requestURI.split("/");
    request.setAttribute("id", split[split.length - 1]);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

5, Filter

   servlet filter is very similar to servlet. For program developers, the filter is essentially a Web application component on the Web application server, which is used to intercept the requests of the client (browser) and the target resource (servlet), filter these requests, and then send them to the target resource. Servlet filter can change the content of the request to meet the needs of actual development.

   the core object of Filter is placed in the javax.servlet package. Its name is Filter, which is an interface. In addition to this interface, the Filter related objects include FilterConfig (Filter configuration object) object and FilterChain (Filter transfer object). In actual development, defining the Filter object only needs to implement the Filter interface directly or indirectly.

   each Filter object must implement the Filter interface directly or indirectly. Three methods are defined in the Filter interface, namely init (Filter initialization method, which is called during Filter initialization), doFilter (Filter requests) and destroy (destroy method to release resources).

We call filterChain.doFilter(servletRequest, servletResponse) in the doFilter method. Method to complete the release operation. If there is no release operation. The client browser will not receive any data in this request, and the browser generally displays a white screen.

Case:

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().endsWith("login.jsp")) {
            filterChain.doFilter(servletRequest, servletResponse);//Release
        } else {
            response.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {
    }
}

   filters are very similar to servlets. They also need to be configured after creation. The configuration of filters is mainly divided into two steps: declaring filter objects and creating filter mappings.

<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>cn.hxzy.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

    < Filter > tag is used to declare the filter object. Two sub elements must be configured in this tag, namely, the name of the filter and the full class name of the filter, where < filter name > is used to define the name of the filter and < filter class > is used to specify the full class name of the filter< The filter mapping > tag is used to create a filter mapping. Its main function is to specify which URLs should be processed by which filter in the Web application. In the < filter mapping > tag, you need to specify the mapping between the name of the filter and the URL of the filter, where < filter name > is used to define the name of the filter and < URL pattern > is used to specify the URL of the filter application.

Case: the filter implements login interception

Delete the following code of the first page:

<%
    if (session.getAttribute("userInfo") == null) {//If there is no user information in the session
        response.sendRedirect("login.jsp");//Redirect to login.jsp
    }
%>

And use the filter to complete. Users do not log in and cannot access index.jsp

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        //Since ServletRequest is the parent class of HttpServletRequest, the URI of the request cannot be obtained, so it is cast to HttpServletRequest
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        if (request.getRequestURI().endsWith("login") || request.getRequestURI().endsWith("login.jsp")) {
            filterChain.doFilter(request,response);//Release
            return;
        }else {
            if (request.getSession().getAttribute("user")==null) {
                response.sendRedirect("login.jsp");//Not logged in, redirect to login page
            }else {
                filterChain.doFilter(request,response);//Release
                return;
            }
        }
    }

    @Override
    public void destroy() {
    }
}

Note: static resources, such as css, js, pictures, etc., need to be considered during filter configuration. Otherwise, static resources cannot be accessed.

Case: filter parameters

When configuring web.xml, add the following parameters.

<filter>
    <filter-name>FirstFilter</filter-name>
    <filter-class>cn.hxzy.FirstFilter</filter-class>
    <init-param>
        <param-name>param</param-name>
        <param-value>parameter</param-value>
    </init-param>
</filter>

Get the parameters in the filter initialization method.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String param = filterConfig.getInitParameter("param");
    System.out.println(param);
}

practice:

1. Create project demo5 to implement an IP filter, such as localhost, 127.0.0.1 and local IP address, and add the IP of the same table to the blacklist test. If it is not in the blacklist, it will be released, otherwise "insufficient permission" will pop up on the page.

2. Create project demo6 and write a filter chain. The first filter is responsible for correcting the character coding of the request and response, and the second is responsible for checking that there is a token parameter in the request address, which is an md5 encrypted 123456. Release if the requirements are met, otherwise redirect to index.jsp

Reference code

1 question

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("utf-8");
        String remoteHost = request.getRemoteHost();
        if (remoteHost.equals("192.168.8.223")) {
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('Insufficient permissions')</script>");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

Question 2 filter 1

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CharEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

Filter 2

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getParameter("token");
        if ("E10ADC3949BA59ABBE56E057F20F883E".equals(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        response.sendRedirect("index.jsp");
    }

    @Override
    public void destroy() {
    }
}

6, session timeout

  in Java Web development, session provides us with a lot of convenience. Ssession is maintained between the browser and the server. Session timeout is understood as: a session is created between the browser and the server. Because the client has not interacted with the server for a long time (30 minutes by default), the server destroys this session, and the previous session does not exist when the client interacts with the server again.
Calling invalidate() during normal use of session can also remove the current session of the client browser.

session.invalidate();

  it is generally used to destroy a session when the user exits. After clearing the session and requesting the website again, the tomcat server will allocate a new session space for the client browser, send the session ID to the client browser through the response hair and set it in the cookie.
  in actual development, you need to listen to the creation and destruction of sessions and the values stored in sessions. These functions can only be completed by listening.
  set the Session timeout, usually set Session config in web.xml

<session-config>
      <session-timeout>2</session-timeout>
</session-config>

    as above, the maximum interval between two consecutive interactions between the client and the server is 2 minutes. After 2 minutes, the value obtained by session.getAttribute() is empty.

be careful:

   1. If the access server session times out (the time interval between this access and the last access is greater than the maximum inactive interval of the session), that is, the last session ends, the server will clear the session. When the client requests again, the server will generate a new session and replace the previous sessionId. So as to ensure data security.

   2. The service cycle of the cookie recording the session is generally before the browser is closed. If the user closes the client browser, the last logged in cookie will become invalid and the session cannot be obtained. At this time, the session on the server still exists, but the client browser cannot access the space. Therefore, the common destruction methods of session are: the session.invalidate() method is called in a request cycle, and the session is destroyed after the request cycle ends; Or it is automatically destroyed after the session timeout; Or close the client browser; Restart tomcat and all sessions will be cleared.

Case: exit case

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();//Clear the session of the current client
        response.sendRedirect("login.jsp");
    }
}

7, Listener

  the Listener is used to listen for validity events of the Web container, so it is managed by the container. The Listener interface is used to listen to an executor in the container and make appropriate responses according to the needs of its application.
   there are usually eight types of monitoring in the following three categories, which monitor the changes of ServletContext (application in jsp), session and request respectively.
1.ServletContextListener: complete the overall listening of Servlet context, mainly including the following methods:

  • contextInitialized(ServletContextEvent event) listens for application context initialization.
  • contextDestroyed(ServletContextEvent event) listens that the application context is loaded, that is, it is closed.

2.ServletContextAttibuteListener: the following methods are used to listen to the content of Servlet context:

  • Attributeadded (servletcontentattributeeevent event) listens when an object is added to the scope of an application.
  • Attributereplaced (servetcontextdistributeevent event) listens when an object replaces another object in the scope of the application.
  • Attributeremoved (erlecotetattributecevent event) when the listener object is removed from the scope of the application.

3.HttpSessionListener: complete the overall Session listening, mainly including the following methods:

  • sessionCreated(HttpSessionEvent event) listens for session initialization.
  • Sessiondetoyed (htpsessionevent) listens for session destruction.

4.HttpSessionActivationListener: the following methods are used to complete Session status listening:

  • Sessiondidactivate (htpsessionevent) listens that the session becomes valid.
  • sessionWillPassivae(HttpSessionEvent event) listening session becomes invalid.

5.HttpSessionAttributeListener: the following methods are used to complete Session content listening:

  • attributeAdded(HttpSessionBindingEvent event) listening object is added to the session.
  • attributeReplaced(HttpSessionBindingEvent event) listens when an object in a session replaces another object.
  • attributeRemoved(HttpSessionBindingEvent event) when the listening object is removed from the session.

6.HttpSessionBindingListener: the following methods are used to complete Session binding listening:

  • valueBound(HttpSessionBindingEvent event) listening object is added to the session.
  • valueUnBound(HttpSessionBindingEvent event) listener object is removed from the session.

7.ServletRequestListener: the following methods are used to complete ServletRequest listening:

  • Requestinitialized (servletrequestevent event) listens that ServletRequest has been initialized.
  • requestDestroyed(ServletRequestEvent event) listens that the ServletRequest has been destroyed.

8.ServletRequestAttributeListener: the following methods are used to listen to ServletRequest content:

  • Attributeadded (servletrequestattributeevent) listening object is added to the request.
  • Attributereplaced (servletrequestattributeevent) listens for an object in the request to replace another object.
  • Attributeremoved (servletrequestattributeevent) when the listening object is removed from the request.

Listening can effectively show us the creation and destruction of various objects, content changes, etc. It also needs to be configured in web.xml like Servlet.

<listener>
    <listener-class>cn.hxzy.MyListener</listener-class>
</listener>

Case: servletContext (application in jsp) local area

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener, ServletContextAttributeListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Application initialization");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Application destruction");
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("Add key:" + event.getName());
        System.out.println("Add value:" + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
    }
}

Case: session domain

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyHttpSessionListener implements HttpSessionListener, HttpSessionAttributeListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("session establish" + event.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.println("session Destroy" + event.getSession().getId());
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("session Add key value inside" + event.getSession().getId());
        System.out.println("session Inner key" + event.getName());
        System.out.println("session Inner value" + event.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
    }
}

Case: request domain

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class MyServletRequestListener implements ServletRequestListener, ServletRequestAttributeListener {
    @Override
    public void requestDestroyed(ServletRequestEvent event) {
        System.out.println("ServletRequest Destroy");
    }

    @Override
    public void requestInitialized(ServletRequestEvent event) {
        System.out.println("ServletRequest initialization");
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent event) {
        System.out.println("to request To store data, press:" + event.getName());
        System.out.println("to request Stored data, value:" + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent event) {
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent event) {
    }
}

Case: online population statistics

@WebListener
public class SessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println(httpSessionEvent.getSession().getId());
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        if (context.getAttribute("count") != null) {
            context.setAttribute("count", (int) context.getAttribute("count") + 1);
        }else {
            context.setAttribute("count",  1);
        }

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println(httpSessionEvent.getSession().getId());
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        if (context.getAttribute("count") != null) {
            context.setAttribute("count", (int) context.getAttribute("count") - 1);
        }
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Number of people online:${count}
<a href="logout">sign out</a>
</body>
</html>

LogoutServlet

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
    }
}

practice:

1. Create project demo7 and realize the display of an online user through the listener. The user name is added to the HttpSession session when the user logs in. After logging in, jump to the online homepage and display the name of the currently logged in user, the name and number of all online people. Each user can send public messages.

Reference code:

Listening code

@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (event.getName().equals("userInfo")) {
            ServletContext context = event.getSession().getServletContext();
            Object list = context.getAttribute("userList");
            List userList;
            if (list != null) {
                userList = (List) list;
            } else {
                userList = new ArrayList();
            }
            userList.add(event.getValue());
            context.setAttribute("userList", userList);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
    }
}

Login Servlet

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        if (name != null && name != "") {
            request.getSession().setAttribute("userInfo",name);
        }
        response.sendRedirect("index.jsp");
    }
}

Send message Servlet

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String message = req.getParameter("message");
        ServletContext context = req.getSession().getServletContext();
        Object list = context.getAttribute("messageList");
        List userList;
        if (list != null) {
            userList = (List) list;
        } else {
            userList = new ArrayList();
        }
        userList.add(message);
        context.setAttribute("messageList", userList);
        resp.sendRedirect("index.jsp");
    }
}

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
<form action="login" method="post">
    <input name="name">
    <input value="Submit" type="submit">
</form>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    if (session.getAttribute("userInfo") == null) {
        response.sendRedirect("login.jsp");
    }
%>
Online users:${userList}
<br>
Chat record:${messageList}
<br>
<form method="post" action="message">
    <textarea name="message">

    </textarea>
    <input type="submit" value="send out">
</form>
</body>
</html>

8, Annotation

Adding annotations is one of the major innovations in Servlet 3.0. Using annotations eliminates the need to configure servlets or filters in the web.xml file. The new annotations in Servlet 3.0 include @ WebServlet, @ WebFilter, @ WebListener and @ WebInitParam, which are introduced below.

1.@WebServlet

Annotations are used to define Servlet components before the class declaration of the Servlet. With this annotation, there is no need to configure the Servlet in the web.xml file@ The WebServlet annotation contains the following properties:

name(String)             Equivalent to<servlet-name>,If not explicitly specified, the fully qualified name of the class
value(String[])          This attribute is equivalent to urlPatterm Properties. Two properties cannot be used at the same time
urlPatterns(String[])    Equivalent to<urlpattern>label
loadOnStartup(int)       appoint Servlet Loading order, equivalent to<load-on-startup>label
initParams(WebInitParam[])Specify a group Servlet Initialization parameter, equivalent to<init-param>label
asyncSupported(boolean)  statement Servlet Whether asynchronous operation mode is supported, equivalent to<async suppored>label
description(String)      Should Servlet Description information, equivalent to<description>label

2.@WebFilter

The annotation is used to declare the filter. The annotation will be processed by the container during deployment. The container deploys the corresponding class as the filter according to the specific attribute configuration. The annotation also contains the following attributes:

filterName(String)        Specifies the of the filter name Attribute, equivalent to<filter-name>
value(String[])           This attribute is equivalent to urlPatterns Properties. But both should not be used at the same time
urlPattemns(String[])     Specifies the of a set of filters URL Match pattern. Equivalent to<url-patterm>label
servletNames(String[])    Specify which filters will be applied to Servlet
initParams(WebInitParam]) Specify a set of filter initialization parameters, equivalent to<init-param>label
asyncSupported(Boolean)   Declare whether the filter supports asynchronous operation mode, which is equivalent to<async-supported>label
description(String)       The description information of the filter is equivalent to<description>label

3.@WebListener

This annotation is used to declare listeners and can also be used as a class that acts as a listener for various Web application events in a given Web application context. You can use @ WebListener to label a class that implements ServletContextListener, ServletContextAttributeListener, ServletRequestListener, ServletRequestAttributeListener, HttpSessionListener, and HttpSessionAttributeListener@ WebListener annotation has a value attribute, which is optional and used to describe listener information. Using this annotation eliminates the need to configure tags in the web.xml file.

4.@WebInitParam

This annotation is equivalent to the sub tag of sum in the web.xml file. This annotation is usually not used alone, but in conjunction with @ WebServlet or @ WebFilter. Its function is to specify initialization parameters for servlets or filters.

@WebServlet(value = "/my",initParams = {@WebInitParam(name = "a",value = "1")})

5.@MultipartConfig

This annotation is mainly used to obtain the Part file object from the request object. It is generally used on the Servlet for file upload.

9, File upload and download

JSP can be used with HTML form tags to allow users to upload files to the server. The uploaded file can be a text file or an image file or any document.

When uploading files, the servlet needs to be decorated with the annotation @ MultipartConfig. Meanwhile, enctype = "multipart / form data" should be specified for the previous form.

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Part file = request.getPart("file");
        if (file != null && file.getSize() != 0) {
            String fileName = file.getSubmittedFileName();
            System.out.println(fileName);
            file.write("E:/ideaProject/jsp/web/aa.png");
            response.getWriter().write("Upload succeeded");
        }
    }
}

Front end jsp

<form action="upload" enctype="multipart/form-data" method="post">
    Select file<input type="file" name="file1"/>
    <input type="submit" name="upload" value="upload"/>
</form>

For the location of file upload, it is recommended to use the relative path and mount it to tomcat, otherwise the uploaded file cannot be previewed.

File download

Generally, if the file is stored in tomcat, you can directly request the file path to obtain the file. Therefore, the files in this section are outside Tomcat and cannot be obtained directly through Tomcat. When downloading using Servlet, you should specify the ContentType of the response and the downloaded file name. The code is as follows:

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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet("/down")
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/x-msdownload");
        //The response header must be set during file download
        String fileName = "chinese.txt";
        //The file name of the browser when downloading the file
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream("C:\\ProgramData\\DisplaySessionContainer1.log");
        byte[] bytes = new byte[1024];
        int read;
        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.close();
        inputStream.close();
    }
}

practice:

1. Create project demo8 and complete the file upload function. In the actual development, the file name cannot be the same as that when uploading, otherwise it will lead to the problem of file coverage. Generally, the UUID is used to name the file, and the suffix remains unchanged. Use jquery to complete the file upload echo, and use bootstrap to beautify it.

Reference code:

html code

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Picture upload back to display</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file">
<img>
<script>
    $("#file").change(function () {
        let formData = new FormData();  //Get a FormData object
        let file = $(this).get(0).files[0];  //Get file object
        formData.append('file', file);  //Add a key value pair with the append method
        $.ajax({
            url: "upload",
            type: "post",
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                $("img").attr("src",response)
            }
        });
    });
</script>
</body>

Servlet code

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Part ap = request.getPart("file");
        if (null != ap) {
            String[] split = ap.getSubmittedFileName().split("\\.");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = uuid + "." + split[split.length - 1];
            ap.write("E://IdeaProjects/testweb/image/" + fileName);
            out.write("/image/" + fileName);
        }
    }
}

10, jsp security mode

In actual development, jsp can not be accessed directly because its page does not carry data. An empty jsp doesn't make much sense. Usually, the corresponding servlet is requested to obtain data and forward it to the corresponding jsp.

Even if the page does not need data, it can be forwarded through servlet. Another advantage of this is that the request address no longer contains the. jsp suffix. This is also a good protection for hiding the background framework.

Usually, the jsp page can be protected by putting it into the WEB-INF directory. Accessing jsp must be forwarded by servlet to access. In this way, you can verify permissions and so on in the servlet.

jsp security mode development code:
   1. Each JSP corresponds to a Servlet, such as index.jsp corresponds to IndexServlet and login.jsp corresponds to LoginServlet.
   2. Any redirection operation can not redirect jsp pages, but redirect servlets, and can not arbitrarily replace redirection with forwarding.
   3. The order of writing the system is: JSP - > Servlet - > filter. The filter cannot be written at the beginning. All requests are intercepted, resulting in inaccessible pages or servlets.
  4. You can't write a lot of java code on jsp pages. jsp is essentially understood as a component at the presentation level.

Case:

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("aa","data");
        request.getRequestDispatcher("WEB-INF/jsp/index.jsp").forward(request,response);
    }
}

Welcome page configuration: the default welcome pages in web.xml are index.html and index.jsp. If you need to configure them as Servlet addresses, you can also use the following methods. The Servlet is called automatically after the project is started or the root path of the open project.

<welcome-file-list>
    <welcome-file>index</welcome-file>
</welcome-file-list>

Chapter exercise: (dictation for 30 minutes)
1. Use secure jsp to develop user login, exit and display the current login interface.

Reference code:

IndexServlet:

@WebServlet("/index")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/index.jsp").forward(req, resp);
    }
}

LoginServlet:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if ("admin".equals(name) && "123".equals(password)) {
            req.getSession().setAttribute("userInfo", name);
            resp.sendRedirect("index");
        } else {
            req.setAttribute("name", name);
            req.setAttribute("password", password);
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
        }
    }
}

LogoutServlet

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect("index");
    }
}

MyFilter

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        if (uri.endsWith("login")) {
            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("userInfo") != null) {
            filterChain.doFilter(request, response);
            return;
        }
        response.sendRedirect("login");

    }

    @Override
    public void destroy() {

    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>welcome ${userInfo}Sign in</h1>
<a href="logout">sign out</a>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="login">
    <input name="name" value="${name}">
    <input name="password" value="${password}">
    <input type="submit" value="Submit">
</form>
</body>
</html>

Keywords: JSP servlet

Added by iantresman on Tue, 30 Nov 2021 01:24:51 +0200