Servlet-related Technology

Servlet-related Technology

Previously, no tools were used for development.Development is cumbersome, start here and import the project into idea

Import projects into IDEA and develop

(1) Import Project

(2) Create a new src directory to facilitate the development of java code such as servlet s in the future

(3) Importing jar configuration items

(1) Configure the java compilation placement path and place it in the classes directory

(2) Importing jar from tomcat,

(3) EditingWeb.xmlPlaced Path

(4) Add Airifacts

(4) Deploy tomcat

Start Successful

Development steps for Servlet s

Configuring Servlet with xml

(1) InWeb.xmlConfigure the following configuration

    <!--To configure servlet name-->
    <servlet>
        <!--Amount to@WebServlet Of name attribute-->
        <servlet-name>secondServlet</servlet-name>
        <!--Appoint servlet Implementation Class-->
        <servlet-class>com.servletdemo.SecondServlet</servlet-class>
    </servlet>
   <!-- To configure servlet url-->
    <servlet-mapping>
        <!--Appoint servletname-->
        <servlet-name>secondServlet</servlet-name>
        <!--Appoint servlet Pointing to an address equivalent to urlPatterns-->
        <url-pattern>/secondServlet</url-pattern>
    </servlet-mapping>

(2) Development

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

/**
 * 〈Second servlet
 *
 * @author PitterWang
 * @create 2020/6/22
 * @since 1.0.0
 */
public class SecondServlet extends HttpServlet {

   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      resp.sendRedirect("index.jsp");
   }
}
Annotation Configuration Servlet
package com.servletdemo;

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;

/**
 * 〈First Servlet
 *
 * @author PitterWang
 * @create 2020/6/22
 * @since 1.0.0
 */
@WebServlet(name = "firstServlet",urlPatterns = {"/firstServlet"})
public class FirstServlet extends HttpServlet {
   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      resp.sendRedirect("index.jsp");
   }
}

Visit:http://localhost:8080/webDemo/firstServlet to jump toIndex.jsp

Properties of @WebServlet

Property Name type describe
name String servlet-name, if not specified, takes the fully qualified name
value String[] Equivalent to the urlPatterns property, which cannot be used at the same time
urlPatterns String[] Specifies the matching pattern of the Servlet url, equivalent to
loadOnStartup int Specify the loading order of Servlet s
initParams webInitParam[] Specify initialization parameters
asyncSupported boolean Is Asynchronous Operation Supported
description String describe
displayName String servlet display name

Servlet life cycle

Two times to create a servlet
 (1) When a client first requests a servlet, the system creates a servlet instance
 (2) Create a servlet, load-on-startup Servlet immediately when the web application starts
	Two ways to configure
	First: @WebServlet (name = "first Servlet", urlPatterns = {"/first Servlet"}, loadOnStartup = 1)
	Second:  
    <servlet>
        <!--The name property equivalent to @WebServlet-->
        <servlet-name>secondServlet</servlet-name>
        <!--Specify the implementation class for the servlet-->
        <servlet-class>com.servletdemo.SecondServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
Each Servlet Life Cycle
 (1) Create a servlet instance
 (2) The web container calls the init method to initialize the servlet
 (3) After the servlet is initialized, it is used to always respond to client requests.If the client sends a Get request, points to the doGet method, sends a Post request, and points to the doPost method.Or use service () uniformly to respond to user requests
 (4) When the web container is destroyed, the destroy() method is called.

Servlet Get Profile

xml mode
 <servlet>
     <!--Amount to@WebServlet Of name attribute-->
     <servlet-name>secondServlet</servlet-name>
     <!--Appoint servlet Implementation Class-->
     <servlet-class>com.servletdemo.SecondServlet</servlet-class>
     <load-on-startup>2</load-on-startup>
     <init-param>
         <param-name>name</param-name>
         <param-value>Wang Chengdong</param-value>
     </init-param>

 </servlet>
<!-- To configure servlet url-->
 <servlet-mapping>
     <!--Appoint servletname-->
     <servlet-name>secondServlet</servlet-name>
     <!--Appoint servlet Pointing Address-->
     <url-pattern>/secondServlet</url-pattern>
 </servlet-mapping>
