Servlet中的Service、get、post方法的区别
Servlet类中有init、Service、destroy等几个方法。其中,Service方法又封装了doget方法和dopost方法。也就是说,在重写Servlet类的时候,只需要重写Service方法即可,不需要重写doget或dopost方法去处理请求。
在Service方法中,如果浏览器是通过post请求,会自动调用Service方法中的dopost方法去处理请求。
比如,在index.jsp文件中,使用get方法发送请求:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>JSP - Hello World</title> </head> <body> <h1><%= "Hello World!" %> </h1> <br/> <a href="hello-servlet">Hello Servlet</a> <form action="hello-servlet" method="get"> <input type="text" name="username"> <input type="submit"> <%-- <button>登录</button>--%> </form> </body> </html>
@WebServlet(name = "helloServlet", value = "/hello-servlet") public class HelloServlet extends HttpServlet { @Override public void init(ServletConfig servletConfig) throws ServletException { System.out.println("这是init方法"); } @Override public ServletConfig getServletConfig() { return null; } // @Override // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // req.setCharacterEncoding("utf-8"); // post请求从网页传过来的中文参数会乱码 // System.out.println("这是service方法"); // String str = req.getRequestURI() + ""; // System.out.println("请求链接" + str); // // // String str1 = req.getParameter("username"); // 获取客户端传递的参数 // System.out.println(str1); // } @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方法被启动"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { System.out.println("这是destroy方法"); } }
传入参数: 小鹿
这时候,控制台中会自动调用doget方法,输出doget方法(没有实现service方法)
而如果同时重写Service、get和post方法,最后输出的是: 这是Service方法。
说明当Service方法存在的时候,不管是否重写doget或者dopost方法,都会优先执行Service方法,然后Service方法调用自身内部的get方法或者post方法去处理请求。
所以一般处理请求只需要重写Service方法即可,不需要单独再写doget和dopost方法