代码如下:
package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WqServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<p>你好</p>"); out.close(); } } 注意:一般使用protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {}如果要使用public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {},则必须先将两个参数类型转换后使用
还可以使用doGet()和doPost()方法,只是这两个方法只能对于同一类型的请求才有效
总结:在处理请求的时候,可以使用1.protected void service 2.public void service 3.doGet() 4.doPost()
一般使用第一种,因为参数使用更方便