HttpServletRequest接口实例化的使用

HttpServletRequ接口的使用和jsp内置对象的request对象非常类似,request对象其实

就是HttpServletRequest接口的一个实例,不过气实例化的过程是自动的,无须自定义。

以下示例达到的效果为:通过一个HttpServletRequest接口的实利化对象设置并取得

request范围属性的示例。

RequestDemo.java

 1 package com.mhb;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class RequestDemo extends HttpServlet {
12 
13 public void init() throws ServletException {
14 }
15 public void doGet(HttpServletRequest request, HttpServletResponse response)
16 throws ServletException, IOException {
17 
18 //设置输出内容的格式和编码
19 response.setContentType("text/html;charset=gb2312");
20 PrintWriter out = response.getWriter();
21 
22 //存储在request范围内
23 request.setAttribute("name", "测试者");
24 //取得request范围name的属性
25 String name = (String) request.getAttribute("name");
26 
27 out.println("");
28 out.println("");
29 out.println("name:"+name);
30 out.println("");
31 out.println("");
32 
33 }
34 public void doPost(HttpServletRequest request, HttpServletResponse response)
35 throws ServletException, IOException {
36 }
37 public void destroy() {
38 super.destroy();
39 }
40 }

浏览器显示:

HttpServletRequest接口实例化的使用_第1张图片

你可能感兴趣的:(HttpServletRequest接口实例化的使用)