Servlet处理get和post请求

Servlet处理请求:

  • 处理所有请求:service()
  • 处理Get请求: doGet()
  • 处理Post请求: doPost()

service()里无论get,post请求都会被处理:
 

public class SampleServlet extends HttpServlet {

	/**
	 * service方法无论get,post请求都会被处理
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO 自动生成的方法存根

		// 获取何种请求方式:get,post
		String methodName = request.getMethod();

		String name = request.getParameter("name");
		String mobile = request.getParameter("mobile");
		String sex = request.getParameter("sex");
		String specs[] = request.getParameterValues("spec");
		PrintWriter out = response.getWriter();// 向浏览器输出的数据流
		out.println("<h1>methodName:" + methodName + "</h1>");
		out.println("<h1>name:" + name + "</h1>");
		out.println("<h1>mobile:" + mobile + "</h1>");
		out.println("<h1>sex:" + sex + "</h1>");
		for (int i = 0; i < specs.length; i++) {
			out.println("<h1>spec:" + specs[i] + "</h1>");
		}
		out.println("<a href='http://www.baidu.com/'>Baidu</a>");
	}

}

 

Servlet分别处理get和post请求


public class RequestMethodServlet extends HttpServlet {
	//处理Get请求,方法名必须叫doGet
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String name=request.getParameter("name");
		response.getWriter().println("<h1 style='color:red'>name:"+name+"</h1>");
	}
	
	//处理Post请求,方法名必须叫doPost
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String name=request.getParameter("name");
		response.getWriter().println("<h1 style='color:blue'>name:"+name+"</h1>");
	}
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页