当前位置:网站首页>Three implementation methods of Servlet
Three implementation methods of Servlet
2022-07-29 02:30:00 【Medlar tea*】
List of articles
Preface
Servlet yes JavaWeb Of One of the three components , It's a dynamic resource .Servlet The role of is to process requests , The server will deliver the received request to Servlet To deal with it , stay Servlet We usually need :
Receive request data ;
Processing requests ;
Complete the response .
For example, the client issues a login request , Or output registration request , These requests should be made by Servlet To complete the process !Servlet We need to write it ourselves , Every Servlet Must be realized javax.servlet.Servlet Interface .
Tips : The following is the main body of this article , The following cases can be used for reference
One 、Servlet Life cycle
Servlet The default creation time : Create on the first request For the first time
init(): Execute on server startup
service : The service method , The server will execute when the update is turned on .
destroy: The method of destruction , Only execute once when the server is shut down normally .
getServletConfig(): obtain servlet Configuration information .
getServletInfo(): obtain servlet Some basic information of , For example, author , Copyright and so on
- Be careful : There is only one in memory servlet object , But it can be referenced by multiple classes , There are security issues , So try not to define member variables in its methods .
Two 、 Realization Servlet Three ways ?
Realization Servlet There are three ways :
Realization javax.servlet.Servlet Interface ;
Inherit javax.servlet.GenericServlet class ;
Inherit javax.servlet.http.HttpServlet class ;
Usually we will inherit HttpServlet Class to complete our Servlet, But learning Servlet Also from the javax.servlet.Servlet The interface begins to learn .
public interface Servlet {
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
public String getServletInfo();
public void destroy();
}
3、 ... and 、GenericServlet
summary :GenericServlet yes Servlet Implementation class of interface , We can do it through inheritance GenericServlet To write your own Servlet. Here is GenericServlet Source code of class :
public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
@Override
public void destroy() {
}
@Override
public String getInitParameter(String name) {
return getServletConfig().getInitParameter(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return getServletConfig().getInitParameterNames();
}
@Override
public ServletConfig getServletConfig() {
return config;
}
@Override
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
@Override
public String getServletInfo() {
return "";
}
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init()throws ServletException {
}
public void log(String msg) {
getServletContext().log(getServletName() + ": " + msg);
}
public void log(String message, Throwable t) {
getServletContext().log(getServletName() + ": " + message, t);
}
@Override
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
@Override
public String getServletName() {
return config.getServletName();
}
}
Realized Servlet Of init(ServletConfig) Method , Put parameters config Assigned to members of this class config, Then call the class's own nonparametric init() Method .
init()The method is GenericServlet Own way , Not from Servlet Inherited from . When we customize Servlet when , If you want to finish the initialization, don't repeat init(ServletConfig) The method , Instead, we should rewrite init() Method . Because in GenericServlet Medium init(ServletConfig) Method ServletConfig object , If you overwrite save ServletConfig Code for , Then you can't use ServletConfig 了 .stay GenericServlet in , Defined a ServletConfig config Instance variables , And in init(ServletConfig) Method ServletConfig Assigned to the instance variable . Then instance variables are used in many methods of this class config.
3.1GenericServlet Medium init()
- If subclasses cover GenericServlet Of init(StringConfig) Method , that this.config=config This statement will be overwritten , in other words GenericServlet Instance variable of config The value of is null, Then all dependencies config Can't use any of the methods . If you really want to complete some initialization operations , Then cover it GenericServlet Provided init() Method , It has no parameters init() Method , It will be init(ServletConfig) Method is called .
3.2 Realized ServletConfig Interface
- GenericServlet It's also achieved ServletConfig Interface , So you can call getInitParameter()、getServletContext() etc. ServletConfig Methods .
2.3.3 Realized ServletConfig Interface
Four 、HttpServlet
summary :HttpServlet Class is GenericServlet Subclasses of , It provides the right HTTP Special support requested , So usually we will inherit HttpServlet To complete the custom Servlet.
4.1
HttpServlet Class provides service(HttpServletRequest,HttpServletResponse) Method , The method is HttpServlet Own way , Not from Servlet inherited . stay HttpServlet Of service(ServletRequest,ServletResponse) The method will put ServletRequest and ServletResponse Strong conversion HttpServletRequest and HttpServletResponse, And then call service(HttpServletRequest,HttpServletResponse) Method , This shows that subclasses can cover service(HttpServletRequest,HttpServletResponse) The method can , There is no need to force the request and response objects .
In fact, subclasses do not need to cover service(HttpServletRequest,HttpServletResponse) Method , because HttpServlet There is another step to simplify the operation , We'll talk about that .
4.2 Implementation code
public abstract class HttpServlet extends GenericServlet {
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//... Code ellipsis
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try{
// Strong go
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
}catch(ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
// call service(HttpServletRequest,HttpServletResponse) Method
service(request, response);
}
// Other methods omitted ……
}
4.3 doGet() and doPost()
stay HttpServlet Of service(HttpServletRequest,HttpServletResponse) Method will judge whether the current request is valid GET still POST, If it is GET request , Then I will call this class doGet() Method , If it is POST The request will be called doPost() Method , This means that we can cover doGet() or doPost() The method can .
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hello doGet()...");
}
}
public class BServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hello doPost()...");
}
}
边栏推荐
- Explain the four asynchronous solutions of JS in detail: callback function, promise, generator, async/await
- 发布融资需求1.29亿元,大科城项目路演持续浇灌科创“好苗子”
- The outsourcing company "mixed" for two years, and I only did five things seriously. Now I get byte offer smoothly.
- 数据安全与隐私计算峰会-安全求交集在隐私计算中的发展和应用:学习
- redis为什么快,消息队列,单线程
- Problems encountered in special flow & properties property set instances and Solutions
- Branch management practice of "two pizza" team
- Responsive dream weaving template home decoration website
- virsh console连接失败问题
- Exploration and practice of network security vulnerability management
猜你喜欢

数据安全与隐私计算峰会-安全求交集在隐私计算中的发展和应用:学习

代码实现 —— 多项式的最大公因式(线性代数)

防止勒索软件攻击数据的十种方法

Meeting notice of meeting OA

When I look at the source code, what am I thinking?

Day 14: continued day 13 label related knowledge

当Synchronized遇到这玩意儿,有个大坑,要注意

Exploration and practice of network security vulnerability management

Remember error scheduler once Asynceventqueue: dropping event from queue shared causes OOM

I was stunned by this question that I browsed 746000 times
随机推荐
How does the Devops team defend against API attacks?
第3章业务功能开发(线索备注的删除和修改)
Chapter 3 business function development (deletion and modification of clue remarks)
Split, an avalanche caused by connection pool parameters
HTTP断点续传以及缓存问题
I want to talk about high concurrency.
DevOps 团队如何抵御 API 攻击?
Jmeter之BeanShell生成MD5加密数据写入数据库
工程经济学简答题
Excel uses countif statistics
When synchronized encounters this thing, there is a big hole, so be careful
Derivation of Euler angle differential equation
多线程浅谈
数据安全与隐私计算峰会-安全求交集在隐私计算中的发展和应用:学习
如果时间不够,无法进行充分的测试怎么办?
ES6 event binding (v-on usage)
Talk about the implementation principle of feign
C语言实现三子棋游戏
virsh console连接失败问题
What if there is not enough time for adequate testing?