Java Web Learning

Posted by mistercash60000 on Sat, 05 Mar 2022 00:38:44 +0100

Tomcat

Statement: This is the note I took when I taught you to learn Java at station b with up master Nange. I'll share it with you
Video address: https://www.bilibili.com/video/BV1NE411Q7Nx
If there is any offense, please contact me to delete

web application server: Tomcat, Jboos, Weblogic, Jetty

  • Install Tomcat
  1. Download the compressed file from the official website.

    Tomcat official website

  2. decompression

    bin: it stores the script files for starting and stopping Tomcat service on each platform.

    conf: store configuration files of various Tomcat servers.

    lib: store the jar package required by Tomcat server.

    Logs: store the running logs of Tomcat service. (like a daily diary)

    temp: temporary file for Tomcat runtime.

    webapps: store resources (Java programs) that clients are allowed to access.

    work: store the Servlet file after Tomcat converts JSP.

Servlet

  • What is a Servlet?

Servlet is the cornerstone of Java Web development. It is a platform independent server component. It runs in servlet container / Web application server / Tomcat and is responsible for communicating with the client.

Functions of Servlet:

  1. Create and return dynamic HTML pages based on customer requests.
  2. Communicate with the database.
  • How to use servlets?

    Servlet itself is a set of interfaces, javax servlet,java.lang,java.util.javax.sql. Customize a class and import interface.

  • Main methods of Servlet interface (5 methods in total):

    • public void init(ServletConfig servletConfig): create
    • Public void service (ServletRequest, ServletRequest, servletresponses: work area
    • Public void destruction(): destruction of servlet s
  • We can't access servlets. In order to ensure security, otherwise users can easily activate the logic of the server back end. Some servlet interfaces are the mapping of servlets by the server builder, which not only ensures the security of the server, but also ensures the use of some functions by users.

Recognize servlets:

Implementation of Servlet interface

package Servlet;

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

public class dome implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //Create Servlet method
    }

    @Override
    public ServletConfig getServletConfig() {
        //return
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Visited Tomcat The server");
        //Want the corresponding information from the client browser
        servletResponse.setContentType("text/html;charset=UTF-8");
        servletResponse.getWriter().write("Hello, I received the request");

    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        //Destroy
    }
}

Via web XML configuration Servlet mapping:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>dome</servlet-name>	<!-- For the following class Give a name-->	
        <servlet-class>Servlet.dome</servlet-class>	<!--corresponding src Location in -->
    </servlet>
    <servlet-mapping>	<!--mapping -->
        <servlet-name>dome</servlet-name>	<!--Mapped servlet Your name corresponds to the one above servlet-name -->
        <url-pattern>/Dome</url-pattern>	<!-- Through this URL visit servlet Mapping service -->
    </servlet-mapping>
</web-app>

The browser cannot directly access the Servlet file, but can only indirectly access the Servlet through mapping. The mapping needs to be manually configured by the developer. There are two configuration methods.

  • Configuration method based on XML file.
  • Annotation based approach
@WebServlet("/Dome")
public class dome implements Servlet {
    
}

The results of the above two configuration methods are completely consistent. Map the dome, that is, directly access the dome in the browser address bar to map to the Servlet file dome.

Life cycle of Servlet

Servlets are used to process data services. When clients access services, init() will first create a servlet object (in order to save server resources, a service will be created once); Then let service() process the data. When the user refreshes the page again, the code in service() will be executed again; Finally, when the Tomcat server is shut down, the code in destroy () will be executed and the servlet object will be destroyed.

Note: in the use of servlets, we did not create a Servlet object, but this does not mean that we did not create an object. In fact, we created it through the reflection inside Tomcat

  • Verify the reflection mechanism inside Tomcat
package Servlet;

import java.lang.reflect.Constructor;

