request的作用:
get方法中:1、获取请求参数 2、获取项目的虚拟路径 3、获取转发器、转发
post方法中:1、给浏览器响应一个字符串或者页面 2、重定向
转发与重定向的区别:
1、转发是发一次请求,重定向是发了两次请求
2、转发地址栏无变化,重定向地址栏有变化
3、转发可以访问WEB_INF下的资源,重定向不可以
4、转发可以共享request域中的数据,重定向不可以
public class AutoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//get请求
//get请求解决中文乱码的事情,在server.xml配置文件第一个Connector标签中加一个属性URIEcoding="utf-8"
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet请求!");
//request的作用
//1、获取请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + " " + password);
//2、获取项目的虚拟路径(context环境 )
String contextPath = request.getContextPath();
System.out.println(contextPath);
//3、转发
//获取转发器
RequestDispatcher requestDispatcher = request.getRequestDispatcher("success.html");
//转发
requestDispatcher.forward(request, response);
}
//post请求
//post请求解决中文乱码的事情,在第一次获取请求参数之前设置字符集为utf-8:request.setCharacterEncoding("UTF-8");
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost请求!");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + " " + password);
//解决相应乱码的方案:在获取流之前设置响应数据的类型
//response.setContentType("text/回头ml;charset=UTF-8");
response.setContentType("text/回头ml;charset=UTF-8");
//post的作用
//1、给浏览器响应一个字符串或者一个页面
PrintWriter writer = response.getWriter();
writer.write("响应成功");
//2、重定向
response.sendRedirect("success.html");
}
}