重生day01

一、config初始化参数的获取、HttpServletRequest接口的常用方法(爸爸是ServletRequest)、HttpServletResponse(爸爸是ServletResponse)接口的常用方法

中文的请求中设置只是针对post,如果get那就需要修改server.xml中71行开始插入 URIEncoding="UTF-8"   但是在开发中一般都是post提交







	HttpServletRequestTest
	day01.HttpServletRequestTest
	
	  encoding
	  GBK
	


	HttpServletRequestTest
	/test




package day01;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpServletRequestTest extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		//获取初始化参数
		String encoding = config.getInitParameter("encoding");
		System.out.println(encoding);
		//这里还有个方法可以获得所有names
		Enumeration initParameterNames = config.getInitParameterNames();
	}

	@Override
	protected void service(HttpServletRequest requ, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置中文编码
		requ.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
//		System.out.println(requ.getMethod());
		//  01/test
//		System.out.println(requ.getRequestURI());
		//  http://localhost:8080/01/test
//		System.out.println(requ.getRequestURL());
		// / 01
//		System.out.println(requ.getContextPath());
		// 0:0:0:0:0:0:0:1
//		System.out.println(requ.getRemoteAddr());
		
		// 获取html里所有的头信息名称
//		Enumeration headerNames = requ.getHeaderNames();
//		while(headerNames.hasMoreElements()){
//			System.out.println(headerNames.nextElement());
//		}
//		System.out.println(requ.getHeader("cookie"));
		String username = requ.getParameter("username");
		String password = requ.getParameter("password");
		System.out.println(username+"---"+password);
		String[] hobby = requ.getParameterValues("hobby");
		System.out.println(Arrays.toString(hobby));
		
		//Map getParameterMap():返回所有的参数和值所组成的Map对象。
		Map parameters = requ.getParameterMap();
        Set paramNames = parameters.keySet();
        for (String param : paramNames) {
            String[] value = parameters.get(param);
            System.out.println(param + ":" + Arrays.asList(value));
        }
        //字符流输出
		//PrintWriter writer = resp.getWriter();
		//writer.println("你好");
        
		//字节流输出,两个输出流不能同时存在。下载的时候使用
		ServletOutputStream out = resp.getOutputStream();
		out.write("你好response".getBytes());
	}
	

}


你可能感兴趣的:(重生day01)