Java Annotation - Annotation Processor, Serlet 3.0 | Lebytes

Posted by slobodnium on Sat, 27 Jul 2019 11:06:50 +0200

Hello, everyone. I'm Lebyte's Xiaole. Last time I brought you Java Annotation - Metadata, Annotation Classification, Built-in Annotation and Custom Annotation | Lebyte. This time I'll go on to explain the Annotation Processor and servlet 3.0.

Annotation Processor

An important part of the process of using annotations is to create annotation processors. Java SE5 extends the API of reflection mechanism to help programmers quickly construct custom annotation processors.

1. Annotation Processor Class Library java.lang.reflect.AnnotatedElement

Java uses the Annotation interface, which is the parent of all Annotation types, to represent the annotations that precede program elements. In addition, Java has added AnnotatedElement interface under the java.lang.reflect package, which represents the program elements that can accept annotations in the program. The interface has the following main implementation classes:

Class: Class Definition
Constructor: Constructor definition
Field: Definition of cumulative member variables
Method: Method definitions of classes
Package: Package definition of classes

The java. lang. reflection package mainly contains some tool classes to implement reflection function. In fact, all the reflection API s provided by the java. lang. reflection package expand the ability to read Annotation information at runtime. When an Annotation type is defined as a runtime Annotation, the annotation is visible at runtime, and only when the class file is loaded, the Annotation stored in the class file is read by the virtual machine.

AnnotatedElement interface is the parent interface of all program elements (Class, Method and Constructor), so after a program obtains an AnnotatedElement object of a class by reflection, the program can call the following four methods of accessing Annotation information of that object:

(1) < T extends Annotation > T get Annotation (Class < T > annotation Class): Returns a specified type of annotation that exists on the program element and null if it does not exist.

(2) Annotation[] getAnnotations(): Returns all comments that exist on the program element.

(3) Boolean is Annotation Present (Class <? Extends Annotation > annotation Class): Determine whether the program element contains annotations of a specified type, and return true if they exist, or false if they exist.

(4) Annotation [] getDeclared Annotations (): Returns all comments that exist directly on this element. Unlike other methods in this interface, this method ignores inherited annotations. (If no comment exists directly on this element, an array of zero length is returned.) The caller of this method can modify the returned array at will; this does not have any effect on the returned array of other callers.

2. Analytical Examples

public class ParseCoder {
    public static void main(String[] args) {
        String coderName="Name:";
        String coderType="Type:";
        String coderProvider="The manufacturer's information is as follows ";
        Field [] fields=Coder.class.getDeclaredFields();
        for(Field field:fields){
            if(field.isAnnotationPresent(Programmer.class)){
                Programmer pro=(Programmer)field.getAnnotation(Programmer.class);
                coderName=coderName+pro.value();
                System.out.println(coderName);
            }else if(field.isAnnotationPresent(ProgrammerType.class)){
                ProgrammerType type=(ProgrammerType)field.getAnnotation(ProgrammerType.class);
                coderType=coderType+type.type().toString();
                System.out.println(coderType);
            }else if(field.isAnnotationPresent(ProgrammerProductor.class)){
                ProgrammerProductor fruitProvider=(ProgrammerProductor)field.getAnnotation(ProgrammerProductor.class);
                coderProvider+="No."+fruitProvider.id()+" Name:"+fruitProvider.name()+" address:"+fruitProvider.address();
                System.out.println(coderProvider);
            }
        }
    }
}

Servlet 3.0

1,@WebServlet

Use annotations to achieve zero configuration, develop servlet projects, and use @WebServlet to define a class inherited from javax.servlet.http.HttpServlet as a servlet component. In Servlet 3.0, a class inherited from javax.servlet.http.HttpServlet can be annotated as a Servlet that can handle user requests using the @WebServlet annotation.

@ Relevant properties of WebServlet annotations

The access URL of a Servlet is a mandatory attribute of a Servlet, and you can choose to use urlPatterns or value definitions. For example, a Servlet can be described as:

@WebServlet(name="ServletDemo",value="/ServletDemo").

Multiple URL access is also defined: for example

@WebServlet(name="ServletDemo",urlPatterns={"/ServletDemo","/ServletDemo2"})

Or:

@WebServlet(name="AnnotationServlet",value={"/ServletDemo","/ServletDemo2"})

initParams can be used to specify the initialization parameters of the current Servlet, which is an array in which each @WebInitParam represents a parameter.

@WebServlet(value="/servlet/init-param", initParams={@WebInitParam(name="param1", value="value1")})

The test examples are as follows

/**
 * A class inherited from javax.servlet.http.HttpServlet is defined as a Servlet component using @WebServlet.
For example, @WebServlet has many attributes:
1,asyncSupported:     Declare whether the Servlet supports asynchronous mode of operation.
2,description:       Servlet Description.
3,displayName:        Servlet Display name.
4,initParams:         Servlet The init parameter.
5,name:            Servlet Name of.
6,urlPatterns: Servlet Access URL.
7,value:            Servlet Access URL.
Servlet Access URL s for Servlet s are mandatory attributes, and you can choose to use urlPatterns or value definitions.
For example, @WebServlet(name="TestServlet",value="/TestServlet") also defines multiple URL access:
For example, @WebServlet (name= "TestServlet", urlPatterns= {"/ TestServlet", "Test"})
Or @WebServlet (name = "TestServlet", value = {"/ TestServlet", "TestServlet"})
 */