public class verification Tomcat Reflection mechanism of {
    public static void main(String[] args) {
        String str = "Servlet.Servlet Life cycle of";
        try {
            Class servlet = Class.forName(str);
            Constructor constructor = servlet.getConstructor();
            //System.out.println(constructor);
            Object object = construct.newInstance();
            System.out.println(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package Servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/dome2")
public class Servlet Life cycle of{
    //Construction method (empty parameter)
    public Servlet Life cycle of(){
        System.out.println("Servlet Was created");
    }
//    @Override
//    public void init(ServletConfig servletConfig) throws ServletException {
//        System.out.println("initialize the Servlet...);
//    }
//
//    @Override
//    public ServletConfig getServletConfig() {
//        return null;
//    }
//
//    @Override
//    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
//        System. out. Println ("business method of servlet.....");
//    }
//
//    @Override
//    public String getServletInfo() {
//        return null;
//    }
//
//    @Override
//    public void destroy() {
//        System.out.println("release Servlet resources...");
//    }
}
  1. When the browser accesses the Servlet, Tomcat will query whether the instantiated object of the current Servlet exists. If it does not exist, it will dynamically create the object through the reflection mechanism.
  2. Call the init method to complete the initialization operation.
  3. Call the service method to complete the business logic operation.
  4. When Tomcat is closed, the destroy method will be called to release the resources occupied by the current object.

Life cycle methods of Servlet: parameterless constructor, init, service, destroy

  1. The parameterless constructor is called only once to create an object.
  2. init is called only once to initialize the object.
  3. service calls N times to execute business methods.
  4. destory is called only once to unload the object.

ServletConfig

This interface is used to describe the basic information of Servlet.

Method namedescribe
getInitParameter(String key)Get the value of init parameter (Web.xml)
getInitParameterNames()Returns the name values of all initparamters, which are generally used as traversal initialization parameters
getServletContext()Return the ServletContext object, which is the context of the Servlet and the manager of the whole Servlet.
getServletName()Returns the name of the Servlet, the full class name (the name with the package name)

Differences between ServletConfig and ServletContext:

ServletConfig works with a Servlet instance. Each Servlet has a corresponding ServletConfig. ServletContext works with the whole Web application. A Web application corresponds to a ServletContext, and multiple Servlet instances correspond to a ServletConfig.

Interface introduction

ServletConfig interface:

[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-I8n8VvkK-1616141272360)(E:\Java notes \ JavaWeb\imgs\ServletConfig.png)]

ServletContext interface:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package javax.servlet;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.descriptor.JspConfigDescriptor;

public interface ServletContext {
    String TEMPDIR = "javax.servlet.context.tempdir";
    String ORDERED_LIBS = "javax.servlet.context.orderedLibs";

    String getContextPath();

    ServletContext getContext(String var1);

    int getMajorVersion();

    int getMinorVersion();

    int getEffectiveMajorVersion();

    int getEffectiveMinorVersion();

    String getMimeType(String var1);

    Set<String> getResourcePaths(String var1);

    URL getResource(String var1) throws MalformedURLException;

    InputStream getResourceAsStream(String var1);

    RequestDispatcher getRequestDispatcher(String var1);

    RequestDispatcher getNamedDispatcher(String var1);

    /** @deprecated */
    Servlet getServlet(String var1) throws ServletException;

    /** @deprecated */
    Enumeration<Servlet> getServlets();

    /** @deprecated */
    Enumeration<String> getServletNames();

    void log(String var1);

    /** @deprecated */
    void log(Exception var1, String var2);

    void log(String var1, Throwable var2);

    String getRealPath(String var1);

    String getServerInfo();

    String getInitParameter(String var1);

    Enumeration<String> getInitParameterNames();

    boolean setInitParameter(String var1, String var2);

    Object getAttribute(String var1);

    Enumeration<String> getAttributeNames();

    void setAttribute(String var1, Object var2);

    void removeAttribute(String var1);

    String getServletContextName();

    Dynamic addServlet(String var1, String var2);

    Dynamic addServlet(String var1, Servlet var2);

    Dynamic addServlet(String var1, Class<? extends Servlet> var2);

    <T extends Servlet> T createServlet(Class<T> var1) throws ServletException;

    ServletRegistration getServletRegistration(String var1);

    Map<String, ? extends ServletRegistration> getServletRegistrations();

    javax.servlet.FilterRegistration.Dynamic addFilter(String var1, String var2);

    javax.servlet.FilterRegistration.Dynamic addFilter(String var1, Filter var2);

    javax.servlet.FilterRegistration.Dynamic addFilter(String var1, Class<? extends Filter> var2);

    <T extends Filter> T createFilter(Class<T> var1) throws ServletException;

    FilterRegistration getFilterRegistration(String var1);

    Map<String, ? extends FilterRegistration> getFilterRegistrations();

    SessionCookieConfig getSessionCookieConfig();

    void setSessionTrackingModes(Set<SessionTrackingMode> var1);

    Set<SessionTrackingMode> getDefaultSessionTrackingModes();

    Set<SessionTrackingMode> getEffectiveSessionTrackingModes();

    void addListener(String var1);

    <T extends EventListener> void addListener(T var1);

    void addListener(Class<? extends EventListener> var1);

    <T extends EventListener> T createListener(Class<T> var1) throws ServletException;

    JspConfigDescriptor getJspConfigDescriptor();

    ClassLoader getClassLoader();

    void declareRoles(String... var1);

    String getVirtualServerName();
}

Test procedure:

package Servlet;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;

public class know ServletConfig Interface implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //initialization
        System.out.println(servletConfig.getServletName());     //Returns the name of the Servlet, the full class name (the name with the package name)
        String username = servletConfig.getInitParameter("username");
        System.out.println(username);
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames(); //Returns the (set) set of initialization data (unordered)
        while (initParameterNames.hasMoreElements()){
            String element = initParameterNames.nextElement();
            String s = servletConfig.getInitParameter(element);
            System.out.println(element);
            System.out.println(s);
        }
        ServletContext servletContext = servletConfig.getServletContext();  //The most important method
//        Returns a Servlet context object, which is equivalent to the administrator object of the Servlet

        String contextPath = servletContext.getContextPath();//Returns the virtual path of the project
        System.out.println(contextPath);
        String servletContextName = servletContext.getServletContextName();
        System.out.println(servletContextName);
    }

    @Override
    public ServletConfig getServletConfig() {
        //Returns the ServletConfig object
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //Business processing method
    }

    @Override
    public String getServletInfo() {
        //Returns information about the Servlet object
        return null;
    }

    @Override
    public void destroy() {
        //Destruction procedure
    }
}

Hierarchy of servlets

Servlet (Interface) – "genericservlet (object) –" httpservlet (object)

There are many types of HTTP requests. There are four commonly used:

GET read

POST save

PUT modification

DELETE delete

GenericServlet implements the Servlet interface and shields its subclasses from infrequent methods. Subclass methods only need to rewrite the service method.

HttpServlet inherits GenericServlet and performs distribution processing according to the request type. GET enters doGET method and POST enters doPOST method.

The Servlet class customized by the developer only needs to inherit HttpServlet and re doGET and doPOST.

JSP

JSP is essentially a Servlet. JSP is mainly responsible for interacting with users and presenting the final interface to users. It is a mixed file of HTML+JS+CSS+Java.

When the server receives a request with JSP suffix, it will hand over the request to the JSP engine for processing. When each JSP page is accessed for the first time, the JSP engine will translate it into a Servlet file, and then the Web container will call the Servlet to complete the response.

Simply from the perspective of development, JSP is to embed Java programs in HTML

There are three specific embedding methods:

