Service方法,doGet方法,doPost方法:
- Service方法:可以处理get/post方式的请求,如果servlet中有Service方法,则服务器会优先调用service方法进行处理。
- doGet方法:处理get方法的请求。
- doPost方法:处理post方法的请求。
- 注意:如果在覆写service方法中调用了父类的service方法(super.service(arg0,arg1)),那么service方法处理完后,会再次根据请求方式响应doGet/doPost方法并执行。所以,一般不在覆写service方法的情况下调用父类的service方法。
代码学习:复制粘贴吧,先看效果在学习哦!
项目下创建包:com.ly.servlet,然后再在包下创建类:ServletMethod,之后复制下面代码:
package com.ly.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletMethod extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
System.out.println("我是service方法!");
resp.getWriter().write("我是service方法!");
super.service(req, resp);//一般覆写service方法而不调用父类service
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("我是doGet方法");
resp.getWriter().write("我是doGet方法");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("我是doPost方法");
resp.getWriter().write("我是doPost方法");
}
}
Web.xml配置:(一样的套路,一样的学习)
<?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>Test_WEB1</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>ServletMethod</servlet-name>
<servlet-class>com.ly.servlet.ServletMethod</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletMethod</servlet-name>
<url-pattern>/method</url-pattern>
</servlet-mapping>
</web-app>
运行结果:
控制台结果:
浏览器结果: