Article From:https://www.cnblogs.com/huangdabing/p/9219444.html

One, the traditional configuration of Servlet

  In JavaWeb development, every time you write a Servlet, you need toweb.xmlThe configuration is shown in the file as follows:

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>com.web.controller.ActionServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>/servlet/ActionServlet</url-pattern>
</servlet-mapping>

It’s really a headache to send a Servlet to configure Servlet in web.xml, so Servlet3.0 provides a annotation that no longer needs S in the web.xml file.Ervlet’s deployment description, simplifying the development process. In this paper, the configuration of Servlet based on annotation is not based on Servlet3.0, but based on Servlet2.5. By developing custom annotation and annotation processor,Analog implementation similar to Servlet3.0’s annotation mode configuration Servlet

Two. Configuring Servlet based on annotations

  JDK1. 5After the version, JAVA provides a name calledAnnotationThe new data type, translated into ChineseAnnotation or annotation,Its appearance provides a perfect solution for the overwhelming XML configuration files, making JAVA EE development more convenient, faster and cleaner.However, Servlet2.5 does not support the configuration of the annotations by default, but we can develop a custom annotation, then annotate the annotations to Servlet, and then write a annotation processor for our custom annotations.

Principle:
  First, the browser passes the request and passes through the filter. The filter executes the initial init method. The tool class scans the specified package in the configuration file. The scan tool stores all the byte code files of the class under the specified package into the Set collection, then traverses the set collection, if the elements in the set collection (package)The bytecode files of each class are developed with the WebServlet.class annotation type, then get the value value (URI address) defined in the annotation of the current set element, and the value value in the annotated interface WebServletWhat is defined is Servlet’s access to URI. Therefore, the initialization init () method of the filter uses the “bytecode file of all the ordinary classes under the specified package to develop the WebServlet annotations” as the value value, using the String in the annotation.Value() defines the Servlet access URI as the key key, and stores it to Map< String, Class< > >ClassMap in this Map collection. The map collection is stored to the global object ServIn eltContext. Then, in the doFilter method of the filter, get the map in ServeltContext. If the filter is executed, then the user must issue the request request. Get the use of request objects firstThe URI of the user finds the general Java class that uses annotations in the map collection, reflecting the object that created the Java class. If you do not specify which method to call, then get or post is called according to the request of the user, and the corresponding method is called. If the method is specified, first according to URI finds the corresponding bytecode file in the map collection and creates objects of the Java generic class. According to the method behind the address in the address, it reflects the way to execute Java generic class object. Of course, with bytecode files, you can get all the methods in the Java class, and of course get annotations.The parameter value defined in this method is used as the parameter to execute the init method of the Java class.

The concrete practices are as follows:

 

2.1、Developing relevant annotations for configuring Servlet

 

  1、Developing WebServlet annotation for tagging Servlet classes for processing requests

package com.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Customize the WebServlet annotation to simulate the WebServlet annotation of Servlet3.0.* the property value of @Target annotation indicates that the @WebServlet annotation can only be used in front of the class or interface definition declaration.* @WeThe bServlet annotation has a required attribute, value.* the way to call is: @WebServlet (value= "/xxxx").* because of syntax, if the attribute name is value and only the value attribute value is added,You can omit the value attribute name, that is, you can also write: @WebServlet ("/xxxx").*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebServlet {
    //ServletAccess to URL
    String value();
    //ServletAccess to URL
    String[] urlPatterns() default {""};
    //ServletDescription
    String description() default "";
    //ServletDisplay name
    String displayName() default "";
    //ServletName
    String name() default "";
    //ServletInit parameters
    WebInitParam[] initParams() default {};
}

