Servlet Technical documentation (one step learning, become a master)

Source: Internet
Author: User
Tags connection pooling



Servlet Notes Document


Servlet, server-side applet, which is relative to applets, applets are client applets.
Servlets, which accept requests from the network (form forms, and other requests) and respond differently to different requests
Servlet, which is based on the HTTP protocol, is a program that runs on a Web server. The concept of a container is presented here.
The servlet is run in a Web container, which is explained in detail later in this web container, which controls the life cycle of the Servlet object, and the control request is handled by the Servlet object.
Web server, where the server is not the concept of hardware, but the software, the common Web server has Tomcat,jboss, etc., we use the Tomcat is an open source server, Tomcat is a Java language written in the Web server, So there needs to be a corresponding Java runtime environment, the JVM, and the specific path of Tomcat to be configured.
Configuration of Tomcat

java_home=/xxx/xxx/(JDK path, up-level directory in bin)
Catalina_home=/xxxx/xxx (Tomcat's absolute path in Windows X:\xxx\xxx)
When you start Tomcat, you are running startup.sh (using Startup.bat in Windows) in the bin directory of Tomcat
To determine if Tomcat is successful, you can use http://localhost:8080/or http://127.0.0.1:8080/in the address bar of the browser to access the Tomcat home page that was successfully started. To stop the Tomcat server from using shutdown.sh (using Shutdown.bat in Windows), if you close the Startup window directly, it will cause 8080 port occupancy error, you can use shutdown.sh to shut down the server.
Startup.sh,shutdown.sh,shutdown.bat,startup.bat These files are actually some script files used to execute a lot of commands, that is, a lot of Java commands.
The default listener port for Tomcat is port 8080, and when each connection request is received, it is assigned a thread.
Tomcat can identify the resources only in the WebApps folder, WebApps is the Web Application folder, WebApps folders in these folders are Web applications, Web applications are formatted, each Web application folder must have
Web-inf folder, Web-inf folder has classes, and Lib folder, as well as a Web. xml file, some used to the class file in classes, some used to the corresponding jar file.
Note: Use a limited amount of resources to release.
The root default app is configured in Tomcat, which is accessed by default when not specified.
Web. xml file notation
<?xml version= "1.0" encoding= "Iso-8859-1"?>
<! DOCTYPE Web-app
Public "-//sun Microsystems, INC.//DTD Web application 2.3//en"
"Http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
</web-app>
In the Tomcat server, access to resources under the app can be seen by name on the Web App folder in the port number back rack
http://localhost:8080/xxxxx/xxxx.html, a static page can only be placed under a folder in the Web application and cannot be placed in
Under the Web-inf folder, the resources in the Web-inf folder are protected and cannot be accessed over the network.
Servlet Basics


Servlet, can implement dynamic page, can respond to different requests, can realize the flow of the page, servlet can act as the CTRL module in MVC mode, he can control the flow of information.
The Web server searches the classes folder under the Web-inf folder for the class file to be loaded, so the class file we write is placed under the Classes folder under the Web-inf folder in the Web App.
How to set the class and access for a servlet
Configuration of the Web. xml file, multiple Servlets can be configured in a Web. xml
<! DOCTYPE Web-app
Public "-//sun Microsystems, INC.//DTD Web application 2.3//en"
"Http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>servlet's name </servlet-name>
<servlet-class>servlet class name </servlet-class>
</servlet>
<servlet>
<servlet-name>servlet's name 1</servlet-name>
<servlet-class>servlet class full Name 1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet's name (to be the same as in the servlet tag) </servlet-name>
<url-pattern> specify the path of the servlet relative to the app directory </url-pattern>
</servlet-mapping>
Servlet-mapping>
<servlet-name>servlet's name 1</servlet-name>
<url-pattern> specify the path of the servlet relative to the app directory </url-pattern>
</servlet-mapping>
</web-app>


Catalina.sh run starts the Tomcat server with the console.
The invocation procedure of the servlet
1, the user sends a request to the Web server through the browser
Http://serverip:port/apppath
2, the server locates the resource for the user
Static resources:/a.html/a/b.html (the path here is for the Web App folder directory) to read the file and send the contentSend to Client
Dynamic resources: Parsing Web. XML locating the name of the Servlet class
Load Class (web-inf/classes| Web-inf/lib/*.jar)
Create an instance of the object
Servlet ser= (servlet) (Class.forName ("Servle class name")). newinstance ();
We write a servlet that must implement a servlet interface or inherit a class that implements a Servlet interface
Ser.service (Request,response);

<servlet-mapping>
<servlet-name>servlet's name (to be the same as in the servlet tag) </servlet-name>
<url-pattern> specify the path of the servlet relative to the app directory </url-pattern>
</servlet-mapping>
Url-parttern configuration, this URL is the servlet's virtual path, you can use a relative path or an absolute path.
/xxx/xxx (absolute path), XXX (relative path), try to use absolute path.
Ways to access a servlet
http://serverip:port/Application Folder name/url-pattern
Requests for HTTP
Get request, POST request.
A GET request writes parameters to the address bar when the request is made, and the POST request does not display the parameters to be sent on the address bar.
<form method= "Get" action= "app name/url-pattern" >
......
</form>
We can get the parameters that are passed in the request by means of the ServletRequest object.
The GetParameter (String name) method allows you to obtain a parameter of the specified name in a form, with the same name as a multi-parameter.
Getparameternames (), an iterator enumeration can be obtained to obtain the name of the parameter in the form form.

Getparametervalues (String name) Gets the value of all parameters specified with the same name.

(2)

The service () method in the implementation class of the Servlet interface, when inheriting the HttpServlet class, if the service () method of the parent class is not overridden, then the service () method of the parent class will call the overridden doget (), depending on the request type. DoPost () method, the service () method can be overridden directly if the action in response to both requests is the same. If you overwrite the
Doget (), one of the DoPost () methods, then only one request will be made accordingly. In the browser's address bar operation Press ENTER, or a hot connection, is a GET request, the method property of form if not specified, the default is a GET request.
We can get the parameters that are passed in the request by servletrequest the object or the HttpServletRequest object.
The GetParameter (String name) method allows you to obtain a parameter of the specified name in a form, with the same name as a multi-parameter.
Getparameternames (), an iterator enumeration can be obtained to obtain the name of the parameter in the form form.
Getparametervalues (String name) Gets the value of all parameters specified with the same name.
Get request, the parameter is displayed in the browser's address bar, its display format, after the address will start with a question mark, with ' & ' to separate parameters, you can get the parameter value of the GET request by the HttpServletRequest object's GetQueryString () method.
The getInputStream () method of the ServletRequest object can obtain an input stream from the socket, which can be used to upload the file. The Getreader () method can get the parameters of the post request directly.
The ServletContext object is the context object of the servlet, which is created when the server is started and can be viewed as
An applied object that can be seen as an object that contains a servlet that manages a servlet.
The life cycle of the servlet
Classes that conform to the servlet specification can produce objects (reflection mechanisms) through the server and process requests.
Methods in the Servlet interface
Implementing a Servlet interface
public class Testservlet implements Servlet {
ServletConfig config;
public void init (ServletConfig config) throws servletexception {
This.config=config;
This ServletConfig object is generated by the server, which is provided by the system,
Through which he can get boot information. The ServletConfig object and the servlet are one by one corresponding.
This method is called after the servlet has been created. If you use the ServletConfig object is aYou must assign a value to the object.
}
Public ServletConfig Getservletconfig () {
return this.config;
}
public void Service (ServletRequest request, servletresponse response) throws Servletexception, IOException {
...;//This method is the core method used to process the request
}
Public String Getservletinfo () {
Return "...";//This is used to write the servlet information, to write the author, and version information
}
public void Destroy () {
...;//This method is used to destroy the Servlet object's
}


}
Both HttpServlet and Genericservlet implement the Servlet interface.
The service (HttpServletRequest request,httpservletresponse response) method in HttpServlet is through the service (ServletRequest request, Servletresponse response) method is called to implement the processing of the request.
The life cycle of a servlet is divided into four stages
1, create a Servlet object that creates a Servlet object through the server reflection mechanism, which is created the first time the request is made. Default
2, call the Servlet object's init () method, initialize the servlet's information, and the Init () method is called only once after it is created
3, responding to requests, invoking service () or doget (), DoPost () methods to handle requests, these methods are running in multithreaded state.
4, the Destroy () method is called to destroy the Servlet object when it has not been called for a long time or when the server is shut down.
You can configure the creation time of a Servlet object through the Web. xml file.
<load-on-startup> digital </load-on-startup&gt, which means that the server is created at startup and is created sequentially according to the number size, which is used only by important servlets.
Initialization parameters can be configured with the <init-param> tag, which can be used with the ServletConfig object's
The Getinitparameter (String name) method to get the arguments.

<init-param>
<param-name>...</param-name>
<param-value>...</param-value>
</init-param>
Multi-threaded operation of the variable, if the operation is a variable, and read and write operations, it is necessary to consider adding synchronization, but synchronization can not be added, otherwise it will cause deadlock problems.
Both the Init () and Destroy () methods are run under a single thread.
The Init method in the Genericservlet class that has a parameter and no parameters.
public void init (ServletConfig config) throws Servletexception
{
this.config = config;
Init ();
}
public void Init () throws Servletexception
{
....//the Non-parametric init () method that is overridden when the servlet is created invokes the parameter Init method
will also be called.
}

The invocation relationship of a service method with different parameters in the HttpServlet class.
public void Service (HttpServletRequest req,httpservletresponse res) {
.......;
.......;
}
public void Service (ServletRequest req, servletresponse Res)
Throws Servletexception, IOException
{
HttpServletRequest request;
HttpServletResponse response;
Try
{
Request = (httpservletrequest) req;
Response = (httpservletresponse) res;
}
catch (ClassCastException e)
{
throw new Servletexception ("Non-http Request or response");
}
Service (request, response);
}


Resource access for Servlets
Resources such as Jdbc,rmi (remote method calls), and components across language platforms, can be accessed in the servlet.
It is easy to use JDBC in a servlet, that is, to invoke a method in JDBC in a servlet to gain access to the database.


(3)

Resource access for Servlets
If you want to use other resources in the servlet, such as the drive to connect to the database, it can be placed under the common/lib of the Tomcat server folder, which contains some common resources that will be loaded when the server is started, usually in order to use specific resources in the application. That is, the jar file, then do not put under the Common/lib, if common/lib under the jar file too much will cause the server to start slowly, the application used in the jar file to be placed under the Web-inf/lib, you can be found by the server.
If you are using Hibernate to access the database in a servlet, then you need to put the jar file that hibernate needs into web-inf/lib, Xxxxxx.hbm.xml or the entity class. Hibernate.cgf.xml file, you should put it under the web-inf/classes.
MVC Framework
Models, the model layer, this layer is generally for database access, and encapsulated objects, this layer is also stored in the Access database to extract information encapsulated into the object class, that is, the entity class information, you can use JDBC or hibernate to achieve this layer of functionality.
Ctrl, which controls once, is used to request and invoke the appropriate method of accessing the database, this layer is used to control the response of the request, and now we use the servlet to implement this layer, but generally using an open-source MVC framework to implement this layer, such as struts, Or it's the Spring MVC framework.
View, Presentation layer, he only used to display data and collect the necessary data, the collection of data is generally form forms, but to ensure that the correctness of the data if you use JavaScript to verify the information, we will learn in the future JSP (Java Server page) is used to express, display data.
The method setattribute (String name,object o) in the HttpServletRequest object can be used to carry information using the HttpServletRequest object and can be getattribute ( String name) method to obtain the information that is carried, which is similar to the access method in map, the SetAttribute method assigns the data to the identity, and the GetAttribute method obtains the data by this identifier. The premise to use this pair of methods is to ensure that the same request object (HttpServletRequest)
Control flow of the servlet
Servletcontext,servlet the context object, there will be a servletcontext reference in each servlet, and this ServletContext is a global object, There is only one ServletContext object in each app.
The Getservletcontext () method in HttpServlet obtains the ServletContext object.
The Getrequestdispatcher (String Path) method of the ServletContext class obtains a RequestDispatcher object and jumps to the specified servlet,getrequestdispatcher The parameter in the (String path) method is path, which is the url-pattern of the servlet that specifies the jump.
The forward (ServletRequest request, Servletresponse Response) method of the RequestDispatcher class allows the request object to be forwarded to other servlets.
Database connection pool, that is, in the absence of a program to take a connection, you can create a good connection in advance, connection pooling is a running in a multi-threaded environment, to provide a database connection of the program, the program is the database connection after the shutdown of the database connection action is no longer close the connection, but put the database connection back to the connection pool That is, the database connection is already idle and can be used by other programs.
Configure the data source for the Tomcat server
Tomcat users are configured in the Tomcat-users.xml file in the Conf directory under Tomcat
<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
<tomcat-users>
<role rolename= "manager" description= ""/>
<role rolename= "Admin"/><!--Configuration Manager--
<user username= "manager" password= "123" Fullname= "" roles= "manager"/>
<user username= "admin" password= "123" roles= "admin"/>
<!--Configure the Administrator's username and password and indicate that the administrator roles= "admin"--
</tomcat-users>
<resource
Name= "jdbc/oracle" Configuration Jdni Name
Type= type of "javax.sql.DataSource" binding resource
Password= "sd0605"
Driverclassname= "Oracle.jdbc.driver.OracleDriver" driver name
maxidle= "1" Maximum number of connections
maxwait= "-1" Wait time, configured to 1 is infinite wait, only until there is idle connection
Username= "sd0605"
Url= "JDBC:ORACLE:THIN:@192.168.0.39:1521:TARENADB"
Maxactive= "3" Maximum number of active connections/>
The following is the code to fetch the database connection from the connection pool
public static Connection getconnection (String jndiname)
{
Connection conn = null;
Try
{
Context initctx = new InitialContext ();
Context Envctx = (context) initctx.lookup ("java:comp/env");
This is the default binding context under Tomcat Jndiname
DataSource ds = (DataSource) envctx.lookup (jndiname);
conn = Ds.getconnection ();
} catch (Namingexception ne)
{
Ne.printstacktrace ();
} catch (SQLException se)
{
Se.printstacktrace ();
}
Return conn;
}


Java EE Programming tiering
Presentation layer, business layer, data layer.
The presentation layer, even if it is used to display data, accepts data. Jsp,servlet
The business layer is the process of processing the core business Ejb,jdbc (Hibernate)
The data layer, which is the database, is used to store data. Oracle,sqlserver

(4)

The Url-pattern of the servlet
Url-pattern can be used in the following three ways
1, exact path matching, that is, to give a definite path xxx/xxxx
2, fuzzy path matching, that is, to give a part of the path, xxxx/*, he will match the determined path, that is, xxxx/a or xxxx/b can be matched
3, the extension matches, which will match the extension, as long as the extension is identical, xxx.xxx *.xx
Note: extension matching and exact path matching cannot be used together, that is, they cannot be written as xxxx/xxxx/xxx.xx, but can be used
*.xxx.
Three ways to return a path to a ServletRequest object
Getcontextpath () Get the application path and get the application path dynamically
Getservletpath () obtains the servlet path, which is the action in the form, and if the exact path is used, it will be the url-pattern of the servlet configuration.
GetPathInfo () returns the matching Blur section when using fuzzy path matching.
Note: In the action of the form form of HTML, if the extension match is used, be sure to state/xxxxx/xxx.xx, do not write/xxxx/*.xx, in the action of the form to use absolute path, that is to use the application name/ xxx.xx or application name/xxx.
Singlethreadmodel interface
1) If you want to prohibit multi-threaded access, you can let the servlet use the Singlethreadmodel interface: public class Yourservlet extends HttpServlet implements Singlethread Model{...} 2) With this interface, the system guarantees that there will be no multiple request threads accessing a single instance of the servlet at the same time. However, you still need to synchronize access to class variables or shared fields that are stored outside the servlet. 3) If the servlet is frequently accessed, the synchronization of the servlet access will severely affect performance (latency).
The life cycle of the ServletRequest object is in the service () method, except for the forward (...,...) Method forwards the request object to the other servlet.
Session (sessions) and cookies
The session object is used to solve a storage problem where the client requests information when sending multiple requests, but he and the ServletRequest object are different and will be created when necessary, but his life cycle will be longer than the requested object. The lifetime of the session object is also limited, and if it is not accessed for a long time, the session object will be destroyed and the session object can be
SetAttribute (string name, Object O) and getattribute (string name) to access data information. The session is a user-level object.
public void Service (ServletRequest request,servletresponse response) {
String user = Request.getparameter ("user");
String pass = request.getparameter ("Pass");
HttpSession session = Request.getsession (true);//Use the Request object to create a session
Session.setattribute ("username", user);
Session.setattribute ("passwd", pass);
}
GetSession (True) indicates that a new session is created if the session does not exist, and that the session's identity SessionID written to the cookie, if it exists, it is used in this session. GetSession (false) does not create a new session when the session does not exist but returns NULL. If you use the GetSession () method, it is equivalent to GetSession (true).
Note: The ServletRequest object is suitable for transmitting large amounts of data because of its short life cycle, which can effectively conserve memory resources.
The transfer or preservation of large data volumes is not suitable for using session space.
A Cookie is a record of the user's session information, or the user's request information, that is, SessionID, to identify which user has logged in. The cookie is also sent back to the server on each login, and the cookie is used to track the session.
public void Service (ServletRequest request,servletresponse response) {
String user = Request.getparameter ("user");
String pass = request.getparameter ("Pass");
Cookie Usercookie = new Cookie ("user", user);
Usercookie.setmaxage (60 * 60 * 24 * 365);//Set the maximum lifetime of the cookie, in seconds
Cookie Passcookie = new Cookie ("Pass", pass);
Passcookie.setmaxage (60 * 60 * 24 * 365);
Response.addcookie (Usercookie);
Response.addcookie (Passcookie);


}

HttpServletResponse class
HttpServletResponse is used to respond to a user's actions, and it enables page redirection.
Sendredirect (String location), which specifies the servlet to be accessed using this method, whose parameters are the servlet's Url-pattern
If a redirect is used, the original request object is not preserved.


(5)

Servlet Filters and listeners
Servlet Filters (Filter)
A filter is a request and a response that filters the servlet, and the filter exists between the request and the requested resource.
Filter is like when in a middleware, the request to go through the filter, then the filter to remove the response with Servlet,servlet will be intercepted by the filter and processed accordingly.
Filter is an interface, to write a filter on its own can only implement the filter interface.
Filter also has its own life cycle, and his life cycle is similar to the servlet, and will call the Init () method first, and then call the core processing filtering Method Dofilter (), which can define the filter rule, then Destory () method to destroy the filter object.
Dofilter (ServletRequest request,servletresponse response,filterchain chain)
This is the core method of filtering, Filterchain method Dofilter (ServletRequest request, servletresponse response) is the method of invoking resources with the filtered requests, if you do not write this method, Even if you do not call the appropriate resource.
Configuration of filter
The configuration of the filter is similar to the servlet.
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>alan.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/protected/*</url-pattern>
<!--here Url-pattern is the url-pattern--> of the servlet to be filtered
<dispatcher>request</dispatcher>
<dispatcher>forward</dispatcher>
<dispatcher>include</dispatcher>
<!--the top three is the filter range--
</filter-mapping>
The Chararraywriter class is an output stream that holds data in a character array, and we can use it to construct a PrintWriter object, which also implements the output to memory. The ToString () and ToCharArray () methods of the Chararraywriter class can get data written to memory.
Note: The Chararraywriter class is a class that will not actually output, and his write () method will only write the contents to an array of characters, and the character array will automatically grow.
Servlet Listener
The following are 3 listener interfaces.
Servletrequestlistener
Httpsessionlistener
Servletcontextlistener
These three listener interfaces, respectively, monitor the creation and destruction of objects in 3 comparisons in a servlet. The three interfaces each have a way to listen for the object creation and destruction events, the server itself is the event source.
Configuration of the Listener
<listener>
<listener-class>alan.servlet.listener.AlanContextListener</listener-class>
<!--Listener-class is the class that implements the listener interface--
</listener>

Important objects in the servlet (for apps only)






Servlet Technical documentation (one step learning, become a master)

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.