  1. JSP script

    <% Java code %>
    
  2. JSP declaration: defining Java methods

    <%!
    	statement Java method
    %>
    
  3. JSP expression: output Java objects directly to HTML pages

    <%=java variable%>
    

    Example code:

    <%
        String str = "Hello World";
        System.out.println(str);
      %>
    
    <%!
      //Declare java methods
      public String test(){
        return "Hello JSP";
      }
    %>
      <%
        System.out.println(test());
      %>
    <%=test()%>
    

    JSP small example:

    <%@ page import="java.util.List" %>
    <%@ page import="java.util.ArrayList" %><%--
      Created by IntelliJ IDEA.
      User: caishenao
      Date: 2021/2/10
      Time: 17:25
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>JSP demonstration</title>
    </head>
    <body>
        <%
            ArrayList<String> name = new ArrayList<>();
            ArrayList<Integer> age = new ArrayList<>();
            name.add("Zhang San");
            name.add("Li Si");
            name.add("Wang Wu");
            age.add(20);
            age.add(21);
            age.add(22);
        %>
        <table border="1px">
            <tr>
                <th>full name</th>
                <th>Age</th>
            </tr>
            <%
                for (int i = 0;i<name.size();i++){
            %>
            <tr>
                <td>
                    <%=name.get(i)%>
                </td>
                <td>
                    <%=age.get(i)%>
                </td>
            </tr>
            <%
                }
            %>
        </table>
    </body>
    </html>
    

JSP built-in objects (9)

  1. Request: indicates a request, HttpServletRequest.

  2. Response: indicates a response, HttpServletResponse.

  3. Pagecontext: page context, get page information, pagecontext.

  4. Session: represents a session, saving user information, HttpSession.

  5. Application: it refers to the current Web application, global object, save the information shared by all users, and ServletContext.

  6. config: the ServletContfig object of the Servlet corresponding to the current JSP to obtain the information of the current Servlet.

  7. out: want the browser to output JSPWriter.

  8. page: the Servlet object and Servlet corresponding to the current JSP.

  9. Exception: indicates the exception of the JSP page.

Commonly used are: request, response, session, application and pageContext

Common methods of request:

  1. String getParameter(String key) gets the parameters from the client.

  2. void setAttribute(String key,Object value) saves data in the form of key value pairs.

  3. Object getArrtribute(String key) retrieves value through key.

  4. RequestDispatcher getRequestDispatcher(String path) returns a RequestDispatcher object whose forward method is used for request forwarding.

  5. String[] getParameterValues() gets multiple parameters with the same name from the client.

  6. void setCharacterEncoding(String charset) specifies the encoding for each request.

HTTP request status code:

200: normal access

404: resource not found

400: request type mismatch

500: exception thrown by Java program

Common methods of response:

  1. sendRedirect(String path) redirection, jump between pages.

    The difference between forwarding getRequestDispatcher and redirection:

    Forwarding is to pass the same request to the next page. Redirection is to create a new request and pass it to the next page. The previous request ends the declaration cycle.

    Forwarding: when the same request is transmitted between servers, the address bar remains unchanged, which is also called server jump.

    Redirection: the client sends a new request to access the target resource after the jump. The address bar changes, which is also called client jump.

    If the value needs to be transmitted between two pages through request, forwarding must be used instead of redirection.

    The user logs in. If the user name and password are correct, jump to the home page (forwarding) and display the user name. Otherwise, return to the login page (redirection).

Session

User session

The server cannot recognize the source of each HTTP request (I don't know which terminal it comes from). It will only receive a request signal, so there is a problem: to send the user's response to others, there must be a technology to let the server know where the request comes from. This is session technology.

Session: it refers to a series of continuous request and response processes between the client and the server, from opening the browser for operation to closing the browser.

Session state: refers to the state information generated during the re session between the server and the browser. With the help of session state, the server can associate a series of requests and responses belonging to synonymous sessions.

There are two ways to implement a session:

  • Session

  • Cookie

All requests belonging to the same session have the same identifier, sessionID

Common methods of session:

String getId() get sessionID

Void setmaxinactivitinterval (int interval) sets the expiration time of the session, in seconds

int getMaxInactiveInterval() gets the expiration time of the current session

void invalidate() sets the session to expire immediately

void setAttribute(String key,Object value) stores data in the form of key value pairs

Object getAttribute(String key) gets the corresponding data through the key

void removeAttribute(String key) deletes the corresponding data through the key

# Cookie

A cookie is a small text file attached to the browser by the server in the HTTP response. Once the browser saves a cookie, it will be delivered in the subsequent request and response process, so that the data interaction between the client and the server can be completed through the cookie carrier.

Cookie class

  • Create Cookie

    Cookie cookie = new Cookie("name","Zhang San");
    response.addCookie(cookie);
    
  • Read cookies

    Cookie[] cookies = request.getCookies();
    for (int i = 0;i<cookies.length;i++){
        out.write(cookies[i].getName()+":" +cookies[i].getValue()+"<br/>");
    }
    

Common methods of cookies

void setMaxAge(int age) / / set the effective time of the Cookie, in seconds

int getMaxAge() / / get the effective time of the Cookie

String getName() / / get the name of the Cookie

String getValue() / / get the value of the Cookie

The difference between Session and Cookie

Session: saved on the server

The saved data is of type Object

Is destroyed as the session ends

Cookie: saved in browser

The saved data is String

It can be saved in the browser for a long time, independent of the session

Save unimportant information

Store user information:

session: setAttribute(name, "admin") save

getAtrribute(name)

Declaration cycle: Server: the WEB application will be destroyed upon restart, and client: it will be destroyed as long as the browser is closed.

Log out: session invalidate()

Cookie: new Cookie(name, "admin") creation

​ response.addCookie() save

Cookie[] cookies = request.getCookies();
for (int i = 0;i<cookies.length;i++){
    out.write(cookies[i].getName()+":" +cookies[i].getValue()+"<br/>");
}

Take

Declaration cycle: it will not be destroyed with the restart of the server. The client: by default, it will be destroyed as long as the browser is closed. We set the validity period through the setMaxAge() method. Once the validity period is set, it will not be destroyed with the shutdown of the browser, but determined by the set time.

Log out: setMaxAge(0)

JSP built-in object scope

4

page,request,session,application

setAttribute,getAttribute

page scope: the corresponding built-in object is pageContext.

Request scope: the corresponding built-in object is request.

Session scope: the corresponding built-in object is session.

Application scope: the corresponding built-in object is application.

page is valid in one request.

Session is valid within a session.

Application corresponds to the whole web application.

  • Website traffic statistics
<%
    //First get the count variable from the server
    Integer count = (Integer) application.getAttribute("count");
    if (count == null){
        count = 0;
        count++;
        application.setAttribute("count",count);
    }else {
        count++;
        application.setAttribute("count",count);
    }
%>
<h1 style="text-align: center">Small cases of statistical visits</h1>
<%=count%>

EL expression

Expression Language is an Expression Language that replaces the complex coding of data access in JSP pages. It can easily take out the data saved in domain objects (pageContext, request, session and application). On the premise, setAttribute must be set first. El is equivalent to simplifying getAttribute

The ${variable name} variable name is the key value corresponding to setAttribute.

1. Default search order for domain objects in EL 4:

pageContext->request->session->application

Search in the above order. If it is found, it will return immediately. If it cannot be found in the application, it will return null

2. Specify the scope to find

pageContext: ${pageScope.name}

request: ${requestScope.name}

session: ${sessionScope.name}

application: ${applicationScope.name}

Data cascade:

${user.["id"]}

EL Execute expression

${num1&&num2}

&& || ! < > <= >= ==



&& and

|| or

!  not

== eq

!= ne

< lt

> gt
<= le
>= ge
empty Variable is null,The length of the is 0 String,size Collection with 0

JSTL

JSP Standard Tag Library JSP standard tag library is a series of tags provided by JSP for developers. Using these tags can complete some logical processing, such as looping through the collection, making the code more concise and eliminating the interspersed situation of JSP scripts.

In actual development, EL and JSTL are used together. JSTL focuses on logic processing, and EL is responsible for displaying data.

Use of JSTL

  1. The jar package needs to be imported

    Storage location: Web Info - > Lib

  2. Import the JSTL tag library at the beginning of the JSP page

    <%@ taglib prefix="c" uri="http://java. sun. com/jsp/jstl/core" %> 	// introduce
    
  3. Use where needed

<c:forEach items="${requestScope.students}" var="user">
    <tr>
        <td>${user.name}</td>
        <td>${user.age}</td>
        <td>${user.sex}</td>
        <td>${user.height}</td>
    </tr>
</c:forEach>

Advantages of JSTL

  1. Provides a unified label
  2. It can be used to write various dynamic functions

Common tags in core tag library:

set,out,remove,catch

set: adds data to the domain object

<%
	request.setAttribute(key,value);
%>


<c:set var="name" value="tom" scope="request"></c:set>	//Store a string into the request field
<p style="color: green">${requestScope.name}</p> <!-- Read data in domain--%>


<%
        Student student = new Student("Zhang San",20,'male',180);
        request.setAttribute("student",student);
%>
    <p style="color: red">
        full name: ${requestScope.student.name}<br>
        Age: ${requestScope.student.age}<br>
        Gender: ${requestScope.student.sex}<br>
        Height: ${requestScope.student.height}<br>
    </p>
    <hr>
	//Change data in objects in a domain
    <c:set target="${requestScope.student}" property="name" value="Li Si"></c:set>
    <p style="color: green">
        full name: ${requestScope.student.name}<br>
        Age: ${requestScope.student.age}<br>
        Gender: ${requestScope.student.sex}<br>
        Height: ${requestScope.student.height}<br>
    </p>

out: output the data in the domain object

<c:set var = "name" value="tom"></c:set>
<c:out value="${name}" default="Undefined"></c:out>	//When you are not sure whether there is the desired data in the field, you can specify the information to be output in space time

remove: deletes the data in the domain object

<c:remove var = "name" scope = "page"></c:remove>
<c:out value="${name}" default="Undefined"></c:out>

Catch: catch exception

<c:catch var="error">		//With tay() {...} catch {...}
	<%
		int a = 10/0;
	%>
</c:catch>
${error}

<c:catch var = "error">
	//Write a statement with possible errors in the tag. When an error occurs, throw the error information to the variable error
</c:catch>		
${error}		//Print error messages

Condition label: if choose

<c:set var="num1" value="1"></c:set>
<c:set var="num2" value="2"></c:set>
<c:if test="${num1 > num2}">num1 than num2 large</c:if>
<c:if test="${num1 < num2}">num2 than num1 large</c:if>

< C: if test = "judge" > Data judged as true to be displayed < / C: if >

Judgment can be combined with EL expression and judged as Boolean value

<c:choose>
    <c:when test="${num1 > num2}">ok</c:when>
    <c:otherwise>fail</c:otherwise>
</c:choose>

Iteration label: forEach

<c:forEach item="${list}" var ="str" begin="2" end="3" step="2" varStaus="sta">
	${sta.count},${str}<br/>	
</c:forEach>

Of which:

item: is the array or collection in the field to be obtained.

var: is a temporary variable

begin: the position where the iteration starts. It starts from 0 by default.

end: the non position of the iteration. All iterations are selected by default.

Step: is the number of steps in each iteration. The default value is 1. It is the same as i + + or i = i+step.

varStaus: stores the number of the current iteration, which is equivalent to variable i.

Format labels commonly used in label Library:

fmt time and digital tag library learning:

<%
    request.setAttribute("date",new Date());
%>
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd hh:mm:ss"></fmt:formatDate>
<fmt:formatNumber var="32145.23434" maxIntegerDigits="2" maxFractionDigits="3"></fmt:formatNumber>

Function tag library:

<%
	request.setAttribute("info","Java,C");
%>
${fn:contains(info,"Python")}<br/>
${fn:startsWith(info,"Java")}<br/>
${fn:endsWith(info,"C")}<br/>
${fn:indexOf(info,"va")}<br/>
${fn:replace(info,"C","Python")}<br/>
${fn:substring(info,2,3)}<br/>
${fn:split(info,",")[0]}-${fn:split(info,",")[1]}

filter

Filter: filter requests and process request information

(content of Spring Boot) fuse: Hystrxis

Function:

  1. Used to intercept incoming requests and concatenated corresponding requests.
  2. Modify or process the data flow being exchanged between the client and the server in some way.

How to use?

Similar to using servlets, Filter is an interface provided by Java Web. Developers only need to customize a class and implement the interface.

Filter is an interface. When you need to use it, you can implement the filter interface.

package javax.servlet;

import java.io.IOException;

public interface Filter {
    void init(FilterConfig var1) throws ServletException;

    void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException;

    void destroy();
}

Note: the above code is implemented in Java7. The init() and destroy() methods are not preceded by permission modifiers. The default modifier is introduced in the implementation of Java8. This modifier indicates that the method has been implemented and does not have to be implemented

Web. Configure Filter in XML

<filter>
	<filter-name>charcater</filter-name>
	<filter-class>com.southwind.filter.CharacterFiletr</filter-class>
</filter>
<filetr-mapping>
	<filetr-name>charcater</filter-name>
	<url-pattern>/login</url-pattern>
	<url-pattern>test</url-pattern>
</filetr-mapping>

Note: after processing the business logic in the doFilter method, you must add filterchain daFilter(servletRequest servletResponse); Otherwise, the request / response cannot be passed back and remains in the filter.

Life cycle of filter

When Tomcat starts, it calls the parameterless constructor of Filter through the reflection mechanism to create an instantiated object, and calls the init method to initialize. The doFilter method is called many times. When Tomcat service is closed, it calls destroy to destroy the Filter object.

Parameterless constructor: called only once when Tomcat starts (Filter must be configured)

init method: calls only once, and when the instantiated object of Filter is created, it is called.

doFilter: call multiple times, and the business logic accessing the Filter is written in the Filter

Destruction: only called once, when Tomcat is closed.

Configure multiple filters at the same time. The calling order of Filter is determined by web The configuration order in XML is determined. The configuration written above is called first because web XML is read from top to bottom

You can also simplify the web by annotation Configuration in XML

Use scenarios of Filter in actual development:

1. Unified handling of Chinese garbled code.
2. Screen sensitive words.
3. Control access to resources.

1 2. Uniformly deal with Chinese random codes and filter sensitive words:

package cn.cai.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/login")
public class Filter Processing character set implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //The Filter function will be initialized only once when the function is called
        System.out.println("User accessed init program");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //The function implemented by the main function of the listener. The function will be called once the user accesses it
        System.out.println("Filter through filter");
        //Set character set
        servletRequest.setCharacterEncoding("UTF-8");
        //Get the submitted data of name
        String name = servletRequest.getParameter("name");
        //Replace all sensitive words in the data
        String s = name.replaceAll("Sensitive words", "***");
        //Print
        System.out.println(s);
        //Store the processed data into the servletRequest object
        servletRequest.setAttribute("name",s);
        System.out.println("obtain name");
        //Listener release
        filterChain.doFilter(servletRequest,servletResponse);
//        System.out.println("will this line of code be executed after release?");
    }

