JavaWeb request用法

request封装了所有的请求信息

如:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("请求方法:"+request.getMethod());
		System.out.println("URI:"+request.getRequestURI());
		System.out.println("URL:"+request.getRequestURL());
		//获取所有请求头信息
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			System.out.println(key+"  "+value);
		}
	}

结果:

JavaWeb request用法_第1张图片


1、request请求中如果有中文可能会导致乱码

乱码的原因是在html中使用utf-8编码,Tomcat服务器使用iso-8859-1编码,到servlet中处理,再传递给浏览器则会导致乱码

如以下代码:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		System.out.println(username);
	}

请求链接为:http://localhost:8888/requestDemo/encodeservlet?username=张飞

结果:

可以这样解决get请求乱码问题:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		//解决get请求中文乱码问题
		username=new String(username.getBytes("iso-8859-1"),"utf-8");
		System.out.println(username);
	}

结果:


用上面这种方法有时对post乱码不起作用:

可以在方法中这样写:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username=request.getParameter("username");
		//解决get请求中文乱码问题
		//username=new String(username.getBytes("iso-8859-1"),"utf-8");
		System.out.println(username);
	}

2、request可以接收浏览器传来的参数或者存储数据,并传递给别的Servlet:

如在servlet1中:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");//获取来自服务器的数据
		request.setAttribute("zx","zhangxiang");//存储自定义数据
		request.getRequestDispatcher("servlet2").forward(request, response);//请求转发到servlet2
	}

在servlet2中:

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getParameter("username"));//获取request传递的参数
		System.out.println(request.getAttribute("zx"));
	}

你可能感兴趣的:(Java,Web)