标签:
转自:http://zhidao.baidu.com/link?url=8BI0cjlcFdBSJKHTZlpo874eqtbTJoZfrh3miQgM_05RvSER8skPiBc1wSPZtXT8OGGCHfVXFAzAosa6E5HBl_
内置对象
request:请求对象
request.getParameter("名字") 获得客户端输入的信息***************
request.getParameterValues("名字") 获得客户端输入的一组信息
request.getRequestDispatcher("url").forward(request,response): 转到url页面
response:响应对象
response.sednRedirect("url"):转到url指定的页面
转自:http://blog.csdn.net/a859522265/article/details/7259115
web服务器收到客户端的HTTP请求,会针对每一次请求分别创建一个用于代表请求的request对象和代表响应的response对象。
1.要得到客户机提交过来的数据,只需要找request对象就行了。
2、要向客户机输出数据,只需要找response对象就行了。
一、response对象
1.1向客户端发送数据,以字节为单位(一定要先设置编码方式,再输出)
- String data = "你好,中国1";
- OutputStream out = response.getOutputStream();
- out.write(data.getBytes());
- String data = "你好,中国2";
- OutputStream out = response.getOutputStream();
- out.write(data.getBytes("UTF-8"));
- response.setHeader("Content-Type","text/html;charset=UTF-8" );
- String data = "你好,中国3";
- OutputStream out = response.getOutputStream();
- out.write("<meta http-equiv=‘Content-Type‘ content=‘text/html;charset=UTF-8‘>".getBytes());
- out.write(data.getBytes("UTF-8"));
- String data = "你好,中国4";
- OutputStream out = response.getOutputStream();
- response.setContentType("text/html;charset=UTF-8");
- out.write(data.getBytes("UTF-8"));
- response.setContentType("text/html;charset=UTF-8");
等价于下面两句代码的效果:
response.setCharacterEncoding("UTF-8");//更改服务器发送数据的默认编码
response.setHeader("Content-Type","text/html;charset=UTF-8");//还要通知客户端解码方式
- int x=97;
- OutputStream out = response.getOutputStream();
- out.write((x+"").getBytes());
1.2 以字符为单位向客户端发送数据
String data = "你是谁?";
response.setCharacterEncoding("UTF-8"); //设置编码为UTF-8
response.setHeader("Content-Type", "text/html;charset=UTF-8");//告诉客户端编码方式
// 第二种方法:相当于以上两句代码
//response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();//默认编码是iso-8859-1 创建该对象前必须设置好编码方式
writer.write(data);
System.out.println(response.getCharacterEncoding());
1.3 让客户端以下载方式打开文件,解决中文文件名乱码问题(URLEncoder.encode(name, "UTF-8"))
- String realPath = getServletContext().getRealPath("/files/漂亮美眉.jpg");
- String name = realPath.substring(realPath.lastIndexOf("\\"));
-
- response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(name, "UTF-8"));
-
- InputStream in = new FileInputStream(realPath);
-
-
- OutputStream out = response.getOutputStream();
- int len = -1;
- byte buf[] = new byte[1024];
- while((len=in.read(buf))!=-1)
- {
- out.write(buf, 0, len);
- }
-
- in.close();
1.4 输出随机数字生成验证码图片
-
- response.addHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setHeader("Expires", "0");
-
-
- BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
-
-
- Graphics g = image.getGraphics();
-
-
- g.setColor(Color.GRAY);
- g.drawRect(0, 0, WIDTH, HEIGHT);
-
- g.fillRect(1, 1, WIDTH-1, HEIGHT-1);
-
-
- Random r = new Random();
- g.setColor(Color.BLUE);
- int x = 5;
- for(int i=0;i<4;i++)
- {
-
- g.setFont(new Font("宋体",Font.BOLD,20));
- g.drawString(r.nextInt(10)+"", x, 20);
- x+=30;
- }
-
-
- g.setColor(Color.YELLOW);
- for(int i = 0;i<9;i++)
- {
-
- g.drawLine(r.nextInt(WIDTH),r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
- }
-
-
- ImageIO.write(image,"jpeg",response.getOutputStream());<pre name="code" class="java">
- response.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);</pre><br>
- <pre></pre>
- <p></p>
- <pre></pre>
- 1.5 控制客户端刷新时间
- <p></p>
- <p></p>
- <pre name="code" class="java">
- response.getOutputStream().write("<meta http-equiv=\"Refresh\" content=\"3;URL=/day05/login.html\">".getBytes());</pre>1.6 控制客户端缓存时间
- <p></p>
- <p></p>
- <pre name="code" class="java">
- response.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);</pre><br>
- 1.7 用response实现请求重定向
- <p></p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_13292204202s0e.gif" alt=""></p>
- <p>特点:地址栏会变,发送两次请求,增加服务器负担。</p>
- <p>实现方式:response.sendRedirect()<br>
- 实现原理:302状态码和location头即可实现重定向<br>
- </p>
- <pre name="code" class="java">
- 注意
- response.setStatus(307);
- response.setHeader("location", "http://localhost:8080/day05/servlet/ResponseDemo1");</pre><br>
- 1.8 小细节
- <p></p>
- <p></p>
- <pre name="code" class="java"> String s1 = "abc";
- String s2 = "def";
- response.getOutputStream().write(s1.getBytes());
-
-
-
-
-
- <p><br>
- </p>
- <p>二、request(HttpServletRequest)对象</p>
- <p>2.1.get方法</p>
- <p></p><pre name="code" class="java"> String locale = request.getLocalName();
- String url = request.getRequestURL().toString();
- String uri = request.getRequestURI();
- String protocol = request.getProtocol();
- String add = request.getRemoteAddr();
- String host = request.getRemoteHost();
- String port = request.getRemotePort()+"";
- String method = request.getMethod();
- String localAddr = request.getLocalAddr();
- String username = request.getParameter("username");
- String serverPort = request.getServerPort()+"";
- String serverName = request.getServerName();
- 2.2 获取客户端请求头<p></p>
- <p></p><pre name="code" class="java"> response.setContentType("text/html;charset=UTF-8");
-
- PrintWriter out = response.getWriter();
-
- out.write(request.getHeader("Accept-Language")+"<br/>");
-
- Enumeration headers = request.getHeaders("user-agent");
- while(headers.hasMoreElements())
- {
- out.println(headers.nextElement()+"<hr/>");
- }
-
-
- Enumeration names = request.getHeaderNames();
- while(names.hasMoreElements())
- {
- String name = (String)names.nextElement();
- out.println(name+"="+request.getHeader(name)+"<br/>");
- }</pre><br>
- 2.3获取请求参数<p></p>
- <p>String usernameValue = request.getParameter("username");
- </p>
- <p></p><pre name="code" class="java">String names[] = request.getParameterValues("username");
- for(String name:names)
- {
- System.out.println(name);
-
- }</pre><pre name="code" class="java">
-
- Enumeration names = request.getParameterNames();
- while(names.hasMoreElements())
- {
- String name = (String)names.nextElement();
- System.out.println(name+"------->"+request.getParameter(name));
- }</pre><br>
- 2.4 封装到bean<br>
- <pre name="code" class="java">public class Student {
- private String[] username;
- private String password;
-
- public String[] getUsername() {
- return username;
- }
- public void setUsername(String[] username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
-
-
- }
-
- </pre><pre name="code" class="java">
- private void test5(HttpServletRequest request) {
-
- Map map = request.getParameterMap();
- Student s = new Student();
- try {
- BeanUtils.populate(s, map);
- } catch (IllegalAccessException e) {
-
- e.printStackTrace();
- } catch (InvocationTargetException e) {
-
- e.printStackTrace();
- }
- String[] names = s.getUsername();
- System.out.println(names[0]);
- System.out.println(names[1]);
- System.out.println(s.getPassword());
- }
- 2.5 得到请求正文<br>
- <pre name="code" class="java">
- InputStream in = request.getInputStream();
- byte[] buf =new byte[1024];
- int len = -1;
- while((len=in.read(buf))!=-1)
- {
- System.out.println(new String(buf,0,len));
- }</pre><br>
- 2.6解决请求参数的中文乱码<p></p>
- <p> get方式:先按照原编码得到原始字节码,然后再重新编码。如:name = new String(name.getBytes("ISO-8859-1"),"UTF-8");</p>
- <p>post方式:客户端是什么编码,发送的请求数据就是什么编码,根据客户端的编码,告知服务器编码方式。</p>
- <p>如:request.setCharacterEncoding("UTF-8");
- <p><br>
- </p>
- <p>2.7请求转发 forward</p>
- <p><span style="white-space:pre"></span>RequestDispatcher rd = request.getRequestDispatcher("path");
- <span style="white-space:pre"></span>rd.forward(request, response);<br>
- </p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_1329238218CM8E.gif" alt=""><br>
- </p>
- <p>2.8 包含include</p>
- <p><span style="white-space:pre"></span>RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo9");<br>
- <span style="white-space:pre"></span>rd.include(request, response);<br>
- </p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_1329238034rHHG.gif" alt=""><br>
- </p>
- <p>三 、路径的写法:<br>
- a、绝对路径写法:ServeltContext都必须用绝对路径。“/”开始 (如ServletContext.getRequestDispatcher("path") path必须是绝对路径)<br>
- b、相对路径:其他情况都可以使用相对路径,也可以使用绝对路径<br>
- <br>
- <br>
- c、在使用绝对路径时,要不要加"/"或者是项目名:如果是服务器调用的,不用加项目名,用“/”就可以代表了当前应用根目录<br>
- 如果是客户端调用的,必须加上项目名<br>
- <br>
- <br>
- 1、转发:request.getRequestDispather(String url)<br>
- 绝对路径:url /servlet/ServletDemo<br>
- 2、重定向:response.sendRedirect(String url)<br>
- 绝对路径:url /day05/servlet/ServletDemo<br>
- <br>
- <br>
- 3、超链接:<a href="url"/><br>
- 绝对路径:url /day05/servlet/ServletDemo<br>
- 4、类加载文件的路径<br>
- web应用中只能用相对路径,相对于classes目录的<br>
- 5、<fomr action="url"/><br>
- 绝对路径:/day05/servlet/ServletDemo<br>
- 6、页面分帧(frame)<br>
- 绝对路径:/day05/servlet/ServletDemo<br>
- 7、ServletContext.getRealPath(url)<br>
- 绝对路径:url /servlet/ServletDemo<br>
- <br>
- <br>
- URLEncoder.encode("name", "UTF-8")
- <p><br>
- </p>
- <p></p>
-
Request和Response详解
标签:
原文地址:http://www.cnblogs.com/name-hanlin/p/5059965.html