JavaWeb 后端 <三> 之 Response Request
1. 响应对象 Response(重点:HTTP协议响应部分)
查看 HttpServletResponse
set是 有这个头 修改 没有添加一个新的 和 add 有点小区别
案例:
1.1 字节流向客户端输出中文数据 ServletOutputStream
//字节流向客户端输出中文数据 public class ResponseDemo1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(response); } //解决方案一:更改浏览器的码表(不建议) //解决方案二(不建议):向客户端输出一个<meta>标签,模拟了响应消息头:<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'> //out.write("<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>".getBytes()); //解决方案三(建议):向客户端输出响应消息头:response.setHeader("Content-Type", "text/html;charset=UTF-8"); //解决方案四(建议):向客户端输出响应消息头response.setContentType("text/html;charset=UTF-8"); //字节流输出数据查UTF-8 private void test2(HttpServletResponse response) throws IOException { String data = "不见了远处的青山"; response.setContentType("text/html;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); out.write(data.getBytes("UTF-8"));//默认情况下:浏览器是乱码的(他默认查GBK) } //字节流输出数据查本地码表 private void test1(HttpServletResponse response) throws IOException { String data = "不见了远处的青山"; ServletOutputStream out = response.getOutputStream(); out.write(data.getBytes());//String: getBytes()查本地默认的码表GBK getBytes(String charset)查指定码表 }
1.2 字符流输出中文数据 PrintWriter
//字符流输出中文数据 public class ResponseDemo2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "幸福是什么呢"; //改变字符流查的码表,还能告知客户端用UTF-8进行解码 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //HttpServletResponse的实例由Tomcat服务器提供,默认查ISO-8859-1的。 //Tomcat8.X ,默认编码就变为了UTF-8 out.write(data); } private void test1(HttpServletResponse response) throws IOException { String data = "幸福是什么"; //改变字符流查的码表 response.setCharacterEncoding("UTF-8"); //告知客户端用UTF-8进行解码 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();//HttpServletResponse的实例由Tomcat服务器提供,默认查ISO-8859-1的。 //Tomcat8.X ,默认编码就变为了UTF-8 out.write(data); }
1.3 输出随机验证码图片:CAPTCHA图像
//输出随机验证码图片:CAPTCHA图像 public class ResponseDemo3 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 120; int height = 25; //创建一副内存图像 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //得到画笔 Graphics g = image.getGraphics(); //开始画 //边线 g.setColor(Color.BLUE); g.drawRect(0, 0, width, height); //填充背景色 g.setColor(Color.YELLOW); g.fillRect(1, 1, width-2, height-2); //话干扰线 g.setColor(Color.GRAY); Random r = new Random(); for(int i=0;i<9;i++) g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); //验证码 g.setColor(Color.RED); g.setFont(new Font("宋体", Font.ITALIC|Font.BOLD, 19)); // String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6"; int x = 20; for(int i=0;i<4;i++){ g.drawString(r.nextInt(10)+"", x,20 ); // g.drawString(base.charAt(r.nextInt(base.length()))+"", x, 20); x+=18; } //输出 response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
html
<body> <form action="" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"/><br/> <input type="text" size="3" name="code"/><img id="img1" src="/day08_00_response/servlet/ResponseDemo3"/><a href="javascript:change()">看不清</a><br/> <input type="submit" value="登录"/> </form> <script type="text/javascript"> function change(){ var imgObj = document.getElementById("img1"); imgObj.src="/day08_00_response/servlet/ResponseDemo3?time="+new Date().getTime();//浏览器发现地址没有变化,根本不发请求 } </script> </body>
1.4 定时刷新 登陆跳转等待
//控制客户端定时刷新 public class ResponseDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test2(response); } //定时刷新到别处 private void test2(HttpServletResponse response) throws IOException { response.setContentType("text/htm;charset=UTF-8"); response.setHeader("Refresh", "2;URL=http://www.huyifan.cn"); response.getWriter().write("登录成功,2秒后跳转到主页"); } //定时刷新自己 private void test1(HttpServletResponse response) throws IOException { Random r = new Random(); // response.setHeader("Refresh", "1"); response.setIntHeader("Refresh", 1); response.getWriter().write(r.nextInt()+""); }
1.5 控制缓存时间
//控制缓存的时间 //静态资源需要控制缓存时间 //动态资源一般不要缓存 public class ResponseDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "不见了远处的青山"; //让他缓存1个小时 response.setDateHeader("Expires", System.currentTimeMillis()+1*60*60*1000); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(data); }
1.6 请求重定向
//演示请求重定向:可以重定向到任何地址上 //发出2次请求 //地址栏会发生变化 public class ResponseDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("http://www.huyifan.com"); } //重定向到应用内的资源 private void test1(HttpServletResponse response) throws IOException { // response.setStatus(302); // response.setHeader("Location", "/day08_00_response/servlet/ResponseDemo7"); response.sendRedirect("/day08_00_response/servlet/ResponseDemo7"); }
public class ResponseDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("I am yif"); // response.getOutputStream().write("a".getBytes()); }
细节:
1、字节流和字符流互斥,只能用其中一个。
2、response的流用完之后自动关(服务器关)
2. 请求对象 Request(重点:HTTP协议请求部分)
2.1 HttpServletRequest对象的生命周期
诞生:请求来了
死亡:响应结束
2.2 也是一个域(范围)对象:请求范围
request
Map
setAttribute
getAttribute
removeAttribute‘
2.2 开发中尽量用绝对路径
绝对路径:要不要加应用名称
地址给服务器用的:/就代表当前应用
地址给客户端用的:/应用名demo
2.3 HttpServletRequest中的常用方法
public class RequestDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getMethod();//请求方式 String uri = request.getRequestURI();// /day08_01_request/servlet/RequestDemo1 String url = request.getRequestURL().toString();// http://localhost:8080/day08_01_request/servlet/RequestDemo1 String protocal = request.getProtocol();//客户端使用的协议 String remoteIp = request.getRemoteAddr();//来访者的ip int port = request.getRemotePort();// 随机的 String queryString = request.getQueryString();//GET方式:/day08_01_request/servlet/RequestDemo1?username=abc&password=123 //username=abc&password=123 System.out.println(method); System.out.println(uri); System.out.println(url); System.out.println(protocal); System.out.println(remoteIp); System.out.println(port); System.out.println(queryString); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.4 获取请求消息头
public class RequestDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test3(request); } //得到所有的消息头 private void test3(HttpServletRequest request) { Enumeration<String> e = request.getHeaderNames(); while(e.hasMoreElements()){ String headerName = e.nextElement();//透明称 Enumeration<String> headerValues = request.getHeaders(headerName); while(headerValues.hasMoreElements()){ System.out.println(headerName+":"+headerValues.nextElement()); } } } //http协议是允许头有重复的情况,多个重名的头 private void test2(HttpServletRequest request) { Enumeration<String> e = request.getHeaders("Accept-Encoding");//得到的头值 while(e.hasMoreElements()){ String headerValue = e.nextElement(); System.out.println(headerValue); } } //得到指定请求消息头的值。如果没有该头,返回null private void test1(HttpServletRequest request) { String supportEncoding = request.getHeader("Accept-Encoding"); if(supportEncoding.contains("gzip")){ System.out.println("支持gzip压缩"); }else{ System.out.println("不支持gzip压缩"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.5 获取请求参数
public class RequestDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test8(request, response); } //终极解决方案:借助BeanUtil框架 jar包直接放在 web-inf 的 ;lib 文件夹里就ok private void test8(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = new User(); System.out.println("封装前:"+user); try { BeanUtils.populate(user, request.getParameterMap()); } catch (Exception e) { e.printStackTrace(); } System.out.println("封装后:"+user); } //getParameterMap获取参数:封装到JavaBean中 private void test7(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //key:请求参数名 value:请求参数值数组 Map<String,String[]> map = request.getParameterMap(); User user = new User(); System.out.println("封装前:"+user); for(Map.Entry<String, String[]> me:map.entrySet()){ String paramName = me.getKey();//参数名称 String paramValues[] = me.getValue();//参数值 try { PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class); Method m = pd.getWriteMethod();//setter方法 if(paramValues.length>1){ m.invoke(user, (Object)paramValues);//参考补充视频:反射main方法 }else{ m.invoke(user, paramValues); } } catch (Exception e1) { e1.printStackTrace(); } } System.out.println("封装后:"+user); } //getParameterMap获取参数 private void test6(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //key:请求参数名 value:请求参数值数组 Map<String,String[]> map = request.getParameterMap(); for(Map.Entry<String, String[]> me:map.entrySet()){ System.out.println(me.getKey()+"="+Arrays.asList(me.getValue())); } } //把请求参数的值封装到JavaBean中 //约定优于编码:表单的输入域的name取值和JavaBean中的属性(getter和setter方法)保持一致 private void test5(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration<String> e = request.getParameterNames();//参数名 User user = new User(); System.out.println("封装前:"+user); while(e.hasMoreElements()){ String paramName = e.nextElement();//即是JavaBean中的属性名称 String paramValue = request.getParameter(paramName); // setUsername(paramValue); setPassword(paramValue); //JavaBean的内省 try { PropertyDescriptor pd = new PropertyDescriptor(paramName, User.class); Method m = pd.getWriteMethod();//setter方法 m.invoke(user, paramValue); } catch (Exception e1) { e1.printStackTrace(); } } System.out.println("封装后:"+user); } // private void test4(HttpServletRequest request, HttpServletResponse response) // throws ServletException, IOException { // User user = new User(); // System.out.println("封装前:"+user); // String username = request.getParameter("username"); // String password = request.getParameter("password"); // String gender = request.getParameter("gender"); // user.setUsername(username); // user.setPassword(password); // user.setGender(gender); // System.out.println("封装后:"+user); // } //以下内容只用简单的程序开发 //获取所有的请求参数名和值 private void test3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration<String> e = request.getParameterNames();//参数名 while(e.hasMoreElements()){ String paramName = e.nextElement(); String values [] = request.getParameterValues(paramName); System.out.println(paramName+"="+Arrays.asList(values)); } } //获取重名请求参数的值 private void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username");//不区分get还是post的 String passwords[] = request.getParameterValues("password");//获取重名的请求参数值 System.out.println(username+":"+Arrays.asList(passwords)); } //获取单一的请求参数的值(用户所有的输入都是String) private void test1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username");//不区分get还是post的 String password = request.getParameter("password"); System.out.println(username+":"+password); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
domain
public class User { private String username; private String password[]; private String gender; public String getUsername() {//读属性,属性名称username return username; } public void setUsername(String username) {//写属性,属性名username this.username = username; } public String[] getPassword() { return password; } public void setPassword(String[] password) { this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "User [username=" + username + ", password=" + Arrays.toString(password) + ", gender=" + gender + "]"; } }
public class Student { private int id;//BeanUtil对于基本类型自动转换 private String name; private String password; private String gender; private boolean married; private String[] hobby; private String province; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", password=" + password + ", gender=" + gender + ", married=" + married + ", hobby=" + Arrays.toString(hobby) + ", province=" + province + ", description=" + description + "]"; } }
<form action="/day08_01_request/servlet/RequestDemo4" method="post"> 用户名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"/><br/> 确认密码:<input type="password" name="password"/><br/> 性别:<input type="text" name="gender" value="male"/> <input type="submit" value="注册"/> </form>
2.4 以输入流的形式接收请求正文:POST
一般情况下用不着,文件上传时使用。
public class RequestDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletInputStream in = request.getInputStream(); int len = -1; byte b[] = new byte[1024]; while((len=in.read(b))!=-1){ System.out.println(new String(b,0,len)); } in.close(); }
2.5 获取常用表单输入域的值
type:radio checkbox ,如果用户一个都没有选,客户端是根本不会传参数到服务器的。
public class RequestDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test3(request,response); } //请求编码和响应编码没有关系 private void test3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8");//设置请求正文的编码。只对POST有效 Student s = new Student(); System.out.println("封装前:"+s); try { BeanUtils.populate(s, request.getParameterMap()); } catch (Exception e) { e.printStackTrace(); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(s.toString()); } //get请求方式的编码问题 private void test2(HttpServletRequest request) throws UnsupportedEncodingException { String username = request.getParameter("name");//是二进制数据 %E6%9D%8E%E5%9B%9B byte b[] = username.getBytes("ISO-8859-1"); username = new String(b,"UTF-8"); System.out.println(username);//二进制转为字符,用ISO-8859-1的 } //获取请求正文的参数乱码问题 private void test1(HttpServletRequest request) throws UnsupportedEncodingException { request.setCharacterEncoding("UTF-8");//设置请求正文的编码。只对POST有效 Student s = new Student(); System.out.println("封装前:"+s); try { BeanUtils.populate(s, request.getParameterMap()); } catch (Exception e) { e.printStackTrace(); } System.out.println("封装后:"+s); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
<form action="/day08_01_request/servlet/RequestDemo5" method="post"> <input type="hidden" value="438" name="id"/> <table border="1" width="438"> <tr> <td>姓名</td> <td> <input type="text" name="name"/> </td> </tr> <tr> <td>密码</td> <td> <input type="password" name="password"/> </td> </tr> <tr> <td>性别</td> <td> <input type="radio" name="gender" value="male" checked="checked"/>男性 <input type="radio" name="gender" value="female"/>女性 </td> </tr> <tr> <td>婚否</td> <td> <input type="checkbox" name="married"/> </td> </tr> <tr> <td>爱好</td> <td> <input type="checkbox" name="hobby" value="eat"/>吃饭 <input type="checkbox" name="hobby" value="sleep"/>睡觉 <input type="checkbox" name="hobby" value="java"/>学Java </td> </tr> <tr> <td>籍贯</td> <td> <select name="province"> <option value="BJ">北京</option> <option value="SD">山东</option> <option value="HB">湖北</option> </select> </td> </tr> <!-- <tr> <td>靓照</td> <td> <input type="file" name="image"/> </td> </tr> --> <tr> <td>简介</td> <td> <textarea rows="3" cols="38" name="description"></textarea> </td> </tr> <tr> <td colspan="2"> <!-- <input type="submit" value="注册"/> --> <!-- <input type="image" src="an-0333.gif"/> --> <input type="button" value="注册" onclick="toSubmit()"/> </td> </tr> </table> <script type="text/javascript"> function toSubmit(){ //验证用户的输入 document.forms[0].submit(); } </script> </form>
编码:
2.6 请求转发
//转发:源 //源和目标:共享请求范围中的数据 public class RequestDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("p", "ppp"); //ServletContext:地址的写法。必须以"/",代表当前应用。(应用开头的绝对路径) // RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/RequestDemo7"); //绝对路径 // RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo7"); //相对路径 RequestDispatcher rd = request.getRequestDispatcher("RequestDemo7"); rd.forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//转发:目标 public class RequestDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s = (String)request.getAttribute("p");//注意和getParameter没有关系 response.getWriter().write(s); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
请求与重定向区别
2.7 包含:源 服务器端行为
public class RequestDemo8 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("我喜欢"); RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo9"); rd.include(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
public class RequestDemo9 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("成都"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2.8 请求 和 包含 的小细节
//转发前后,源输出的任何响应正文无效 public class Forward1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Refresh", "1"); System.out.println("转发前"); response.getWriter().write("forward before");//转发前会清空响应对象中的正文内容 request.getRequestDispatcher("/servlet/Forward2").forward(request, response);//转发 System.out.println("转发后"); response.getWriter().write("forward after"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//转发:目标 public class Forward2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("222222");//响应结束 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//包含:源 //只会包含目标的正文,头部信息包含前清空 public class IncludeDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("11111"); request.getRequestDispatcher("/servlet/IncludeDemo2").include(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
//包含:目标 public class IncludeDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setIntHeader("Refresh", 1); response.getWriter().write("22222"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }