Servlet

What is a Servlet

Servlet is a dynamic Web resource development technology (specification, interface) provided by Sun. Static Web resources: different people go to see the effect is the same HTML/ CSS/JS dynamic Web resources: Servlet/JSP/.NET/PHP is essentially a Java program, but unlike the Java programs we've seen before, Servlet can not run independently (there is no main function in the Servlet), you need to put the Servlet program in the server, called by the server can be executed! The Servlet program running on the server is used to process the request received by the server (process the request).

Two, the development of Servlet program 1, the development of Servlet program steps

1) write a class, you need to implement a Servlet interface or inherit Servlet interfaces subclass Servlet | - GenericServlet implementation Servlet interface, and implements the method | - HttpServlet GenericServlet (GenericServlet, GenericServlet, GenericServlet, GenericServlet, GenericServlet, GenericServlet, GenericServlet, GenericServlet) 2) configure the external access path of the Servlet in the web.xml file, and then publish the Web application to the server!

Create a Web application using Eclipse

Note: 1)Dynamic Web Version: Select Version 2.5, because after Version 2.5, the Servlet is configured through annotations, which is easier, but not easy to understand, so we choose Version 2.5. Use XML to configure the Servlet(the XML configuration Servlet information is automatically generated without our handwriting!) 2) It is recommended to open Web projects using Package Explorer, not Project Explorer!! 3) the Web project in Eclipse the directory structure in CGB Servlet - 01 (We) | - SRC: which is used to store a Java source file (xx. Java), also can put configuration files (XML/properties) | - build/classes: After SRC things in the source directory compiled, can in the classes directory | - WebContent: Is the root directory of the Web application, which can hold static Web resource file, compiled class files, Web applications rely on jars, Web, XML files etc. | | - Web - INF files - lib: Web applications rely on the jar package | -- Web. XML: Core configuration files for web applications (configuration servlets, etc.)

2. Run the Servlet program

The first way to Run: directly On the file to Run (HTML/JSP/Servlet, etc.) --> right click -->Run as-->Run On Server, Eclipse will help us do the following things: 1) Publish the Web project (CGB-Servlet-01) to the server 2) start the Tomcat server 3) finally open the browser and enter the path in the address bar to access the Servlet Eclipse uses the built-in browser to access servlets by default, but this built-in browser is bugged and it is best to use a local browser to test! The second way of operation: you can manually publish the project to the server, start the server, open the browser to enter the address for access!

3. Configuration of Servlet in Web.xml file

Fully qualified class name (full class name): Package name. Class name or package name. < Servlet > < Servlet -name>HelloWorld</ Servlet -name> < Servlet -class>com.tedu.HelloWorld</ Servlet -class> </ Servlet > <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> 1) For each Servlet created, Eclipse will generate at least 8 lines of configuration information for us. These 8 lines of configuration information consist of a Servlet tag and a Servlet-Mapping tag. The <servlet-name> tag in the two tags is the same, which determines that they are a set of configurations 2)<servlet-class> tag The full class name (package name) of the current servlet class configured in the <servlet-class> tag. In the future, the server will find this full class name according to the access path, and then use reflection + full class name to get the instance of the current Servlet class 3)<url-pattern> tag is configured through which path the outside world should access the current Servlet. In other words, the external world has to use whatever path is configured to access the Servlet! Note 1: The configuration information of the Servlet in the web.xml file is generated for us by Eclipse when we create the Servlet. If the Servlet is not created through Eclipse (for example, it is copied),Eclipse will not generate the configuration information of the Servlet. Servlets are not accessible without configuration information (except for development using annotations)! Note 2: If the Tomcat Server fails to start for some unknown reason, you can delete the Server created by Eclipse and create a new one (delete the Server and also delete the Servers project on the left from the workspace!). Note 3: After integrating Tomcat with Eclipse, Tomcat turns on hot deployment by default: You can make changes to the code and run the latest effects without republishing or restarting the server! (If you create a new Servlet class, or change the web.xml file, you need to restart the server for it to take effect!)

4. Create a project with Servlet3.0 or higher

In the Servlet3.0 project, there is no web.xml file, so the Servlet information cannot be configured via XML file, but via annotations to configure the servlet-related information @WebServlet("/SecondServlet") public class SecondServlet extends HttpServlet{} The content configured in the @WebServlet annotation is the access path configured in the (XML)url-pattern In addition, the server can locate the current Servlet by scanning the annotation, get the full path of the class, load the class from the hard disk to the memory through the full path, get the bytecode object of the class, and then create the instance of the class by reflection + bytecode object!

5. How to configure Eclipse to run a Web resource with a local browser after right-clicking –>run as

If you have Chrome or Firefox on the right, you can select Default System. If you have Chrome or Firefox on the right, you can select Default System. , which is the default browser of the system

