servlet, jsp, el&filter

First, tomcat

Dark horse tomcat teaching documents

1.1 tomcat installation

1.2 Manually deploy the project on the tomcat server

1.3 Use IDEA to deploy the project on the tomcat server

二、servlet&jsp

  • 【development of】:

Servlet technology is the underlying technology for developing web applications in java language. After the emergence of jsp technology, servlet program development has been simplified,

After that, a large number of web frameworks based on java appeared.

  • When the servlet container accepts the first request, it creates a servlet object, which has been in memory since

  • A servlet is a java program

  • servlet program, can only run in servlet container

  • The jsp page will eventually be compiled into a servlet program

  • servlet and jsp are just two of the most basic technologies in javaEE

  • [Relationship between request and servlet container]

[External chain image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-djGKgDrZ-1583216913271) (C: UserslenovoDocumentsTypora imgs \ image-20200226175027704.png)]

2.1 URL, request and response

1) URL format

image-20200227102833662
  • protocol

A URL supports multiple protocols, not just http protocol

  • CPU name

www is the default host name, google.com will be mapped to www.google.com

qq.com and mail.qq.com are not the same url

  • The port number

The default port number of the http protocol is 80. If the web server runs on port 80, the port number may not be written in the url

  • One url corresponds to one resource, and the url without corresponding resource accesses the default resource of the default context

2) Request and response

  • Terminology: message

Request messages, response messages, etc., are actually request information, response information

2,2 Servlet interface

  • In Servlet technology, the core is the Servlet interface

  • The contract between Servlet and Servlet container is defined in the Servlet interface

Summary: The Servlet container loads the Servlet into memory, and the Servlet container calls the Servlet instance method

The request is accepted by the servlet container, and the servlet container creates a servlet instance based on the requested url (only the first request)

Call the init method to complete the initialization, call the service method, and return to the client response

1), the method defined in the Servlet interface

-There are three life cycle methods

image-20200226215921613

Note: The init method accepts a ServletConfig object

2.2 Servlet application directory structure

2.3 Deploy Servlet applications

  1. When deploying servlet applications, it is recommended to use war files. When starting Tomcat, Tomcat will automatically decompress

2.4 ServletContext

  • Each web program can only have one ServletContext object

  • The properties in the Servlet context can be accessed anywhere in the web application

  • The ServletContext object can store the object, at this time, the stored object is called an attribute

image-20200227103136236

2.5 javax.servlet.http包

HttpServlet

HttpServletRequest

HttpServletRequest extends the javax.servlet.ServletRequest interface and adds several methods

Request object, reaching the servlet container with client information

HttpServletReponse

Response object, to send information to tell the client what to do

2.6 Session management

The essence of session management is the direct state maintenance of the client and server

The importance of session management:

When there is no session, the user enters the user name and password when logging into the mail server for the first time. Due to the statelessness of http, when the
browser refreshes again, the server considers the request as the first request again. password

2.6.1 Cookie

The use of cookies to maintain state is actually: the server stores the data submitted by the browser in the cookie object, the next time the browser visits, the server obtains the data in the cookie.

Untitled

1), the server sends cookies

image-20200227115906303

2), the server receives cookies

image-20200227115933109

3), delete the cookie in the browser

image-20200227115957358

2.6 Session

Three, JSP

Requirements: to be able to write jsp pages. Also, it is not recommended to write java code in the jsp page.

3.1 JSP basics

3.1.1 Notes

Two types of notes are included:

  1. <%--%> [JSP notes]
  2. [HTML comments]

#### 3.1.2 Implicit objects

When the servlet container calls the servlet method, it will pass in the implicit object. For example, when calling the service method, pass in the request and response; when calling the init method, pass in the servletConfig object.

The jsp page is actually a servlet that can also use implicit objects

image-20200227184034516 image-20200227184052547

3.1.3 JSP syntax elements

instruction

Instruction is a type of jsp syntax element

  • 【page指令】:<%@page attr1=“value1” attr2=“value2” …%>

<&@ page session=“false” buffer=“16kb” %>

  • 【include指令】:<%@include file=“url” %>

  • The content is used on multiple pages or in different locations on the same page, the content should be regarded as an include file

  • This instruction can appear multiple times in the jsp page

  • The file type referenced by the directive is not required (jsp, html)

Script element

The second type of jsp syntax element

  • [Code Block]: <%%>
  • [Expression]: <% =%>
  • [Declaration]: <%!%>

Reference book

action

The third type of jsp syntax element

  • 【include动作】:<jsp:include>…</jsp:include>

Four, EL expression

  • EL expression writing: start with $ {and end with}

${expression}

  • EL expressions can return any type of object.The EL expression used in the jsp page is basically used to get the value of the implicit object

4.1 Operator

1), [] and. Operator

This operator is used to access object properties

image-20200227202132251

2), other operators

  • Mathematical operator
  • Relational operators (==,! =,>, <,> =, <=)
  • Logical Operators
  • The ternary operator $ {expression? A: B}

4.2 Implicit objects

  • Implicit objects that can be used in EL, the type is map
  • EL implicit objects are not the same as jsp implicit objects. The properties of jsp implicit objects are stored as key-value in EL implicit objects
  • 常用${pageContext.request.contextPath}
image-20200228092405773 image-20200228095912203

4.3 Get bounded objects

Bounded objects: objects stored in domain objects

  • Can be obtained directly in the EL expression
  • Operators can be used on bounded objects
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<%
  List list = new ArrayList();
  list.add("1");
  request.setAttribute("list",list);
  request.setAttribute("number",1);
