Service 和 doGet 和 doPost 方法的区别
新建一个JSP文件:
get方式
post方式
service方法、doGet方法和doPost方法的区别:
在上面的步骤中,把下图中的method方法给改了
改变上图,改成下图的样子。重复上述操作:
将会得到以下结果:
service方法、doGet方法和doPost方法的区别
* service方法:可以处理get/post方式的请求,如果servlet中有service方法,会优先调用service方法
* doGet方法: 处理get方法的请求
* doPost方法: 处理post方式的请求
* 注意:如果在覆写的service方法中调用了父类的service方法 super.service(arg0, arg1);
* 则service方法处理完后,会再次根据请求方式响应的doGet和doPost方法执行
* 所以,一般情况下,是不在覆写的service中调用父类的service方法的,避免出现405错误
package com.cl.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* service方法、doGet方法和doPost方法的区别
* service方法:可以处理get/post方式的请求,如果servlet中有service方法,会优先调用service方法
* doGet方法: 处理get方法的请求
* doPost方法: 处理post方式的请求
* 注意:如果在覆写的service方法中调用了父类的service方法 super.service(arg0, arg1);
* 则service方法处理完后,会再次根据请求方式响应的doGet和doPost方法执行
* 所以,一般情况下,是不在覆写的service中调用父类的service方法的,避免出现405错误
* @author Administrator
*
*/
public class ServletMethod extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
System.out.println("我是service");
super.service(arg0, arg1);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("我是doGet方法");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("我是doPost方法");
}
}
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>02-MyServlet</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>servletLife</servlet-name>
<servlet-class>com.cl.servlet.servletLife</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServletMethod</servlet-name>
<servlet-class>com.cl.servlet.ServletMethod</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletLife</servlet-name>
<url-pattern>/life</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletMethod</servlet-name>
<url-pattern>/method</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>