    @Override
    public void destroy() {
        //Destroy the program. This function will be executed when the Tomcat server stops running
        System.out.println("Filter Destroyed");
    }
}

File upload and download

upload

  • jsp
  1. The type of input is set to file
  2. The method of the form is set to post, and the get request will pass the file name to
  3. The entype of the form is set to multpart / form data, and the data is transmitted in binary form
  • Servlet

The fileuoload component can parse all request information into FileIteam objects. You can

Use the fileupload component to upload files

  • fileupload core API

References:

File address

  1. DiskFileItemFactory constructor
    1. DiskFileItemFactory() / / use the default configuration
    2. DiskFileItemFactory(int sizeThreshold,File repository)
      1. sizeThreshold memory buffer cannot be set too large. Otherwise, the JVM will crash
      2. repository temporary file directory
  2. ServletFileUpload
    1. isMutipartContent(request) / / judge whether the uploaded form is multipart / form data type true/false
    2. parseRequest(request) / / parse the request, and the return value is of type List
    3. setFileSizeMax(long) / / the maximum value of a single file uploaded is handled by throwing an exception inside fileupload. If the file size exceeds the limit, you can catch this exception and prompt the user
    4. setSizeMax(long) / / the maximum number of uploaded files
    5. setHeaderEncoding(String) / / set the encoding format
    6. setProgressListener(ProgressListener) / / set listener, which can be used to make progress bar

code

  • Servlet:
package cn.cai;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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

@WebServlet("/upload")
public class uploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //Gets the input stream of data submitted by the client
//        ServletInputStream inputStream = req.getInputStream();
        InputStream in = null;
        OutputStream out = null;
        try {
            //Create parser factory with default configuration
            DiskFileItemFactory factory = new DiskFileItemFactory();//Empty parameter structure
            //Get parser
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            //Judge whether the uploaded file is multiparty / form data type
            if(!upload.isMultipartContent(req)){
                return;
            }
            //Parsing the input stream of request
            List<FileItem> fileItemList = upload.parseRequest(req);
            //Iterative set
            for (FileItem fileItem: fileItemList) {
                if (fileItem.isFormField()){
                    //General field
                    String name = fileItem.getFieldName();
                    String value = fileItem.getString();
                    System.out.println(name+"=" +value);
                }else {
                    //Upload file
                    //Get upload file name
                    String fileName = fileItem.getName();
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    //Get input stream
                    in = fileItem.getInputStream();

                    //Get the directory of uploaded files
                    String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
                    //Judge whether the folder exists. If it does not exist, create it first
                    File savePathDir = new File(savePath);
                    if (!savePathDir.exists()){
                        //Create upload folder
                        savePathDir.mkdir();
                    }

                    //Get output stream
                    out = new FileOutputStream(savePath+"\\"+fileName);
                    int len = -1;
                    byte[] bytes = new byte[1024];
                    while ((len = in.read(bytes)) > 0){
                        out.write(bytes,0,len);
                    }
                    resp.setContentType("text/html;charset=UTF-8");
                    resp.getWriter().write("<h1>Upload successful</h1>");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }finally {
            if(in != null){
                in.close();
            }
            if(out != null ){
                out.close();
            }
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
  • jsp
<%--
  Created by IntelliJ IDEA.
  User: caishenao
  Date: 2021/2/23
  Time: 20:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Upload page</title>
</head>
<body>
<h1>Upload page</h1>
<form method="post" action="/upload">
    Please select a file:<input type="file" name="file"/>
    File Description:<input type="text" name="name" />
    <input type="submit" value="Submit" />
</form>
</body>
</html>

download

reference resources: Address of reference blog

You don't need to use a plug-in. Just set the response body type of the response

code

package cn.cai;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@WebServlet("/download")
public class download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set the character set of the request body to prevent the obtained file name from generating Chinese garbled code
        req.setCharacterEncoding("UTF-8");
        //Get the parameters in the request body
        String fileName = req.getParameter("fileName");
        //Get the path of the Servlet in the server
        String path = this.getServletContext().getRealPath("/WEB-INF/upload");
        //Find out if the path contains the file
        File fileDir = new File(path);
        File file = returnFileName(fileDir, fileName);
        if (file == null){
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write("<h1>Server error</h1>");
            System.exit(-1);
        }
        //Set the response body to download
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/x-msdownload");
        //Set the file name after downloading
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        System.out.println(file.getName());
        //Create byte input stream read
        InputStream is = new FileInputStream(file);
        int len = -1;
        byte buffer[] = new byte[1024];
        //Get byte output stream
        ServletOutputStream outputStream = resp.getOutputStream();
        while ((len = is.read(buffer)) > 0){
            outputStream.write(buffer);
        }
        //Close flow
        is.close();
        outputStream.close();
    }

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

    private File returnFileName(File filePath,String fileName){
        File[] files = filePath.listFiles();
        for (File file:files) {
            if (fileName.equals(file.getName())){
                return file;
            }
        }
        return null;
    }
}

be careful:

resp.setContentType("application/x-msdownload");
//Set the file name after downloading
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

Ajax

Asynchronous JavaScript And XML asynchronous JavaScript and XML

Ajax is not a new programming language. It is an interactive method. Asynchronous loading and interactive updating of data between client and server on local pages do not need to refresh the whole page (local refresh)

advantage:

  1. Local refresh, higher efficiency

  2. Better user experience

AJAX syntax based on jQuery

$. ajax({attribute})

Common attribute parameters:

  • url: the requested back-end service address
  • type: request method; default is get
  • data: request parameters
  • dataType: the data type returned by the server, text/json
  • success: callback function for successful request
  • error: callback function for request failure
  • complete: the callback function that requests completion (it will be called regardless of success or failure)

JSON

JavaScript Object Notation, a lightweight data interaction format, has js applied to the conversion between Java login back-end development language object data

The transfer of object data between client and server requires JSON format.

JDBC

JDBC API

Provider: Java official

Content: interface for developers to call

Location of package: Java SPL and javax spl

  • DriverManager class
  • Connection interface
  • Statement interface
  • ResultSet interface

DriverManager

Provider: Java official

Role: manage different JDBC drivers

JDBC Driver

Provider: database manufacturer

Role: responsible for connecting different databases

Use of JDBC

  1. Loading database drivers, a bridge between Java programs and databases.
  2. Get Connection, a Connection between Java program and database.
  3. Create a Statement object, generated by Connection, and execute SQL statements.
  4. If you choose to receive the return value, create a ResultSet object and save the query results after the Statement is executed.

PreparedStatement

Subclass of Statement, which provides the function of SQL placeholder

Two questions were developed using Statement:

  1. String strings need to be spliced frequently, with a high error rate.
  2. There is a risk of SQL injection

Database connection pool

JDBC development process

  • Load driver (only need to load once)
  • Establish a database Connection
  • Execute SQL Statement
  • ResultSet receive result set (query)
  • Disconnect and free up resources

The database connection object is obtained through DriverManager. Every time you obtain it, you need to apply for the connection as the database, verify the user name and password, and disconnect after executing the SQL statement. This way will cause a waste of resources, and the data connection resources are not well reused.

You can use the database connection pool to solve this problem.

The basic idea of database connection pool is to establish a buffer pool for the database, and put a certain number of connection objects into the buffer pool in advance. When it is necessary to obtain database connection, only one object needs to be taken out of the buffer pool, and then put it back into the buffer pool for the next request, so as to achieve the reuse of resources, Allows programs to reuse an existing database connection object without having to recreate it.

When there is no free connection in the database connection pool, new requests will enter the waiting queue and wait for other threads to release the connection.

Implementation of database connection pool

The database connection pool of JDBC uses javax sql. DataSource interface. DataSource is an interface officially provided by Java. When using it, developers do not need to implement the interface themselves. They can use third-party tools. C3P0 is a common third-party implementation. In actual development, C3P0 can be directly used to complete the operation of database connection pool.

  1. Import jar package

code:

package cn.cai.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * C3P0 Use of:
 *  C3P0 Simplified steps:
 *      It simplifies the loading of Drive driver and the loading of url, user and password
 */
public class C3P0 Use of {
    public static void main(String[] args) {
        try {
            //Create C3P0
            ComboPooledDataSource pool = new ComboPooledDataSource();
            //Load driver
            pool.setDriverClass("com.mysql.cj.jdbc.Driver");
            //Set url
            pool.setJdbcUrl("jdbc:mysql://localhost:3306/students?serverTimezone=UTC&characterEncoding=UTF-8");
            //Set user
            pool.setUser("root");
            //Set password
            pool.setPassword("root");
            //Get Connection object
            Connection connection = pool.getConnection();
            //Subsequent codes remain unchanged
            System.out.println(connection);
            //Close and put the object back into the connection pool
            connection.close();
        } catch (PropertyVetoException | SQLException e) {
            e.printStackTrace();
        }
    }
}

Related configuration of C3P0 database connection pool:

package cn.cai.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * C3P0 Use of:
 *  C3P0 Simplified steps:
 *      It simplifies the loading of Drive driver and the loading of url, user and password
 */
public class C3P0 Use of {
    public static void main(String[] args) {
        try {
            //Create C3P0
            ComboPooledDataSource pool = new ComboPooledDataSource();
            //Load driver
            pool.setDriverClass("com.mysql.cj.jdbc.Driver");
            //Set url
            pool.setJdbcUrl("jdbc:mysql://localhost:3306/students?serverTimezone=UTC&characterEncoding=UTF-8");
            //Set user
            pool.setUser("root");
            //Set password
            pool.setPassword("root");
            /*
            *   Some database connection pool related configurations
            * */
            //Set the number of initialization connection pools
            pool.setInitialPoolSize(20);
            //Set the number of Connection pool pairs, which is the maximum number of Connection objects that can be created
            pool.setMaxPoolSize(40);
            //The number of objects created at one time when there are not enough connected objects
            pool.setAcquireIncrement(5);
            //Set the minimum number of connection pools
            pool.setMinPoolSize(2);
            //Get Connection object
            Connection connection = pool.getConnection();
            //Subsequent codes remain unchanged
            System.out.println(connection);

            //Close and put the object back into the channel connection pool
            connection.close();
        } catch (PropertyVetoException | SQLException e) {
            e.printStackTrace();
        }
    }
}

In the actual development, the configuration information of C3P0 is defined in the xml file, and the Java program only needs to load the configuration file to complete the initialization of the database connection pool.

  1. The name of the configuration file must be c3p0 config XML, and the location of the file should be placed in the src directory.
  2. When initializing ComboPoolDataSource, the parameter passed in must be c3p0 config The value of the name attribute of the named config tag in XML.
  • The file name is c3p0 config Contents of XML file:
<c3p0-config>
  <!-- Read the connection pool object using the default configuration -->
  <named-config name="otherc3p0">
    <!--  Connection parameters -->
<!--    Related configuration of database connection-->
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/students?serverTimezone=UTC&amp;characterEncoding=UTF-8</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- Connection pool parameters -->
    <property name="initialPoolSize">20</property>
    <property name="maxPoolSize">40</property>
    <property name="acquireIncrement">5</property>
    <property name="minPollSize">2</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>
  • About c3p0 config Use of XML files:
package cn.cai.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class C3P0 Configuration of {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource pool = new ComboPooledDataSource("otherc3p0");//C3p0 config The value of the name attribute of the named config tag of XML
            Connection connection = pool.getConnection();
            System.out.println(connection);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}

DBUtils

DBUtils can help developers complete data encapsulation (mapping result sets to Java objects)

  1. Import jar package
  2. Create QueryRunner object
  3. Set the sql statement to execute
  4. Call the query method of the QueryRunner object, pass in the Conner connector, sql statement and the corresponding implementation class of the corresponding ResultHandler, and receive the returned corresponding object.

The ResultHandler interface is used to process the result set. It can convert the queried result set into Java objects, and provides the implementation classes in 4.

  • BeanHandler maps the result set to a Java object Student
  • BeanListHandler maps the result set to a List set
  • MapHandler maps the result set to a Map object
  • MapListHandler maps the result set to a MapList collection

MVC

It is a development mode and an idea of layering programs.

M: Model business data (servcie, repository, entity)

5: V iew (JSP, HTML, APP client)

C: Controller control (Servlet, Handeler, Action)

After the request enters the Java Web application, the Controller receives the request, performs business logic processing, and finally returns the processing result to the user (View + Model)

Controller (receiving request processing response) -- "Service (processing business logic) -- > repository (underlying database interaction)

nitialPoolSize">20
40
5
2
1000

* about c3p0-config.xml Use of documents:

```java
package cn.cai.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class C3P0 Configuration of {
    public static void main(String[] args) {
        try {
            ComboPooledDataSource pool = new ComboPooledDataSource("otherc3p0");//C3p0 config The value of the name attribute of the named config tag of XML
            Connection connection = pool.getConnection();
            System.out.println(connection);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}

DBUtils

DBUtils can help developers complete data encapsulation (mapping result sets to Java objects)

  1. Import jar package
  2. Create QueryRunner object
  3. Set the sql statement to execute
  4. Call the query method of the QueryRunner object, pass in the Conner connector, sql statement and the corresponding implementation class of the corresponding ResultHandler, and receive the returned corresponding object.

The ResultHandler interface is used to process the result set. It can convert the queried result set into Java objects, and provides the implementation classes in 4.

  • BeanHandler maps the result set to a Java object Student
  • BeanListHandler maps the result set to a List set
  • MapHandler maps the result set to a Map object
  • MapListHandler maps the result set to a MapList collection

MVC

It is a development mode and an idea of layering programs.

M: Model business data (servcie, repository, entity)

5: V iew (JSP, HTML, APP client)

C: Controller control (Servlet, Handeler, Action)

After the request enters the Java Web application, the Controller receives the request, performs business logic processing, and finally returns the processing result to the user (View + Model)

Controller (receiving request processing response) -- "Service (processing business logic) -- > repository (underlying database interaction)

Topics: Java MySQL