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 .

 

一、HttpServletResponse

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);

     

    RefereshRefresh

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)

二、HttpServletRequest

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();
			System.out.println("封装数据前:"+u);		
			BeanUtils.populate(u, request.getParameterMap());		
			System.out.println("封装数据后:"+u);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void test3(HttpServletRequest request) {
		try {
			User u = new User();
			System.out.println("封装数据前:"+u);
			//获取表单数据
			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);
				//得到setter属性
				Method setter = pd.getWriteMethod();
				
				if(value.length==1){
					setter.invoke(u, value[0]);//给一个值的变量赋值
				}else{
					setter.invoke(u, (Object)value);//相关于给复选框赋值
				}
			}
			
			System.out.println("封装数据后:"+u);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void test2(HttpServletRequest request) {
		//获取所有的表单name的名子
		Enumeration names = request.getParameterNames();
		while(names.hasMoreElements()){
			String name = (String) names.nextElement();//得到每一个name名
			String[] values = request.getParameterValues(name);//根据name名,得到value值
			for (int i = 0;values!=null && i < values.length; i++) {
				System.out.println(name+"\t"+values[i]);
			}
		}
	}
	private void test1(HttpServletRequest request) throws UnsupportedEncodingException {
		//获取表单数据		
		//根据表单中name属性的名,获取value属性的值方法 
		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");
		System.out.println(userName);
		System.out.println(pwd);
		System.out.println(sex);
		
		for (int i = 0;hobbys!=null && i < hobbys.length; i++) {
			System.out.print(hobbys[i]+"\t");
		}
		System.out.println();
		
		System.out.println(city);
	}

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];
		while((len=fis.read(b))!=-1){
			sos.write(b,0,len);
		}	
		sos.close();fis.close();
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478676&siteId=291194637