Request

I. Introduction of Request and Response

When the browser sends a Request to the server, the server will create a Request object representing the Request and a Response object representing the Response before calling the service method of the Servlet to process the Request. These two objects are passed to the service method. In the process of processing the request, if the service method wants to get the request information, it can get it through the method provided by the request. If you want to respond data to the browser, you can write the data to the response buffer first. When the service method finishes executing, the server will automatically get the data to be sent to the browser from the response object and send the data to the browser in accordance with the format of HTTP protocol.

1. Request parameters 1.1. What are Request parameters?

Request parameters are the data that the browser sends to the server when it sends the request. Such as: In the address bar you can concatenate parameters with question marks after the URL address, Bring data to the server http://www.baidu.com?user=zhangsan&psw=123&like=lanqiu You can also write data to form items through a form and bring data to the server by submitting the form Either way you bring parameters to the server, you can have more than one parameter, separated by an &, and each parameter contains the parameter name and parameter value

1.2. How to obtain request parameters?

http://www.baidu.com?user=zhangsan&psw=123&like=lanqiu&like=zuqiu 1)request.getParameter(String paramName) -- Returns a String -- the name of the request parameter, the value of the corresponding parameter. For example, if you pass "user" and return "zhangsan", the method will only return the first value if you get more than one parameter, for example, if you pass "like" and return only one "lanqiu" If there is no such thing as to obtain the parameters of the, this method returns null, such as the incoming uesr, returns null values (2) the request at this time. The getParameterValues (String paramName) - returns a String [] array - By requesting the name of the parameter, get the corresponding array composed of all parameter values. So if you pass in "like", return {"lanqiu", "Zuqiu "} -- This method still returns an array if only one parameter value is obtained, such as "user" and {"zhangsan"} -- NULL if no parameter is obtained, such as "uesr", which returns NULL

1.3. How to deal with the problem of Chinese garbled code when obtaining request parameters?

The GET submission parameter is to concatenate the parameter after the URL address, and to submit the parameter to the server. The POST submission parameter is to submit the parameter to the server through the request entity When the server receives the parameters submitted by GET, it defaults to UTF-8 for receiving (the browser also uses UTF-8 for submitting parameters), so there is no problem getting the parameters submitted by GET. However, when the server receives the parameters submitted by POST, it defaults to use ISO8859-1 to receive, and there are no Chinese characters in this code, so when receiving Chinese data, there will be garbled code problem. The solution is: notification server receives the POST submission of parameters, also receives the request through the utf-8. SetCharacterEncoding (" utf-8 "); Note: this line of code should be executed before the code that gets the parameters! This line of code only applies to POST submissions; GET comparisons are unaffected!

2. Realize request forwarding

The so-called request forward is a jump between resources inside the server (jump from one resource to another resource). 1) Forwarding is one request and one response; 2) The address bar does not change before and after forwarding; 3) Forwarding can only jump between two resources within the same Web application; 4) Data can be transferred between two resources forwarded by using Request Field (Map); /* Forward the request to testForward2 * testForward2: As the server http://localhost:8080/CGB-Servlet-03/TestForward2 * in front of the forward path automatically on the spelling of project path, so we in the paths, * only need to pass the path behind the project path, Project path and path does not pass * / request before getRequestDispatcher ("/TestForward2 "). The forward (request, response);

3. Used as a domain object (with forwarding required)

When requesting forwarding, the request object will be passed to the forwarded resource (A-- forwarding -->B, the request in A will be passed to B). Before forwarding, data can be stored in the map of the request and then forwarded, because forwarding will bring the request to the forwarded resource In the forwarded resources, the data carried in the map can be taken out again through the request! In ServletA, store data in the map of the request: request.setAttribute(String name, Object value); / / to forward the request to the ServletB request. GetRequestDispatcher (ServletB "path"). The forward (the req, res); In ServletB, you can pull data out of a map with request: request.getAttribute(String name);

Response

1. Redirect the request

Request Redirect features: 2) The address bar will change before and after the redirection. 3) There is no limit on the two resources to be redirected. They can be the same Web application, different Web applications or even different servers 4) In the process of redirection, it is not possible to bring data to the destination through the map set of the request: response.sendredirect (" the address of the resource redirected to "); Response.getWriter().write("<h1> Congratulations on your successful registration,5 seconds later will jump to the login page... </h1>"); response.setHeader( "Refresh", "5; url=http://localhost:8080/CGB-Servlet-03/login.html" ); The characteristics of timed refresh and redirect are almost the same, the only difference is that redirect (forward) is immediate jump, there is no time interval, timed refresh can specify how many seconds after the jump, before the jump, You can output a message to prompt the user (such as a message after successful registration: Congratulations on your successful registration,5 seconds later will jump to the login page...)