@WebServlet(name="/TestServlet",urlPatterns={"/test"})
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("hello servlet3");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Initialization parameters

@WebServlet(value="/init", 
initParams={@WebInitParam(name="param1", value="sxt")})
public class TestInit extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      Enumeration<String> paramNames = this.getServletConfig().getInitParameterNames();  
      String paramName;  
      while (paramNames.hasMoreElements()) {  
         paramName = paramNames.nextElement();  
         response.getWriter().append(paramName + " = " + this.getServletConfig().getInitParameter(paramName));  
      }  
      response.getWriter().close();  
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

2,@WebFilter

/**
 * Using annotation annotation filter: @WebFilter implements a javax.servlet.Filter
 * The class of the interface is defined as a filter. The attribute filterName declares the name of the filter. Optional
 * Attribute urlPatterns specify the URL schema to be filtered or can be declared using attribute value.
 * (Specifies that the URL schema to be filtered is a mandatory attribute.
 * You can specify multiple filtering modes @WebFilter(filterName="TestFilter").
 * urlPatterns={"/User","/index.jsp"})
 * @author Administrator
 */
@WebFilter(filterName="TestFilter",urlPatterns="/*")
public class TestFilter implements Filter  {
    @Override
    public void destroy() {
        System.out.println("Filter Destruction");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("Perform filtering operations");
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
         System.out.println("Filter initialization");
    }
}

3,@MultipartConfig

Use the annotation @MultipartConfig to identify a servlet as supporting file upload. Servlet 3.0 encapsulates POST requests for multipart/form-data into parts, and operates on uploaded files through Part s.

Note: Servlet3 does not provide a way to get the filename directly. It needs to be parsed from the request header.

1) Page making

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload</title>
</head>
<body>
    <fieldset>
        <legend>Upload files</legend>
        <!-- Forms must be set when uploading files enctype="multipart/form-data" -->
        <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
            Upload files:<input type="file" name="file1"><br/>
            Upload files:<input type="file" name="file2"><br/>
            <input type="submit" value="upload">
        </form>
    </fieldset>
</body>
</html>

2) Writing Servlet

/**
 * Servlet3.0 Encapsulating POST requests for multipart/form-data into parts,
 * Servlet3 does not provide a way to get file names directly by manipulating uploaded files through Part s.
 * It needs to be parsed from the request header to get the request header and the format of the request header:
 * In Firefox and google: form-data; name="file"; filename="snmp4j--api.zip"
* @author Administrator
 */
@WebServlet(name = "TestUpload", urlPatterns = "/upload")
@MultipartConfig
public class TestUpload extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // Storage path
String savePath = request.getServletContext().getRealPath("/WEB-INF/upload");
        // Get the uploaded collection of files
        Collection<Part> parts = request.getParts();
        //Upload a single file
        if (parts.size()==1) {
            //Obtain files by filename
            Part part = request.getPart("file");
            //Get the file from the request header
            String header = part.getHeader("content-disposition");
            //Get the filename
            String fileName = getFileName(header);
            //Write the file to the specified path
            part.write(savePath+File.separator+fileName);
        }else{
             for (Part part : parts) {//Cyclic processing of uploaded files
//The format of the request header: form-data; name="file"; filename="snmp4j--api.zip"
                 String header = part.getHeader("content-disposition");
                 //Get the filename
String fileName = getFileName(header);
                if(!fileName.equals("")){
                    //Write the file to the specified path
                    part.write(savePath+File.separator+fileName);
                }                 
             }
        }
        PrintWriter out = response.getWriter();
        out.println("Upload Success");
        out.flush();
        out.close();
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
    /**
     * Get the filename
* In Firefox and google: form-data; name="file"; filename="snmp4j--api.zip"
     * @param header
     * @return
     */
    private  String getFileName(String header) {
        String[] headArr = header.split(";")[2].split("=");
        //Get the file name, compatible with all kinds of browsers        
        return headArr[1].substring(headArr[1].lastIndexOf("\\")+1).replaceAll("\"", "");
        
    }
}

4,@WebListener

Servlet 3.0 provides the @WebListener annotation to define a class that implements a specific listener interface as a listener. MyServletContextListener, which implements the ServletContextListener interface, is labeled as a listener.

@WebListener
public class TestListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent event) {
         System.out.println("ServletContext Destruction");
    }
    @Override
    public void contextInitialized(ServletContextEvent event) {
         System.out.println("ServletContex Initialization");
         System.out.println(event.getServletContext().getServerInfo());
    }
}

That's all for the annotations. Thank you all for your patronage and study.

Please continue to pay attention to Lebyte and keep updating Java dry goods information and videos.

Topics: Java Attribute Firefox Google