Servlet (Getting Started)
Servlet: a small program running on the server
Servlet is an interface that defines the rules for java classes to be accessed by the browser (tomcat recognition)
step:
-
Create a project
-
Define a class and implement the interface
public class ServletDemo01 implements Servlet
-
Abstract method to implement interface
-
Configure Servlet file
Configuration file in web.xml
<servlet>
<servlet-name>ServletDemo01</servlet-name>
<servlet-class>cn.lsk.Servlet.ServletDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo01</servlet-name>
<url-pattern>/sd</url-pattern>
</servlet-mapping>
Principle of execution:
- When the server receives the request from the client browser, it will parse the request URL path to obtain the resource path of the accessed servlet.
- Look up the web.xml file and see if there is a corresponding tag body content.
- If so, find the corresponding full class name
- Tomcat will load the bytecode file into memory and create its object
- Call its method
Servlet method (life cycle)
-
Create: Execute the init method only once
When was the servlet created?
By default, the Servlet is created when it is accessed for the first time
You can also configure the creation timing of the execution Servlet (in Web.xml)
If the value is positive, it will be created when the server starts
If it is a negative number, it is created when it is accessed for the first time
<load-on-startup> -4 </load-on-startup>
The init method of Servlet is executed only once, indicating that a Servlet has only one object in the memory, and the Servlet is singleton
When multiple users access at the same time, there may be thread safety issues
Solution: try not to define member variables in the Servlet, if you define it, do not modify the value
-
Provide service: execute Servlet method, execute multiple times
It will be executed once for every visit
-
Destroy: Execute the destroy method, only once
Only the server is shut down normally, the destroy method will be executed
public class ServletDemo02 implements Servlet {
/**
* 初始化方法
* 在Servlet被创建时,执行。只会执行一次
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("我被创建了,我只执行一次");
}
/**
* 获取ServletConfig对象
* ServletConfig: Servlet的配置对象
* /
@Override
public ServletConfig getServletConfig() {
return null;
}
/*
* 提供服务的方法
* 每一次Servlet被访问时,执行。执行多次
*
* */
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("Hello WDNMD");
}
/*
* 获取Servlet的一些信息,版本,作者等等···
*
* */
@Override
public String getServletInfo() {
return null;
}
/*
* 销毁方法
* 在服务器正常关闭时,执行,执行一次
*
* */
@Override
public void destroy() {
System.out.println("GG");
}
}
The first execution:
If we refresh
It can be seen service
again and call init
initialization method is performed only once
If we shut down the server normally
Servlet annotation configuration:
step:
-
Create project
-
Define a class to implement the interface
-
Copy method
-
Use @WebServlet annotation on the class for configuration
@WebServlet("Resource Path")
@WebServlet("/sd3")
public class ServletDemo03 implements Servlet {
/**
* 初始化方法
* 在Servlet被创建时,执行。只会执行一次
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("我被创建了,我只执行一次");
}
/*
* 获取ServletConfig对象
* ServletConfig: Servlet的配置对象
* */
@Override
public ServletConfig getServletConfig() {
return null;
}
/*
* 提供服务的方法
* 每一次Servlet被访问时,执行。执行对此
*
* */
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("注解");
}
/*
* 获取Servlet的一些信息,版本,作者等等···
*
* */
@Override
public String getServletInfo() {
return null;
}
/*
* 销毁方法
* 在服务器正常关闭时,执行,执行一次
*
* */
@Override
public void destroy() {
System.out.println("GG");
}
}
Servlet architecture
Servlet (interface)
GenericServlet
(Abstract class) He implements the Servlet interface
//部分源码
public abstract class GenericServlet implements Servlet,
ServletConfig,
Serializable {
}
HttpServlet (abstract class) it inheritsGenericServlet
//部分源码
public abstract class HttpServlet extends GenericServlet {
}
Let's look at the functions of the two abstract classes separately:
Let's not implement the Servlet interface but inherit GenericServlet
@WebServlet("/sd3")
public class ServletDemo04 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest,
ServletResponse servletResponse)
throws ServletException, IOException {
}
}
Enter the GenericServlet source code, we can see: (only part of the source code)
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
//方法空实现 只有声明
public void destroy() {
}
//方法空实现 只有声明
public void init() throws ServletException {
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}
We can see that he made empty implementations of other methods, and only abstracted one method is the ** service
** method. So we inherit GenericServlet
only rewrite service
method
HttpServlet
There is a service method in the Servlet method. What shall we do in the service in the future?
-
Determine the request method
String mehod = request.getMethod();
if(“GET”.equals(mehod )){
// get way to get data
doGet();
}else if(“POST”.equals(mehod )){
// post data acquisition mode
doPost();
}
-
retrieve data
But our HttpServlet has written the above code for us
@WebServlet("/sd3")
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("doGet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
System.out.println("doPost");
}
}
Request through browser is get request
Access through the form is a Post request
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/sd5" method="post">
<input name="username">
<input type="submit" value="提交">
</form>
</body>
</html>
Introduce comments
-
If you choose Create Java EE 6 annotated class
It creates a succession
HttpServlet
ofServlet
web.xml:
<servlet>
<servlet-name>ServletDemo06</servlet-name>
<servlet-class>cn.lsk.Servlet.ServletDemo06</servlet-class>
</servlet>
//需要自己编写
<servlet-mapping>
<servlet-name>ServletDemo06</servlet-name>
<url-pattern>/sd6</url-pattern>
</servlet-mapping>