Servlet 1 (web basic learning notes 20) and servlet learning notes

Source: Internet
Author: User

Servlet 1 (web basic learning notes 20) and servlet learning notes
1. Servlet Introduction

Servlet is a technology provided by sun for developing dynamic web resources.
Sun provides a servlet interface in its API. To send a dynamic web Resource (that is, to develop a Java program to output data to the browser), follow these two steps:
1. Compile a Java class to implement the servlet interface.
2. Deploy the developed Java class to the web server.
According to a conventional naming convention, we usually call the java program that implements the servlet interface Servlet

Ii. ServletAPI

3. Servlet Method

Iv. Servlet operation

The Servlet program is called by the WEB server. After the web server receives the Servlet access request from the client:
① The Web server first checks whether the Servlet instance object has been loaded and created. If yes, perform Step 4. Otherwise, perform step 2.
② Load and create an instance object for the Servlet.
③ Call the init () method of the Servlet instance object.
④ Create an HttpServletRequest object that encapsulates the HTTP request message and an HttpServletResponse object that represents the HTTP Response Message. Then call the Servlet service () method and pass the request and response object as parameters.
⑤ Before the WEB application is stopped or restarted, the Servlet engine will uninstall the Servlet and call the Servlet's destroy () method before uninstalling it.

5. Servlet Lifecycle

The loading, instantiation, initialization, and destruction operations are performed on only one row.

V. Serlvet deployment 5.1. New Class Myservlet3 inherits HttpServlet

Override doGet, doPost, destroy (), init Method