package com.servletdemo;

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

/**
 * 〈Second servlet
 *
 * @author PitterWang
 * @create 2020/6/22
 * @since 1.0.0
 */
public class SecondServlet extends HttpServlet {

   @Override
   public void init() throws ServletException {
      System.out.println("Initialization");
      String name = getServletConfig().getInitParameter("name");
      System.out.println(name);
      super.init();
   }

   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      System.out.println("call");


      resp.sendRedirect("index.jsp");
   }

   @Override
   public void destroy() {
      System.out.println("Destroy");
      super.destroy();
   }
}

annotation

package com.servletdemo;


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

/**
 * 〈First Servlet
 *
 * @author PitterWang
 * @create 2020/6/22
 * @since 1.0.0
 */
@WebServlet(name = "firstServlet",urlPatterns = {"/firstServlet"},loadOnStartup = 1,
initParams = {@WebInitParam(name="password",value = "1234")})

public class FirstServlet extends HttpServlet {

   @Override
   public void init() throws ServletException {
      System.out.println("first Establish");
      String name = getServletConfig().getInitParameter("name");
      String password = getServletConfig().getInitParameter("password");

      System.out.println(name);
      System.out.println(password);
      super.init();
   }

   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      resp.sendRedirect("index.jsp");
   }
}

Develop JSP2 Custom Label Library

The following steps are required for jsp to develop a label Library

(1) Develop custom label processing classes

Inherit SimpleTagSupport class, re-doTag() method
package com.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.util.Date;

/**
 * 〈Custom Label Class
 *
 * @author PitterWang
 * @create 2020/6/22
 * @since 1.0.0
 */
public class HelloTag extends SimpleTagSupport {
   @Override
   public void doTag() throws JspException, IOException {
      getJspContext().getOut().write("helloword" + new Date());
   }
}

(2) Create a *.tld file, each *.tld file corresponds to a label library, each label library can contain multiple label Libraries

<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>myshortname</short-name>
    <!--Define Label Library's URL-->
    <uri>http://mycompany.com</uri>
    <tag>
        <!--Define label name-->
        <name>helloword</name>
        <!--Define label processing classes-->
        <tag-class>com.tag.HelloTag</tag-class>
        <!--Define empty label body-->
        <!--empty  Labels can only be used as empty labels
        tagdependent  Specify the label handling class to handle the label body itself
        scriptless  Specifies that the label body of the label can be static HTML Element, expression language, when not allowed jsp Script
        JSP  Specifies that the label body of the label can be used jsp Script
        -->
        <body-content>empty</body-content>
    </tag>
</taglib>

(3) Use custom tags in jsp

Two points are required to determine the specified label on the jsp page
 (1) Tag library uri: determine which tag library to use
 (2) Tag name: Make sure to use that tag
 There are two steps to using tags
 (1) Import label Library
 (2) Use labels
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--Import label library, specify mytag Label for prefix--%>
<%@ taglib uri="http://mycompany.com" prefix="mytag"%>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    WELCOME
<br/>
    <%--Use labels, where mytag Is the label prefix, according to taglib Compile instructions for--%>
<mytag:helloword/>
</body>
</html>

Use tags with attributes

(1) Develop custom label processing classes

Inherit SimpleTagSupport class, re-doTag() method
package com.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.util.Date;

/**
 * 〈Tags with Attributes
 *
 * @author PitterWang
 * @create 2020/6/23
 * @since 1.0.0
 */
public class AttributeTag extends SimpleTagSupport {

   private String userName;
   private String passWord;

   public String getUserName() {
      return userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getPassWord() {
      return passWord;
   }

   public void setPassWord(String passWord) {
      this.passWord = passWord;
   }

   @Override
   public void doTag() throws JspException, IOException {
      getJspContext().getOut().write("userName = " + userName + ",passWord = " + passWord);
   }
}

(2) Create a *.tld file, each *.tld file corresponds to a label library, each label library can contain multiple label Libraries

    <tag>
        <name>attribute</name>
        <tag-class>com.tag.AttributeTag</tag-class>
        <body-content>empty</body-content>


        <attribute>
            <!--Configuration Label Property Name-->
            <name>userName</name>

            <!--Set whether the property is required-->
            <required>true</required>

        <!--    Set whether properties are supported sp Dynamic content such as scripts, expressions-->
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>passWord</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
    </tag>

(3) Use custom tags in jsp

<mytag:attribute userName = "dongdong" passWord="1234"/>

Develop and configure Filter and its functions

1. Role of Filter
	1~Intercept customer's HttpServletRequest before HttpServletRequest reaches Servlet
	2~Check HttpServletRequest as needed, or modify HttpServletRequest header and data
	3~Block HttpServletResponse before it reaches the client.
	4~Check the HttpServletResponse as needed, or modify the HttpServletResponse header and data
 2. Various types of Filter
	1~User Authorized Filter
	2~Log Filter
	3~Filter responsible for decoding
	4~XSLT Filter that can change XML content
	5~Filter can intercept multiple requests or responses
 3. Create a Filter step
	1~Create Filter Processing Class
	2~Web.xmlConfigure Filter in File
 4.Filter and Servlet configuration and use are similar

(1) Create a Filter processing class

//RealizationJavax.servlet.FilterInterfaces, which define the following three methods
package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
 * 〈Intercept user requests and log requested information
 *
 * @author PitterWang
 * @create 2020/6/23
 * @since 1.0.0
 */
public class LogFilter implements Filter {

	//Access configuration information for Filter
	private FilterConfig config;

	/**
	 * Initialization Method
	 * @param filterConfig
	 * @throws ServletException
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

		ServletContext servletContext = this.config.getServletContext();

		long before = System.currentTimeMillis();
		System.out.println("Start filtering");

		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

		String servletPath = httpServletRequest.getServletPath();
		System.out.println("l Intercepted Address = "+servletPath);
		filterChain.doFilter(servletRequest,servletResponse);
		long aftet = System.currentTimeMillis();

		System.out.println("End of filtering");

		System.out.println("Request Location To" + httpServletRequest.getRequestURI() + "Time-consuming "+ (aftet - before));
	}

	/***
	 * destroy-method
	 */
	@Override
	public void destroy() {
		this.config = null;
	}
}

(2) Two configurations

1. Configuration of annotation modes

Annotate Filter Processing Class
@WebFilter(filterName = "log",urlPatterns = {"/*"})

2.Web.xmlMode Configuration

<filter>
    <filter-name>log</filter-name>
    <filter-class>com.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>log</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Develop and configure Listener and its capabilities

Listener listening takes only two steps
	1. Define the Listener implementation class
	2. Configure Listener through comments or xml files

(1) Implement the Listener class

Common event listening interfaces
 ServletContextListener: Used to listen for Web application startup and shutdown
 ServletContextAttributeListener: Used to monitor changes in attributes within an application
 ServletRequestListener: Listen for user requests
 ServletRequestAttributeListener: Listens for changes in attributes within the request scope
 HttpSessionListener: Listen for the start and end of session s
 HttpSessionAttributeListener: Attribute change in static session scope
package com.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebFilter;

/**
 * 〈Web Apply Startup and Close Listening
 *
 * @author PitterWang
 * @create 2020/6/23
 * @since 1.0.0
 */
/*@WebFilter*/
public class ConListener implements ServletContextListener {

   @Override
   public void contextInitialized(ServletContextEvent sce) {
      System.out.println("Web Service Start");
   }

   @Override
   public void contextDestroyed(ServletContextEvent sce) {
      System.out.println("Web Service shutdown");

   }
}

(2) Configure Listener

Mode 1: Note Mode

	Annotate @WebFilter on the Listener processing class

Mode 2:Web.xmlTo configure

<listener>
    <listener-class>com.listener.ConListener</listener-class>
</listener>

Test Project Download address; https://github.com/wangchengdonggo/webDemo.git

Tags: JSP Java Attribute xml

Posted on Mon, 22 Jun 2020 21:30:57 -0400 by QWERTYtech