Basic configuration for JavaWeb programming servlets

  • 2020-04-01 02:28:12
  • OfStack

Anyone who has studied the JavaWeb knows about servlets, which require configuration in web.xml. I believe that there are many beginners like me at the beginning, for some configuration parameters are not very understanding.
Here's a basic Servlet configuration:


<servlet>  
    <servlet-name>MyServlet</servlet-name>  
    <servlet-class>com.Servlet.MyServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
    <servlet-name>MyServlet</servlet-name>  
    <url-pattern>/Servlet</url-pattern>  
</servlet-mapping>  

The configuration of a Servlet consists of two parts:
1, < Servlet> Configure the name and full classpath of the Servlet:
Servlet-name is a custom name given to the servlet.
Servlet-class is the complete class of a servlet, that is, from the original package all the way ". "to the servlet.
2, < The servlet - mapping> Is used to intercept requests, including servlet-name and url-pattern.
The servlet -name with < Servlet> The servlet-name in the servlet is corresponding, the two servlet-names must be consistent, otherwise the corresponding servlet will not be found.
Url-pattern is a rule for intercepting requests, and when the form is submitted, the corresponding Servlet is invoked according to a specific rule. This will be explained in detail below.
Url-pattern can be roughly divided into the following ways:
1. Perfect match
  Such as: < Url - pattern> / servlet/MyServlet. Do< / url - pattern>
2. Directory matching
Such as: < Url - pattern> / servlet / * < / url - pattern>

3. Extension matching
Such as: < Url - pattern> *. Do< / url - pattern>
In the web.xml file, the following syntax is used to define the mapping:

  L. Those that begin with '/' and end with' /* 'are used for path-mapping.
2. The prefix "*." is used for extension mapping.
3. "/" is used to define the default servlet mapping.
The rest is used to define detailed mappings. For example: / aa/bb/cc. The action

Container lookup rules:
1, the container will first look for an exact match, if not, then look for a directory match, if not, look for an extension match.
2. If a request matches multiple "directory matches," the container selects the longest match.
For example: the url-pattern of servletA is /test/*, while the url-pattern of servletB is /test/b/*. When http://localhost/test/b is accessed, the container selects the servlet with the longest path to match, which is servletB here.
Note: a normal-looking match like "/*.action" can go wrong. Because this match is part of both the pathmap and the extension map, the container cannot tell.
The above is just a basic configuration of servlets, and there are many other parameters that you can explore on your own if you are interested.


Related articles: