New Features of Servlet 3.0

1 Overview of new features of Servlet3.0 Requirements for

  use : MyEclipse10.0 or above, publish to Tomcat7.0 or above, and create JavaEE6.0 applications!
  The main new features of Servlet 3.0 are as follows:
    use @WebServlet, @WebFilter, @WebListener to replace the configuration of Servlet, Filter, and Listener in the web.xml file;
    Servlet asynchronous processing: when Servlet processing is time-consuming , this will make the client feel very stuck (the original (Servlete2.5), the browser cannot see the response content until the server does not end the response, only when the response ends, the browser can display the result!). When exception handling is used, the processed content can be responded to the client browser first, and then another thread is used to complete the time-consuming operation, that is, to display the content part by part;
    upload component: no need to use commons- For third-party upload components such as fileupload, it is more convenient to use the upload component of Servlet 3.0.

2 @WebServlet, @WebFilter, @WebListener (premise of use: delete web.xml file, advantage: less configuration information, disadvantage: inconvenient to modify) 

@WebServlet( urlPatterns="/AServlet",
          initParams={ //Initialization parameters
              @WebInitParam(name="p1", value="v1"),
              @WebInitParam(name="p2", value="v2")
          },
          //Mark whether the container loads this servlet at startup (instantiate and call its init() method), the value represents the priority, the smaller the positive value, the higher the priority, and the first to load at startup
          loadOnStartup=1    
)
public class AServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().print("hello servlet3.0!!");
    }
}


@WebFilter(urlPatterns="/*")
public class AFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse repsonse,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("Filter............");
        chain.doFilter(request, repsonse);
    }
    @Override
    public void destroy() {}
    @Override
    public void init(FilterConfig arg0) throws ServletException {}
}


@WebListener
public class AListener implements ServletContextListener {
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("died");
    }
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("born");
    }
}


3 Servlet asynchronous processing
  Servlet asynchronous processing is to let Servlet not block when processing time-consuming requests, but display part by part. That is to say, after using Servlet asynchronous processing, the page can display data part by part, instead of being stuck all the time, and displaying it together after the request response is completed.
  Before using asynchronous processing, be sure to give asyncSupported=true in the @WebServlet annotation, otherwise the default Servlet does not support asynchronous processing. If a filter exists, also set @WebFilter's asyncSupportedt=true. Note that the response type must be text/html, so set: response.setContentType("text/html;charset=utf-8");

  Using asynchronous processing can be roughly divided into two steps: Servlet normal response data, Servlet abnormal response data .

  When the servlet responds to the data normally, there is nothing to say. You can notify response.getWriter().print() to output to the client, but after the output, use response.getWriter().flush() to refresh, otherwise the data is just buffered In the area, data cannot be sent to the client.
  Asynchronous response data needs to use the request.startAsync() method to obtain the AsyncContext object. Then call the start() method of the AsyncContext object to start the asynchronous response. The start() method requires a parameter of type Runnable. The code for the asynchronous response is given in the Runnable's run() method. Note that after using response to respond in the asynchronous processing thread, use response.getWriter().flush() to flush the stream, otherwise the data cannot be responded to the client browser.
@WebServlet(urlPatterns="/AServlet", asyncSupported=true)
public class AServlet extends HttpServlet {
    public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // Compatible with IE! If the output is less than 512B, IE has no asynchronous effect!
        for(int i = 0; i <= 512; i++) {
            resp.getWriter().print("a");
        }
        resp.getWriter().flush();
        // get the async context object
        final AsyncContext ac = req.startAsync(req, resp);
        /**
         * Set the timeout time to 10 seconds. Tomcat needs to know whether the asynchronous response is over. If the response is not over, although the client browser will see the response data, there is only a circle on the mouse that can't be turned, indicating that Not finished responding yet. Tomcat will wait until the timeout, which can be obtained through the getTimeout() method of the AsyncContext class. Tomcat defaults to 20000 milliseconds. Of course, this method can also be used to set
         */
        ac.setTimeout(1000*10);
        //Give the context object a Runnable object and let it perform this task
        ac.start(new Runnable() {
            public void run() {
                println("Start now<br/>", resp);
                sleep(2000);
                for(char c = 'A'; c <= 'Z'; c++) {
                    println(c+"", resp);
                    sleep(250);
                }
                ac.complete();// Notify Tomcat that we have finished executing!
            }
        });
    }
    public void println(String text, HttpServletResponse resp) {
        try {
            resp.getWriter().print(text);
            resp.getWriter().flush();
        } catch (IOException e) {
        }
    }
    public void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
        }
    }
}


4 File upload
  Servlet3.0 provides a processing solution for file upload. Just add the @MultipartConfig annotation to the servlet.

  Of course, you can also specify attribute values ​​for the @MultipartConfig annotation, which has four attributes:
    int filesizeThreshold: specifies the size of the cache. When this size is exceeded, the file will be saved to disk;
    String location: Specifies the directory for temporary files;
    long maxFilesize: Specify the size limit for uploading a single file. If the uploader exceeds this size, an exception will be thrown;
    long maxRequestSize: Specify the size limit of the entire form.

  When the @MultipartConfig annotation is used on the servlet, you can use request.getPart("fieldName") to get the content of <input:file>, where Part represents a file form item.
<form action="<c:url value='/AServlet'/>" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"/><br/>
    简 历:<input type="file" name="resume"/><br/>
        <input type="submit" value="注册"/>
</form>

@WebServlet(urlPatterns="/AServlet")
@MultipartConfig(maxFileSize=1024*1024)
public class AServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //getParameter() method is ready to use! ! !
        String username = req.getParameter("username");//It's ready to use! ! !
        //Get the file form field, the corresponding Part object
        Part part = req.getPart("resume");
        //Get the required data from Part
        System.out.println(part.getContentType());//Get the MIME type of the uploaded file
        System.out.println(part.getSize());// Get the number of bytes of the uploaded file
        System.out.println(part.getName());// Get the file field name
        System.out.println(part.getHeader("Content-Disposition"));// Get the header, which contains the name of the uploaded file
        part.write("C:/xxx.jpg");// Save the uploaded file
        // Intercept upload file name
        String filename = part.getHeader("Content-Disposition");
        int start = filename.lastIndexOf("filename=\"") + 10;
        int end = filename.length() - 1;
        filename = filename.substring(start, end);
        System.out.println(filename);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326380665&siteId=291194637
Recommended