Http request and response

When the web server receives the http request from the client , it will create a request object representing the request and a response object representing the response for each request .



1. Response line HTTP/1.1 200 OK

  • setStatus(int sc) Set the response status code

2. Response header

  • ***** sendRedirect(String location) request redirection

  • setHeader(String name, String value) Set the response header information


    // Tell the browser what code table to use

    response.setHeader("content-type", "text/html;charset=UTF-8");


                  // Tell the client not to cache

                  response.setHeader("pragma", "no-cache");

                  response.setHeader("cache-control", "no-cache");

                  response.setDateHeader("expires", 0);



3. Response body (body)

  • *** getWrite(); character output stream

  • getOutputStream(); byte output stream

  • setCharacterEncoding(String charset) tells the server what encoding to use

  • *****setContentType(String type)


1. Request line 

Get  http://localhost:8080/day09/servlet/req1?username=zs  http/1.1

getMethod(); get the request method

***getRequestURL(); Returns the full URL when the client makes a request.

***getRequestURI(); Returns the resource name part of the request line.

*****getContextPath(); The virtual directory of the current application/day09_01_request

getQueryString() ; Returns the parameter part of the request line.

System.out.println(request.getMethod());//  GET
		System.out.println(request.getRequestURL()); // http://localhost:8080/day09_01_HttpServletRequest/servlet/demo1
		System.out.println(request.getRequestURI()); //   /day09_01_HttpServletRequest/servlet/demo1
		System.out.println(request.getContextPath()); //  /day09_01_HttpServletRequest
		System.out.println(request.getQueryString()); //  username=zs

2. Request message header

 * String getHeader(String name) Get the header information value according to the header name

 Enumeration getHeaderNames() get all header information name

 Enumeration getHeaders(String name) Get the same name header information value according to the header name

3. Request body (important)

Methods related to getting form data

<input type="text" name="username" />

*** getParameter(name) Get the value method of the value attribute according to the name of the name attribute in the form

*** getParameterValues ​​(String name) professional method for check box fetching

                getParameterNames() method to get all the names submitted by the form

*** getParameterMap to the method of all values ​​submitted by the form // used as a framework, very practical

getInputStream gets all form data as byte stream

	private void test4(HttpServletRequest request) {
		try {
			User u = new User();
			BeanUtils.populate(u, request.getParameterMap());		
		} catch (Exception e) {

	private void test3(HttpServletRequest request) {
		try {
			User u = new User();
			Map<String,String[]> map = request.getParameterMap();		
			for (Map.Entry<String, String[]> m : map.entrySet()) {
				String name = m.getKey();
				String[] value = m.getValue();			
				PropertyDescriptor pd = new PropertyDescriptor(name, User.class);
				Method setter = pd.getWriteMethod();
					setter.invoke(u, value[0]);//给一个值的变量赋值
					setter.invoke(u, (Object)value);//相关于给复选框赋值
		} catch (Exception e) {

	private void test2(HttpServletRequest request) {
		Enumeration names = request.getParameterNames();
			String name = (String) names.nextElement();//得到每一个name名
			String[] values = request.getParameterValues(name);//根据name名,得到value值
			for (int i = 0;values!=null && i < values.length; i++) {
	private void test1(HttpServletRequest request) throws UnsupportedEncodingException {
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		String[] hobbys = request.getParameterValues("hobby");		
		String city = request.getParameter("city");		
		userName = new String(userName.getBytes("iso-8859-1"),"UTF-8");
		for (int i = 0;hobbys!=null && i < hobbys.length; i++) {

Methods related to manipulating non-form data (request is also a domain object)

*** void setAttribute(String name, Object value);

*** Object getAttribute(String name);

Void removeAttribute(String name);


Methods related to request forwarding

//Get the helper object that the request forwards or the request contains

RequestDispatcher getRequestDispatcher(String path)

*** forward(ServletRequest request, ServletResponse response) //forwarding method

include(ServletRequest request, ServletResponse response) //请求包含


Methods related to request encoding:

/ / Solve the post method encoding

*****request.setCharacterEncoding("UTF-8"); //Tell the server what encoding the client is, and can only handle the post request method


/ / Solve the get method encoding

String name = new String(name.getBytes(“iso-8859-1”),”UTF-8”);



/*download file*/

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/美女.jpg");
		FileInputStream fis = new FileInputStream(path);
		ServletOutputStream sos = response.getOutputStream();	
		String filename = path.substring(path.lastIndexOf("\\")+1);	
		filename = URLEncoder.encode(filename, "UTF-8");//将不安全的文件名改为UTF-8格式	
		response.setHeader("content-disposition", "attachment;filename="+filename);
		response.setHeader("content-type", "image/jpeg");	
		int len = 1;
		byte[] b = new byte[1024];


Guess you like