The configuration information of Servlet in web.xml is expressed using WebServlet annotations, and after the use of annotations, only a similar @WebServlet (“/servlet/LoginServl” (“/servlet/LoginServl”) needs to be used before the corresponding Servlet class.Et “” annotation can achieve the same purpose as the configuration information in the web.xml file above. The attribute value “/servlet/LoginServlet” in @WebServlet indicates the &lt in the web.xml configuration file; sErvlet-mapping> the value of the element < url-pattern> the value of the interior. This annotation simplifies the configuration of Servlet information in XML files, and the entire configuration file will be very succinct, clean, and developed.The work of the staff will also be greatly reduced.

  2、Develop WebInitParam annotation for configuring the parameters used in Servlet initialization.

package com.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @ClassName: WebInitParam
* @Description: Definition of the Initialization Parameter annotation of Servlet*@author: hdb
* @date: 2017-10-1 3:25:53 p.m.**/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebInitParam {
    //Parameter name
    String paramName() default "";
    //Parameter value
    String paramValue() default "";
}

2.2、Write a processor for processing annotations

  It gives a brief introduction to the definition declaration and usage of the annotation. The annotation needs a processor in the background to work, so we have to write a processor for the annotation above. Here we use Filter as the annotation processor to write a AnnotationHandleFiLter, the code is as follows:

package com.web.filter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.annotation.WebInitParam;
import com.annotation.WebServlet;
import com.util.ScanClassUtil;

/**
* @ClassName: AnnotationHandleFilter
* @Description: Use Filter as an annotation processor*@author: hdb
* @date: 2017-11-12 10:15:19 p.m.**/ 
public class AnnotationHandleFilter implements Filter {

    private ServletContext servletContext = null;
    
    /* When filters are initialized, scan the specified packages and use WebServlet annotations.* @see javax.servlet.Filter#init (javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("---AnnotationHandleFilterThe initialization of the filter begins - ");
        servletContext = filterConfig.getServletContext();
        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        //Get the package to be scanned in web.xml
        String basePackage = filterConfig.getInitParameter("basePackage");
        //If multiple packages are configured, such as: < param-value> com.web.controller, com.web.UI< /param-value>
        if (basePackage.indexOf(",")>0) {
            //Separate by comma
            String[] packageNameArr = basePackage.split(",");
            for (String packageName : packageNameArr) {
                addServletClassToServletContext(packageName,classMap);
            }
        }else {
            addServletClassToServletContext(basePackage,classMap);
        }
        System.out.println("----AnnotationHandleFilterFilter initialization end - ");
    }
    
    /**
    * @Method: addServletClassToServletContext
    * @Description:Add ServletClass to ServletContext* @Anthor:hdb**@param packageName
    * @param classMap
    */ 
    private void addServletClassToServletContext(String packageName,Map<String, Class<?>> classMap){
        Set<Class<?>> setClasses =  ScanClassUtil.getClasses(packageName);
        for (Class<?> clazz :setClasses) {
            if (clazz.isAnnotationPresent(WebServlet.class)) {
                //Get an example of the WebServlet Annotation
                WebServlet annotationInstance = clazz.getAnnotation(WebServlet.class);
                //Get the value of the value property of an instance of the Annotation
                String annotationAttrValue = annotationInstance.value();
                if (!annotationAttrValue.equals("")) {
                    classMap.put(annotationAttrValue, clazz);
                }
                //Gets the value of the urlPatterns property of the instance of Annotation.
                String[] urlPatterns = annotationInstance.urlPatterns();
                for (String urlPattern : urlPatterns) {
                    classMap.put(urlPattern, clazz);
                }
                servletContext.setAttribute("servletClassMap", classMap);
                System.out.println("annotationAttrValue:"+annotationAttrValue);
                String targetClassName = annotationAttrValue.substring(annotationAttrValue.lastIndexOf("/")+1);
                System.out.println("targetClassName:"+targetClassName);
                System.out.println(clazz);
            }
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("---Enter the annotation processing filter - ");
        //Forcibly convert ServletRequest into HttpServletRequest
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        Map<String, Class<?>> classMap = (Map<String, Class<?>>) servletContext.getAttribute("servletClassMap");
        //Get contextPath
        String contextPath = req.getContextPath();
        //Obtaining the URI resource of the user's request
        String uri = req.getRequestURI();
        //If you do not specify which method to call the Servlet class
        if (uri.indexOf("!")==-1) {
            //Obtaining the mode of request used by the user
            String reqMethod = req.getMethod();
            //Get the servlet path to be requested
            String requestServletName = uri.substring(contextPath.length(),uri.lastIndexOf("."));
            //Get the class to use
            Class<?> clazz = classMap.get(requestServletName);
            //Creating an instance of a class
            Object obj = null;
            try {
                obj = clazz.newInstance();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            }
            Method targetMethod = null;
            if (reqMethod.equalsIgnoreCase("get")) {
                try {
                     targetMethod = clazz.getDeclaredMethod("doGet",HttpServletRequest.class,HttpServletResponse.class);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    targetMethod = clazz.getDeclaredMethod("doPost",HttpServletRequest.class,HttpServletResponse.class);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
            
            try {
                //The method of calling the object is processed
                targetMethod.invoke(obj,req,res);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }else {
            //Get the servlet path to be requested
            String requestServletName = uri.substring(contextPath.length(),uri.lastIndexOf("!"));
            //Access to the method of servlet to call
            String invokeMethodName = uri.substring(uri.lastIndexOf("!")+1,uri.lastIndexOf("."));
        
            //Get the class to use
            Class<?> clazz = classMap.get(requestServletName);
            //Creating an instance of a class
            Object obj = null;
            try {
                obj = clazz.newInstance();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            }
            //Get all the methods of the clazz class definition
            Method[] methods = clazz.getDeclaredMethods();
            //Get an example of the WebServlet Annotation
            WebServlet annotationInstance = clazz.getAnnotation(WebServlet.class);
            //Get an array of initialization parameters configured on the annotation
            WebInitParam[] initParamArr = annotationInstance.initParams();
            Map<String, String> initParamMap = new HashMap<String, String>();
            for (WebInitParam initParam : initParamArr) {
                initParamMap.put(initParam.paramName(), initParam.paramValue());
            }
            //Traversing the methods in the clazz class
            for (Method method : methods) {
                //The return type of the method
                Class<?> retType = method.getReturnType();
                //Get the name of the method
                String methodName = method.getName();
                //Print method modifier
                System.out.print(Modifier.toString(method.getModifiers()));
                System.out.print(" "+retType.getName() + " " + methodName +"(");
                //Gets an array of method parameters (getparameterTypes is used to return an array of Class objects that describe the parameter type).
                Class<?>[] paramTypes = method.getParameterTypes();
                for(int j = 0 ; j < paramTypes.length ; j++){
                     //If there are multiple parameters, the middle is separated by commas, otherwise printing parameters directly.
                    if (j > 0){
                        System.out.print(",");
                    }  
                    System.out.print(paramTypes[j].getName());
                }
                System.out.println(");");
                if (method.getName().equalsIgnoreCase("init")) {
                    try {
                        //The initialization method of calling Servlet
                        method.invoke(obj, initParamMap);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
            //Get an example of the WebServlet Annotation
            System.out.println("invokeMethodName:"+invokeMethodName);
            try {
                try {
                    //Using the example of reflection acquisition method, the signature of the method must conform to://public void Method name (HttpServletRequest request, HttpServletResponse response)//For example, public void loginHandle (HttpServletRequest request, HttpServletResponse response).
                    Method targetMethod = clazz.getDeclaredMethod(invokeMethodName,HttpServletRequest.class,HttpServletResponse.class);
                    //The method of calling the object is processed
                    targetMethod.invoke(obj,req,res);
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } 
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public void destroy() {

    }
}

AnnotationHandleFilterWhen the filter is initialized, the class that uses the WebServlet annotation under the specified packet is scanned, then the class is stored in a Map set, and the Map collection is stored in the servletContext object.

  

  Configure AnnotationHandleFilter filters and packages that need scanning in the web.xml file.

<filter>
        <description>The annotation processing filter < /description>< filter-name> AnnotationHandleFilter< /filter-name>< filter-class>com.web.filter.AnnotationHandleFilter</filter-class>
        <init-param>
            <description>The configuration should scan the package and its subpackage, if there are multiple packages, separate < by comma; /description>< param-name> basePackage< /param-namE>< param-value> com.web.controller; com.web.UI< /param-value>≪! - < param-value> com.web.controller< /param-value> -->< /init-param>< /filter>< filter-mapping>< filter-name> AnnotationHandleFilteR< /filter-name><! - the interception suffix is the request --> of.Do;< url-pattern> *.do</url-pattern>
    </filter-mapping>

AnnotationHandleFilterThe filter initialization method init (FilterConfig filterConfig) uses a tool class ScanClassUtil, which is used to scan a class under a packet, and the code of ScanClassUtil is as follows:

package com.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ScanClassUtil {

    /**
     * Get all the Class from the package package**@param pack
     * @return
     */
    public static Set<Class<?>> getClasses(String pack) {

        // The set of the first class class
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
        // Loop iteration
        boolean recursive = true;
        // Get the name of the package and replace it
        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');
        // Define an enumeration set and recycle it to handle the things in this directory.
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(
                    packageDirName);
            // Loop iteration
            while (dirs.hasMoreElements()) {
                // Get the next element
                URL url = dirs.nextElement();
                // Get the name of the agreement
                String protocol = url.getProtocol();
                // If it is saved on the server in the form of a file
                if ("file".equals(protocol)) {
                    System.err.println("fileType scans ");
                    // Get the physical path of the package
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // Scan the entire package file in file mode and add it to the collection.
                    findAndAddClassesInPackageByFile(packageName, filePath,
                            recursive, classes);
                } else if ("jar".equals(protocol)) {
                    // If it is a jar package file// Define a JarFile
                    System.err.println("jarType scans ");
                    JarFile jar;
                    try {
                        // Get jar
                        jar = ((JarURLConnection) url.openConnection())
                                .getJarFile();
                        // From this jar package gets an enumerated class
                        Enumeration<JarEntry> entries = jar.entries();
                        // The same cyclic iteration
                        while (entries.hasMoreElements()) {
                            // Getting an entity in jar can be a directory and other files in some jar packages, such as META-INF.
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            // If it is / begins
                            if (name.charAt(0) == '/') {
                                // Get the following string
                                name = name.substring(1);
                            }
                            // If the first half is the same as the definition of the package name
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                // If "/" ending is a package
                                if (idx != -1) {
                                    // Get the package name to replace "/" to "."
                                    packageName = name.substring(0, idx)
                                            .replace('/', '.');
                                }
                                // If you can iterate and be a package
                                if ((idx != -1) || recursive) {
                                    // If it is a.Class file and not a directory
                                    if (name.endsWith(".class")
                                            && !entry.isDirectory()) {
                                        // Remove the ".Class" behind to get the real class name
                                        String className = name.substring(
                                                packageName.length() + 1, name
                                                        .length() - 6);
                                        try {
                                            // Add to classes
                                            classes.add(Class
                                                    .forName(packageName + '.'
                                                            + className));
                                        } catch (ClassNotFoundException e) {
                                            // log
                                            // .error("Adding custom view class error can not find such.Class file "";
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        // log.error("When you scan the user defined view, you get a file error from the jar package.
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }
    
    /**
     * Get all the Class under the package in the form of a file**@param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName,
            String packagePath, final boolean recursive, Set<Class<?>> classes) {
        // Get the directory of this package to establish a File
        File dir = new File(packagePath);
        // If it does not exist or is not a directory, it will return directly.
        if (!dir.exists() || !dir.isDirectory()) {
            // log.warn("The user defined package name "+ packageName +" does not contain any files.
            return;
        }
        // If there is, all files, including directory, can be obtained.
        File[] dirfiles = dir.listFiles(new FileFilter() {
            // Custom filtering rules can be recycled (including subdirectories) or files ending with.Class (compiled Java class files).
            public boolean accept(File file) {
                return (recursive && file.isDirectory())
                        || (file.getName().endsWith(".class"));
            }
        });
        // Loop all files
        for (File file : dirfiles) {
            // If it is a directory, continue to scan
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "."
                        + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                // If it is a Java class file, remove the.Class behind, leaving only the class name.
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    // Add to the collection//classes.add(Class.forName(packageName + '.' + className));
                     //After replying to the students' reminding, there are some bad things about using forName here, which will trigger the static method and do not use classLoader's load clean.
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));  
                    } catch (ClassNotFoundException e) {
                    // log.error("Adding custom view class error can not find such.Class file "";
                    e.printStackTrace();
                }
            }
        }
    }
}

Through the above two steps, our custom annotations and the annotated processors have been developed.

2.3、WebServletAnnotation simple test

  Write a LoginUIServlet for a jump to a Login.jsp page, LoginUIServlet is an ordinary Java class, not a real Servlet, and then annotate Logi with WebServlet annotationsNUIServlet class, the code is as follows:

package com.web.UI;

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

@WebServlet("/servlet/LoginUI")
public class LoginUIServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

Enter the access address in the browser: http://gacl-pc:8080/AnnotationConfigServlet/servlet/Login.do, according to the configuration of the web.xml file, all suffixes are called.Do requestsIn the doFilter method of the AnnotationHandleFilter filter, in the implementation code of the doFilter method, the type of type that is requested from the HttpServletRequest request object (GET/POST) and the requested URI. If http://gacl-pc:8080/AnnotationConfigServlet/servlet/LoginUI.do is requested, the request method type is GET and the URI value is /AnnotationConfigServlet/servlet/LoginUI.do. Get the Map structure saved in the filter from the ServletConext object, and get a Key= “/servl” based on URI.Et/LoginUI “, from the Map structure, the Value is obtained from this Key, at this time Value is the Servlet class to be called to create an object instance based on the Servlet class, and then to determine the call based on the type of request method previously obtained.The doGet or doPost method for this Servlet object instance. The final suffix of the client is.Do request, and the request object (HttpServletRequest) is divided by AnnotationHandleFilter.Analysis, thus calling a corresponding Servlet’s doGet or doPost method, completes a client request to the server response process.

  The following annotated program flow is shown as follows:

  

  The results are as follows:

  

  As you can see from the results of the run, our annotation processor successfully invokes the request of the target Servlet to handle the user, and through the @WebServlet annotation, Servlet does not have to make the tedious registration in the web.xml file, which is the use of @WebSerThe convenience of the vlet annotation.

2.3、WebServletAnnotated complex test

  Write the Login.jsp page, the code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>The login page < /title>< /head>< body>< fieldset>< legend> user login< /legend>< form action= "${pageContext.request.contextPath}/servlet/LoginServlet! Log"InHandle.do "method=" post ">
            User name:<input type="text" value="${param.usename}" name="usename">
            <br/>
            Password:<input type="text" value="${param.pwd}" name="pwd">
            <br/>
            <input type="submit" value="Log in to "/>< /form>< /fieldset>< hr/>< label style= "color: red"> ${msg}< /label>< /body>< /html>

formThe URL= of the action attribute in the form“${pageContext.request.contextPath}/servlet/LoginServlet!loginHandle.do“,/servlet/LoginServletIt means that you are visitingLoginServlet!HinderloginHandleIndicate to callLoginServletMiddleloginHandleMethodDealing with this request, that is, when we visit Servlet, we can specify which method to access Servlet in URL, and the doFilter method of the AnnotationHandleFilter filter is intercepted to the user’s request,First get the URI that the user wants to access, judge the Servlet that the user is going to visit according to URI, and then judge whether the URI contains “!”, if so, it shows that the user shows which method to access Servlet.ServletAll the methods defined in the class, if foundURIIn that method, call the corresponding method to handle the user request!

  LoginServletThe code is as follows:

 

package com.web.controller;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.annotation.WebInitParam;
import com.annotation.WebServlet;

/**
* 
* @ClassName: LoginServlet
* @Description:Processing the Servlet that the user logged in,* LoginServlet is now an ordinary Java class, not a real Servlet.*@author: hdb
* @date: 2017-11-8 12:07:58 a.m.**/
//Annotate the developed WebServlet annotations onto the LoginServlet class.
@WebServlet(
            //ServletAccess to URL
            value="/servlet/LoginServlet",
            //ServletThe access URL can configure multiple access paths in an array manner.
            urlPatterns={"/gacl/LoginServlet","/xdp/LoginServlet"},
            //ServletInitialization parameters
            initParams={
                    @WebInitParam(paramName="gacl",paramValue="hdb"),
                    @WebInitParam(paramName="bhsh",paramValue=""The king of the white tiger". ")
            },
            name="LoginServlet",
            description="Processing the user logged in Servlet "
        )
public class LoginServlet {

    public void loginHandle(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException{
        String username = request.getParameter("usename");
        String pwd = request.getParameter("pwd");
        if (username.equals("gacl") && pwd.equals("xdp")) {
            request.getSession().setAttribute("usename", username);
            request.setAttribute("msg", "Welcome! "+username);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }else {
            request.setAttribute("msg", "Login failed. Please check if user name and password are correct. ");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        }
    }
    
    
    /**
    * @Method: init
    * @Description: ServletInitialization* @Anthor:hdb**@param config
    */ 
    public void init(Map<String, String> initParamMap){
        System.out.println("--LoginServletInitialization - ");
        System.out.println(initParamMap.get("gacl"));
        System.out.println(initParamMap.get("bhsh"));
    }
}

 

The results are as follows:

  

  As you can see, the Servlet configured using the annotation has been successfully invoked, and the loginHandle method handles the complete processing of the user login request as shown in the following diagram:

  

  Servlet3.0It is supported to configure Servlet based on annotations, and I use filters as an annotation processor to simulate a Servlet3.0 – like annotation process that simplifies the configuration of Servlet. This way of using custom annotation + annotation processor is out of Shanzhai.Servlet3.0 everyone can understand it, to understand this process of thinking, in the actual application or not to do so, to really want to use the way to use the annotation Servlet or directly with Servlet3.0 bar.

 

Leave a Reply

Your email address will not be published. Required fields are marked *