Package com. pb. servletdemo; import java. io. IOException; import javax. servlet. servletConfig; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class Myservlet3 extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("doGet method called") ;}@ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("doPost method called");}/* @ Override protected void service (HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {// TODO Auto-generated method stub super. service (arg0, arg1);} */@ Override public void destroy () {System. out. println ("Servlet destruction, destroy method called") ;}@ Override public void init (ServletConfig config) throws ServletException {System. out. println ("Servlet initialization, init method called"); String initParam = config. getInitParameter ("charSetContent"); System. out. println (initParam );}}
5.2 configure in web. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name> servletdemo </display-name> <welcome-file-list> <welcome-file> index.html </welcome-file> <welcome-file> index.htm </welcome-file> <welcome-file> index. j Sp </welcome-file> <welcome-file> default.html </welcome-file> <welcome-file> default.htm </welcome-file> <welcome-file> default. jsp </welcome-file> </welcome-file-list> <! -- The servlet tag --> <servlet> <! -- The name of the specified servlet can be different from the name of the created servlet, alias --> <servlet-name> myserlvet </servlet-name> <! -- Complete path of servlet class name package name. class Name --> <servlet-class> com. pb. servletdemo. Myservlet3 </servlet-class> <! -- Initial Parameter --> <init-param> <! -- Set the character set --> <param-name> charSetContent </param-name> <! -- Value --> <param-value> UTF-8 </param-value> </init-param> </servlet> <! -- Intercept request servlet ing --> <servlet-mapping> <! -- Some servlet-names must be the same as the servlet-name above, otherwise an error will be reported --> <servlet-name> myserlvet </servlet-name> <! -- A servlet can have multiple URLs-pattern --> <! -- Exact match --> <url-pattern>/myservlet3 </url-pattern> <! -- Add the virtual directory --> <url-pattern>/demo/myservlet3 </url-pattern> <! -- Wildcard to configure * --> <url-pattern>/* </url-pattern> <! -- Configure the suffix --> <url-pattern> *. do </url-pattern> </servlet-mapping> </web-app>
5.3. Exact match

5.4. virtual directory matching-multiple virtual directories are allowed

5.5. * wildcard characters

5.6 access by extension

Vi. Overview of url-pattern 6.1 and url-pattern

<Url-pattern> element, used to map a Servlet alias to a URL access rule. In the Servlet configuration process, we first map a servlet implementation class to an alias using the servlet-name, servlet-class, and other child elements in the Servlet element, then, use the servlet-mapping element to map the alias to a url that can be accessed in the browser. The Servlet access is implemented through this URL. Instead of Alias. Therefore, configuring this URL is an important part of Servlet configuration. So how should we configure this URL? In other words, what are the configuration rules of url-pattern? When configuring the url-pattern element, there are three rules: exact match, directory match, and suffix match.

6.2. Exact match

The so-called exact match means that when we access a Servlet using a browser, the entered URL must be different from the part before the project name When configuring the Servlet, the configured url-pattern element must be completely consistent. For example, in the following example, a Servlet named HelloServlet is configured, and its url-pattern is configured as/helloServ, so this configuration is exactly matched. Assume that our project name is
TestServlet: the port number of our Web server is 8080. when accessing the local Servlet in a browser, you need to use this URL: http: // 127.0.0.1: 080/TestServlet/helloServ. Among them, 127.0.0.1 is the reserved IP address, which refers to the local machine, 8080 is the port number of the Web server we set, and TestServlet is the name of the Web project where our Servlet is located. The helloServ at the end is the URL pattern of the Servlet that we configured to be exactly matched.

<servlet><servlet-name>HelloServlet</servlet-name><servlet-class>javaee.sg.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>HelloServlet</servlet-name><url-pattern>/helloServ</url-pattern></servlet-mapping>
6.3. Directory matching

Compared with exact match, directory match is a relatively flexible configuration method. It starts with a slash, ends with a star, and specifies a virtual directory. To better illustrate this configuration method, we still use the example above. For example, for the Servlet we just mentioned, we can use this url-pattern to configure it:

<servlet-name>HelloServlet</servlet-name><url-pattern>/helloServ/*</url-pattern>

In this url-pattern, we use a virtual directory, helloServ, so the URL we enter when accessing this Servlet will have a variety of options, we just need to ensure that in this URL, besides Engineering
You can start with the virtual directory helloServ. For example, we can use this URL to access this Servlet: http: // 127.0.0.1: 8080/TestServlet/helloServ/theServlet. In this URL, TestServlet is the project name of the Web project. HelloServ is the name of the virtual directory, and the last theServlet is the name we randomly enter during access. This name can be replaced with another name, for example, thisServlet or thatServlet. In short, the project name TestServlet is followed by the name of the virtual directory.

6.4 suffix matching

Matching by suffix
. In this way, the url-pattern configuration element only limits the Servlet access suffix, but does not require virtual directories and names. For example, let's modify the Servlet We Just configured and use the suffix matching rule in url-pattern for configuration. Let's look at this Code:

<servlet-name>HelloServlet</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>

In this configuration, the suffix for accessing this Servlet is ". do ". That is to say, when there are no errors in the server address, port number, and project name in our URL, as long as the url ends with ". do ",
Can access our Servlet. For example, when accessing a Servlet with the alias HelloServlet, the URL can be written in the form of http: // 127.0.0.1: 8080/TestServlet/helloServ. do. As you can see, the first half of the URL is the IP address, port number, and project name. The URL ends with. do, so you can access HelloServlet. Alternatively, you can write this URL in the following format: http: // 127.0.0.1: 8080/TestServlet/theServlet. do.

6.5 precautions

During Servlet configuration, You need to note that a Servlet configuration element can correspond to multiple Servlet-mapping elements at the same time. For example, we still use HelloServlet as an example, let's look at this Code:

<servlet-mapping><servlet-name> HelloServlet </servlet-name><url-pattern>/helloServ</url-pattern></servlet-mapping><servlet-mapping><servlet-name> HelloServlet </servlet-name><url-pattern>/helloServ/* </url-pattern></servlet-mapping><servlet-mapping><servlet-name> HelloServlet </servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>

In this Code, three Servlet-mapping elements are configured for the servlet alias HelloServlet. Since we can configure multiple Servlet-mapping for the same servlet at the same time, what sequence does the servlet container look for the servlet when the client accesses this servlet? When multiple Servlet-mapping is configured for the same servlet, the servlet container first follows
If the matching is complete, the matching ends. If the matching fails, the matching continues in the order of directory matching and suffix matching, if there are multiple configuration items that match the directory, match the configuration item according to the longest one. At the same time, the request URL is also required for matching. If the URL ends with a slash, the request will be processed by directory matching.

7. Create a Servlet in eclipse

Select the required Method

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.