%>
${not empty list}<br>
${number % 2 == 0}
</body>
</html>

Five, JSTL

  • JSTL: JavaServer Pages Standard Tag Library (jsp standard tag library)

  • There are five types of tags in JSTL, which are stored in different packages.

  • Use JJSTL tags in jsp pages, use taglib instruction to introduce

image-20200228093058860

5.1 Common tags

5.2 Label display

in conclusion:

  1. EL expression label, the value is null, or the object does not exist, it will not be displayed
${aaaa}
${null}
  1. JSTL tags (not satisfying if tag content) are sometimes not displayed
<c:if test="1">
  一直显示1<br>
</c:if>
<c:if test="true">
  一直显示true<br>
</c:if>
image-20200228113259970

if tag

【note】:

  1. When the tag does not meet the if condition, it will not be displayed
<%
  request.setAttribute("n",1);
%>
<%--test属性值为 true或false--%>
<c:if test="${n%2 != 0}">
  n为奇数<br>
</c:if>
<c:if test="${n%2 ==0}">
  n为偶数<br>
</c:if>
必须是true或false
<c:if test="1">
  一直显示1<br>
</c:if>

choose tag

<%
  request.setAttribute("n",1);
%>
<c:choose>
  <c:when test="${n==1}">星期一</c:when>
  <c:when test="${n==2}">星期二</c:when>
  <c:otherwise>Error!</c:otherwise>
</c:choose>

foreach tag

Two roles:

  1. repeat
  2. Traverse the container

Use foreach to do different things and use different attributes.

The data of the application is often used in the jstl tag, and the frequency of the combination of JSTL and EL is extremely high

<%
  List list = new ArrayList();
  list.add("a");
  list.add("b");
  list.add("c");
  request.setAttribute("list",list);
%>
<h2>foreach标签</h2>
<%--【重复】属性:begin,end,var,step--%>
<c:forEach begin="1" end="10" step="1" var="i">
  ${i}<br>
</c:forEach>
<%--遍历容器--%>
<c:forEach var="c" items="${list}">
  ${c}<br>
</c:forEach>

Six, filter

All URLs correspond to resources (the homepage is also a resource), so external requests cannot access certain resources at will.

filter is one of the three components of java web

After understanding the execution process of filer, you can find that filter can do many things

6.1 Using filter

【Steps for usage】:

  1. Write the implementation class of the Filter interface
  2. Configure the URL intercepted by the filter (comment configuration, xml configuration)

xml placement

1), POJO 类:

public class MyFilter implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    //
    System.out.println("执行step 1");
    chain.doFilter(request, response);
    System.out.println("执行step 3");
  }

  public void destroy() {
  }

  public void init(FilterConfig config) throws ServletException {

  }

}

2) 、 web.xml

<?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">
  <filter>
    <filter-name>filter01</filter-name>
    <filter-class>cn.covey.filter.MyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>filter01</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

3). Execution results:

image-20200228213429696

6.2 filter execution process

  1. The request is intercepted first, and the pre-release code is executed
  2. Request release, execute the service method of the corresponding servlet
  3. Execute the code released in dofilter again

Filter code:

@WebFilter(urlPatterns = {"/*"})
public class MyFilter implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    //
    System.out.println("step 1");
    chain.doFilter(request, response);
    System.out.println("step 3");
  }

  public void destroy() {
  }

  public void init(FilterConfig config) throws ServletException {

  }

}

jsp resource code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>首页</title>
</head>
<body>
<%
  System.out.println("step 2");
%>
</body>
</html>

When accessing resources, the console outputs:

image-20200228212019040

6.3 filter life cycle method

  • The life cycle method of filter is the same as the execution process of servlet life cycle method

Object creation ... init () destroy () object destruction

### 6.4 filter interception configuration

1), intercept resource configuration

  1. Intercept specific resources / jsp / jsp01.jsp
  2. Intercept directory / jsp / * (intercept all resources under jsp directory)
  3. Intercept suffix resource **. Jsp **. Do
  4. Block all resources / *

2) 、 Interception method

Requests for specified resources in a specified way, the request will be intercepted

The request methods are:

  1. DispatcherType.REQUEST
  2. DispatcherType.FORWARD
  3. DispatcherType.ERROR
  4. DispatcherType.ASYNC

[Filter03 code];

@WebFilter(urlPatterns = {"/resource.jsp"},dispatcherTypes = DispatcherType.REQUEST)
public class Filter03 implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

    System.out.println("直接请求");
    // 直接请求该资源,不放心
  }

  public void destroy() {
  }

  public void init(FilterConfig config) throws ServletException {

  }

}

[Servlet forwarding request code]:

@WebServlet(urlPatterns = "/hello")
public class Servlet01 extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //
    request.getRequestDispatcher("/resource.jsp").forward(request,response);
  }

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

6.5 filter chain

1). Execution order:

For example, a url corresponds to two filters, filter1, filter2, then:

  1. Code in filter1 before request release
  2. Code in filter2 before request release
  3. Execute request
  4. 2 codes after request release
  5. 1 code after request release

2), filter sorting rules:

image-20200228220803036 image-20200228221437646

6.6 filter application

Application 1: Logging

Demand: record the time of each resource request in order to know what resources are accessed most frequently

Published 7 original articles · Likes2 · Visits 516

Guess you like

Origin blog.csdn.net/weixin_44671911/article/details/104632076