jsp中doGet和doPost的区别

来源:互联网 发布:淘宝上的劣质充气娃娃 编辑:程序博客网 时间:2024/06/06 03:42
Serlvet接口只定义了一个服务方法就是service,而HttpServlet类实现了该方法并且要求调用下列的方法之一:
doget:处理GET请求
doPost:处理POST请求

当发出客户端请求的时候,调用service 方法并传递一个请求和响应对象。Servlet首先判断该请求是GET 操作还是POST 操作。然后它调用下面的一个方法:doget或 doPost。如果请求是GET就调用doget方法,如果请求是POST就调用doPost方法。 doget和doPost都接受请求(HttpServletRequest)和响应(HttpServletResponse)。

1.doGet
GET 调用用于获取服务器信息,并将其做为响应返回给客户端。当经由Web浏览器或通过HTML、JSP直接访问Servlet的URL时,一般用GET调用。 GET调用在URL里显示正传送给SERVLET的数据,这在系统的安全方面可能带来一些问题,比如用户登录,表单里的用户名和密码需要发送到服务器端, 若使用Get调用,就会在浏览器的URL中显示用户名和密码。
例:
jsp页代码:
<form action="/doGet_servlet" name=”form1” method="get">
………
<input type="text" name="username">
………
</form>
servlet代码:
public class doGet_servlet extends HttpServlet {
  public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
      request.setCaracterEncoding(“UTF-8”);//汉字转码
      String username = request.getParameter("username");

request.setAttribute("username",username);

       request.getRequestDispatcher("/out.jsp").forward(request, response);//跳转到out.jsp页面

 

 

 

  }
}

out.jsp页面

<html>

``````

<%=request.getAttribute("username")%>//在页面上输出username的信息

</html>
这样提交表单后,参数会自动添加到浏览器地址栏中,带来安全性问题。

2.doPost
它用于客户端把数据传送到服务器端,也会有副作用。但好处是可以隐藏传送给服务器的任何数据。Post适合发送大量的数据。
例:
jsp页代码:
<form action="/doPostt_servlet" name=”form2” method="post">
………
<textarea name="name2" cols="50" rows="10"></textarea>
………
</form>
servlet代码:
public class doPostt_servlet extends HttpServlet {
  public void doPost(HttpServletRequest request,HttpServletResponse esponse) throws IOException,ServletException {
      request.setCaracterEncoding(“UTF-8”);//汉字转码
      PrintWriter out = response.getWriter();
      out.println("The Parameter are :"+request.getParameter("name2"));
  }
}
最好用上面在doGet中提到的输出方式进行输出



原创粉丝点击