servlet Development | Streamline servlet-mapping by using Filter + reflection to process URLs

Source: Internet
Author: User

1. Summary

In native Servlet development, if a URL corresponds to a servlet-mapping, then Web. XML will be very lengthy and difficult to maintain. In fact, we can actually use Filter + reflection to make a servlet handle multiple URLs and invoke different methods in the servlet based on different URLs (similar to SPRINGMVC)

According to the following code implementation, you can implement user access to/test, will automatically call Frontservlet the following test () method, and based on the return value of the method to return the JSP file or jump, when the user accesses the/test2, it will be adjusted Use the Test2 () method, and so on.

This article is a small mall-servlet version of the details of one of the series, project github:https://github.com/xenv/s-mall-servlet/Most of this code in GitHub can be found

2. Concrete implementation

Complete implementation code See: Https://github.com/xenv/S-mall-servlet/blob/master/src/filter/BackServletFilter.java

1. Create the Filter file,implements Filter, override DoFilter method 2. Inin the DoFilter methodget URI
// get root Container directory String ContextPath = request.getservletcontext (). Getcontextpath (); // get the full URI String uri  = Request.getrequesturi (); // root uri root uri = Stringutils.remove (Uri,contextpath);
3depending on the URI, get the corresponding function name and insert it into the request, for example, we simply turn the URI of the root directly into a function name here.
if //  The root directory does not contain a URI of.  String method = uri.substring (1);  Request.setattribute ("method"= "Front.servlet"; Request.getrequestdispatcher (Servletpath). Forward (request,response); ..} // Other Request release Filterchain.dofilter (Request,response);

4. Invoke the servlet based on a different URI, for example, we simply call a fixed servlet here
String Servletpath = "Front.servlet";
Request. Getrequestdispatcher (Servletpath). Forward (request,response);
5. In the servlet, rewrite the service method, we read the method just passed in, reflection calls the relevant methods, and send the request and responce in
@Overrideprotected voidService (HttpServletRequest req, HttpServletResponse resp)throwsxception {String method= (String) Req.getattribute ("Method"); //using reflection to convert the method text in a URL into a method for invocationReq.setcharacterencoding ("Utf-8"); Method m= This. GetClass (). GetMethod (method,httpservletrequest.class, HttpServletResponse.class); String redirect= M.invoke ( This, Req,resp). toString (); if(Redirect.startswith ("@") {resp.sendredirect (redirect.substring (1)); }Else if(Redirect.startswith ("%") ) Resp.getwriter (). Print (Redirect.substring (1)); ElseReq.getrequestdispatcher (redirect). Forward (req, resp); }

Here, our method returns a string, if the string is @ at the beginning, then a jump, which is equivalent to Springmvc's (redirect:), if it is a%, it returns plain text, and the other beginning calls that JSP (equivalent to SPRINGMV C's view positioning)

For illegal access, there can be errors, we have to do error handling, here is simply a simple demo

6. In the specific method, we need to accept request and responce, return a string, for example
 Public String Delete (httpservletrequest request, httpservletresponse response) {        int id = Integer.parseint (Request.getparameter ("id"));        Service.delete (ID);         return "@/admin/category_list";}
7. Configuring the filter and servlet in Web. xml
    <Filter>        <Filter-name>Backservletfilter</Filter-name>        <Filter-class>Filter. Backservletfilter</Filter-class>    </Filter>    <filter-mapping>        <Filter-name>Backservletfilter</Filter-name>        <Url-pattern>/*</Url-pattern>    </filter-mapping>    <servlet>        <Servlet-name>Frontservlet</Servlet-name>        <Servlet-class>Servlet. Frontservlet</Servlet-class>    </servlet>    <servlet-mapping>        <Servlet-name>Frontservlet</Servlet-name>        <Url-pattern>/front.servlet</Url-pattern>    </servlet-mapping>

  This way, when the user accesses the/test, the test () method is automatically called Frontservlet, and the return value of the method is returned to the JSP file or to a jump

3. Re-rationalize once

User access URL, first to filter, filter according to URL, get the corresponding method and servlet, and then filter to give control to the servlet, Serlvet again according to the method call specific methods, return to load JSP File or jump, so that we achieve the same effect as SPRINGMVC.

servlet Development | Streamline servlet-mapping by using Filter + reflection to process URLs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.