首页 > 代码库 > JAVAWEB开发之HttpServletResponse和HttpServletRequest详解(下)(各种乱码、验证码、重定向和转发)
JAVAWEB开发之HttpServletResponse和HttpServletRequest详解(下)(各种乱码、验证码、重定向和转发)
HttpServletRequest获取请求头信息
(1)获取客户机请求头
String getHeader(String name)
Enumeration<String> getHeaders(String name)
Enumeration<String> getHeaderNames()
(2)获取具体类型客户机请求头
int getIntHead(String name)
long getDateHead(String name) 日期对应毫秒
(3)常见的请求头
referer 记住当前网页的内容,用于防盗链
User-Agent 判断浏览器(MSIE IE浏览器,Firefox 火狐浏览器,Chrome 谷歌浏览器)
if-modified-since 控制缓存
防盗链案例
[java] view plain copy
- // 遍历所有请求头信息
- Enumeration<String> names = request.getHeaderNames();
- while (names.hasMoreElements()) {
- String name = names.nextElement();
- System.out.println(name + ":" + request.getHeader(name));
- }
- System.out.println("-----------------------------------------");
- System.out.println("您使用浏览器:" + request.getHeader("user-agent"));
- String referer = request.getHeader("referer");
- // 判断referer是否存在和有效
- if (referer != null && referer.startsWith("http://localhost/day6")) {
- // 不属于盗链
- response.setContentType("text/html;charset=utf-8");
- response.getWriter().println("机密信息");
- } else {
- // 盗链
- response.setContentType("text/html;charset=utf-8");
- response.getWriter().println("您的请求是盗链");
- }
HttpServletRequest获取请求参数(以及POST或GET请求乱码解决方法)
String getParameter(String name) 通过name获取一个值
String[] getParameterValues(String name) 通过name获取多个值 checkbox
Enumeration getParameterNames() 获取所有请求参数的名称
Map<String,String[]> getParameterMap()
可以提交请求的两种方式
1>.使用<form>
执行form的submit,提交form表单。
常用表单元素
<input type=[text | password | radio | checkbox | submit ]>
<select>…<option>
<textarea>
2>.使用URL链接
<a href="http://www.163.com?name=abc&password=123"> 点击链接 </a>
这样通过?可以提交参数,&用来分隔多个参数,
效果和<form>的GET方式相同
解决乱码问题:
1>.使用<form>
执行form的submit,提交form表单。
常用表单元素
<input type=[text | password | radio | checkbox | submit ]>
<select>…<option>
<textarea>
2>.使用URL链接
<a href="http://www.163.com?name=abc&password=123"> 点击链接 </a>
这样通过?可以提交参数,&用来分隔多个参数,
效果和<form>的GET方式相同
解决乱码问题:
(1)POST请求乱码
request.setCharacterEncoding("UTF-8");
(2)GET请求乱码
解决方案一:修改tomcat/conf/server.xml
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
* 必须有修改tomcat服务器配置文件权限
解决方案二:逆向编码解码
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
* 必须有修改tomcat服务器配置文件权限
解决方案二:逆向编码解码
username = URLEncoder.encode(username,"ISO-8859-1");
username = URLDecoder.decode(username,"UTF-8");
解决方案三:简写的方式(推荐使用)
username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
request获取中文数据乱码(总结:)
post提交 设置request缓冲区的编码 request.setCharacterEncoding("utf-8");
get提交 * String构造方法 username = new String(username.getBytes("ISO-8859-1"),"utf-8");
非空有效校验
if (username != null && username.trim().length() > 0) {
System.out.println("username 有效");
}else{
// username 无效
}
post提交 设置request缓冲区的编码 request.setCharacterEncoding("utf-8");
get提交 * String构造方法 username = new String(username.getBytes("ISO-8859-1"),"utf-8");
非空有效校验
if (username != null && username.trim().length() > 0) {
System.out.println("username 有效");
}else{
// username 无效
}
URL特殊字符转义规则:
常用转义规则
空格换成加号(+)
+换成%2B
正斜杠(/)分隔目录和子目录 换成%2F
问号(?)分隔URL和查询 换成%3F
百分号(%)制定特殊字符 换成%25
#号指定书签 换成%23
&号分隔参数 换成%26
java.net.URLEncoder和 java.net.URLDecoder
空格换成加号(+)
+换成%2B
正斜杠(/)分隔目录和子目录 换成%2F
问号(?)分隔URL和查询 换成%3F
百分号(%)制定特殊字符 换成%25
#号指定书签 换成%23
&号分隔参数 换成%26
java.net.URLEncoder和 java.net.URLDecoder
URL编码和解码
1) 浏览器提交一次请求,请求中中文字符,自动进行URL编码 (由浏览器完成)
2) web服务器接收到内容之后,自动URL解码
URLEncoder 完成URL编码 , URLDecoder 完成URL解码
服务器端接收请求,请求url : http://localhost/day6/request3?name=aaa+bbb
问题:在服务器端执行 request.getParameter("name"); 值 aaa bbb
1) 浏览器提交一次请求,请求中中文字符,自动进行URL编码 (由浏览器完成)
2) web服务器接收到内容之后,自动URL解码
URLEncoder 完成URL编码 , URLDecoder 完成URL解码
服务器端接收请求,请求url : http://localhost/day6/request3?name=aaa+bbb
问题:在服务器端执行 request.getParameter("name"); 值 aaa bbb
HttpServletRequest利用请求域传递对象
域对象:所知道的已经有两个域对象了
ServletContext:服务器一启动,为每个web应用创建一个ServletContext对象,所有servlet实例共享对象。
request:一次请求的范围。
request:一次请求的范围。
request对象同时也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理
setAttribute方法
getAttribute方法
removeAttribute方法
getAttributeNames方法
request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发,从而共享请求中的数据
setAttribute方法
getAttribute方法
removeAttribute方法
getAttributeNames方法
request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发,从而共享请求中的数据
请求转发传递数据
请求转发forward 和 请求重定向redirect 区别 ???
1) 转发一次请求 一次响应; 重定向两次请求 两次响应
2) 转发URL地址 不变,重定向URL地址改变第二个资源地址
3) 转发只能转发给同一个网站内部资源,重定向可以定向到任何网站
4) 转发中/属于服务器内部路径 不写工程名,重定向/来自客户端必须要写工程名
创建RequestServlet4 RequestServlet5
* 使两个Servlet连续执行 1) 重定向 2) 转发
最佳应用:Servlet处理数据得到数据处理结果,通过请求转发,将处理结果传递JSP显示
* Servlet处理数据获得结果,JSP负责数据显示
request.setAttribute传递数据,必须要结合 request.getRequestDispatcher().forward 转发一起使用!!!
请求转发forward 和 请求重定向redirect 区别 ???
1) 转发一次请求 一次响应; 重定向两次请求 两次响应
2) 转发URL地址 不变,重定向URL地址改变第二个资源地址
3) 转发只能转发给同一个网站内部资源,重定向可以定向到任何网站
4) 转发中/属于服务器内部路径 不写工程名,重定向/来自客户端必须要写工程名
创建RequestServlet4 RequestServlet5
* 使两个Servlet连续执行 1) 重定向 2) 转发
最佳应用:Servlet处理数据得到数据处理结果,通过请求转发,将处理结果传递JSP显示
* Servlet处理数据获得结果,JSP负责数据显示
request.setAttribute传递数据,必须要结合 request.getRequestDispatcher().forward 转发一起使用!!!
请求重定向和请求转发的具体区别:
- RequestDispatcher.forward方法只能将请求转发给同一个WEB应用中的组件;而HttpServletResponse.sendRedirect方法还可以重定向到同一个站点上的其它应用程序中的资源,甚至是使用绝对URL重定向到其它站点的资源。
- 如果传递给HttpServletResponse.sendRedirect方法的相对URL以"/"开头,它相对于服务器的根目录;如果创建ResquestDispatcher对象时指定的相对URL以"/"开头,它是相对于当前WEB应用程序的根目录。
- 调用HttpServletResponse.sendRedirect方法重定向的访问过程结束后,浏览器地址栏中显示的URL会发生变化,由初始的URL地址变成重定向的目的URL;调用RequestDispatcher.forward方法的请求转发过程结束后,浏览器地址栏保持初始的URL地址不变。
- HttpServletResponse.sendRedirect方法对浏览器的请求直接作出响应,响应的结果就是告诉浏览器去重新发出对另外一个URL的访问请求;RequestDispatcher.forward方法在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求并得到了响应结果,并不知道在服务器程序内部发生了转发行为。
- RequestDispatcher.forward方法的调用者与被调用者之间共享相同的request对象和response对象,它们属于同一个访问请求和响应过程;而HttpServletResponse.sendRedirect方法调用者与被调用者使用各自的request对象和response对象,它们属于两个独立的访问请求和响应过程。
代码案例:
项目的整体目录如下:
web.xml
[html] view plain copy
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <servlet>
- <servlet-name>ErrorServlet</servlet-name>
- <servlet-class>cn.itcast.servlet.ErrorServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>LoginServlet</servlet-name>
- <servlet-class>cn.itcast.response.LoginServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>RefreshServlet</servlet-name>
- <servlet-class>cn.itcast.response.RefreshServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>CEPServlet</servlet-name>
- <servlet-class>cn.itcast.response.CEPServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>OutServlet</servlet-name>
- <servlet-class>cn.itcast.response.OutServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>DownloadServlet</servlet-name>
- <servlet-class>cn.itcast.response.DownloadServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>TestServlet</servlet-name>
- <servlet-class>cn.itcast.response.TestServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>CheckcodeServlet</servlet-name>
- <servlet-class>cn.itcast.response.CheckcodeServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>RequestServlet1</servlet-name>
- <servlet-class>cn.itcast.request.RequestServlet1</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>RegServlet</servlet-name>
- <servlet-class>cn.itcast.request.RegServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>RequestDemo3</servlet-name>
- <servlet-class>cn.itcast.request.RequestDemo3</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>RequestDemo4</servlet-name>
- <servlet-class>cn.itcast.request.RequestDemo4</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>Login2Servlet</servlet-name>
- <servlet-class>cn.itcast.request.Login2Servlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ErrorServlet</servlet-name>
- <url-pattern>/error</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>LoginServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>RefreshServlet</servlet-name>
- <url-pattern>/refresh</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>CEPServlet</servlet-name>
- <url-pattern>/cep</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>OutServlet</servlet-name>
- <url-pattern>/out</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>DownloadServlet</servlet-name>
- <url-pattern>/download</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>TestServlet</servlet-name>
- <url-pattern>/test1</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>CheckcodeServlet</servlet-name>
- <url-pattern>/checkcode</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>RequestServlet1</servlet-name>
- <url-pattern>/request1</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>RegServlet</servlet-name>
- <url-pattern>/reg</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>RequestDemo3</servlet-name>
- <url-pattern>/request3</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>RequestDemo4</servlet-name>
- <url-pattern>/request4</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>Login2Servlet</servlet-name>
- <url-pattern>/login2</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
login.html
[html] view plain copy
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="/day10/login" method="post">
- <table border="1" width="50%">
- <tr>
- <td>输入姓名</td>
- <td>
- <input type="text" name="username" />
- </td>
- </tr>
- <tr>
- <td>输入密码</td>
- <td>
- <input type="password" name="password" />
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value=http://www.mamicode.com/"登陆"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
refresh.html
[html] view plain copy
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <!-- 5秒后跳转 -->
- <meta http-equiv="refresh" content="5;url=/day10/response/login.html">
- <title>页面定时跳转(读秒)</title>
- </head>
- <body onload="run()">
- <h2>页面将在<span id="spanId">5</span>秒后跳转</h2>
- </body>
- <script type="text/javascript">
- /*
- 读秒的操作
- 页面一加载,加载事件 onload
- 执行读秒的操作,每隔一秒变一次。
- 每隔一秒,js的定时器
- */
- var x = 5;
- function run(){
- var span = document.getElementById("spanId");
- span.innerHTML = x;
- x--;
- window.setTimeout("run()", 1000);
- }
- </script>
- </html>
checkcode.html
[html] view plain copy
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="/day10/login" method="post">
- <table border="1" width="70%">
- <tr>
- <td>输入姓名</td>
- <td>
- <input type="text" name="username" />
- </td>
- </tr>
- <tr>
- <td>输入密码</td>
- <td>
- <input type="password" name="password" />
- </td>
- </tr>
- <tr>
- <td>验证码</td>
- <td>
- <input type="text" name="code" />
- <img id="imgId" src=http://www.mamicode.com/"/day10/checkcode">
- <a href=http://www.mamicode.com/"#" onclick="run()">看不清,换一张</a>
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value=http://www.mamicode.com/"登陆"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- <script type="text/javascript">
- // 看不清,换一张,时间戳
- function run(){
- // 获取图片
- var image = document.getElementById("imgId");
- image.src = "/day10/checkcode?"+new Date().getTime();
- }
- </script>
- </html>
reg.html
[html] view plain copy
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="/day10/reg" method="get">
- <table border="1" width="50%">
- <tr>
- <td>输入姓名</td>
- <td>
- <input type="text" name="username" />
- </td>
- </tr>
- <tr>
- <td>输入密码</td>
- <td>
- <input type="password" name="password" />
- </td>
- </tr>
- <tr>
- <td>选择性别</td>
- <td>
- <input type="radio" name="sex" value=http://www.mamicode.com/"nan" />男
- <input type="radio" name="sex" value=http://www.mamicode.com/"nv" />女
- </td>
- </tr>
- <tr>
- <td>选择爱好</td>
- <td>
- <input type="checkbox" name="love" value=http://www.mamicode.com/"lq" />篮球
- <input type="checkbox" name="love" value=http://www.mamicode.com/"zq" />足球
- <input type="checkbox" name="love" value=http://www.mamicode.com/"pq" />排球
- </td>
- </tr>
- <tr>
- <td>选择城市</td>
- <td>
- <select name="city">
- <option value=http://www.mamicode.com/"none">--请选择--</option>
- <option value=http://www.mamicode.com/"bj">北京</option>
- <option value=http://www.mamicode.com/"sh">上海</option>
- <option value=http://www.mamicode.com/"gz">广州</option>
- </select>
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value=http://www.mamicode.com/"登陆"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
login.jsp
[html] view plain copy
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- ${msg}
- <form action="/day10/login2" method="post">
- <table border="1" width="50%">
- <tr>
- <td>输入姓名</td>
- <td>
- <input type="text" name="username" />
- </td>
- </tr>
- <tr>
- <td>输入密码</td>
- <td>
- <input type="password" name="password" />
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value=http://www.mamicode.com/"登陆"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
CEPServlet.java (禁用浏览器缓存)
[java] view plain copy
- package cn.itcast.response;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 禁用浏览器的缓存
- * @author Administrator
- *
- */
- public class CEPServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- /**
- * Cache-Control : no-cache
- Expires: -1 值是日期类型(setDateHeader())
- Pragma : no-cache
- */
- // 设置三个头信息
- response.setHeader("Cache-Control","no-cache");
- response.setHeader("Pragma","no-cache");
- response.setDateHeader("Expires", -1);
- // 向页面输出当前的时间
- // 获取当前时间
- Date date = new Date();
- // 修改格式 yyyy-MM-dd HH:mm:ss
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String str = sdf.format(date);
- // 输出
- response.getWriter().write(str);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
TestServlet.java (验证码热身)
[java] view plain copy
- package cn.itcast.response;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 验证码热身
- * @author Administrator
- *
- */
- public class TestServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 在内存中生成图片
- BufferedImage image = new BufferedImage(300, 500, BufferedImage.TYPE_INT_RGB);
- // 获取画笔对象
- Graphics g = image.getGraphics();
- // 设置颜色
- g.setColor(Color.RED);
- // 画一个矩形
- g.drawRect(100, 100, 150, 100);
- g.setColor(Color.YELLOW);
- // 定义字符串
- String str = "abc";
- g.drawString(str, 80, 80);
- // 把内存中的图片输出到浏览器端
- ImageIO.write(image, "jpg", response.getOutputStream());
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
CheckcodeServlet.java(实现验证码流程)
[html] view plain copy
- package cn.itcast.response;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 验证码
- * @author Administrator
- *
- */
- public class CheckcodeServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- /**
- * 在内存中生成图片(纸),没有设置背景颜色,画填充的矩形,并且和纸的大小相同,矩形有颜色。
- * 获取笔的对象(设置颜色,设置字体,画字符串,画矩形)
- * 先准备好数据,随机生成4个字符,把字符画到纸上
- * 画干扰线
- * 把内存中的图片输出到客户端上
- */
- int width = 120;
- int height = 30;
- // 在内存中生成图片
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- // 先获取画笔对象
- Graphics2D g = (Graphics2D) image.getGraphics();
- // 设置灰色
- g.setColor(Color.GRAY);
- // 画填充的矩形
- g.fillRect(0, 0, width, height);
- // 设置颜色
- g.setColor(Color.BLUE);
- // 画边框
- g.drawRect(0, 0, width-1, height-1);
- // 准备数据,随机获取4个字符
- // String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
- String words = "\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";
- // 设置颜色
- g.setColor(Color.YELLOW);
- // 设置字体
- g.setFont(new Font("隶书", Font.BOLD, 20));
- Random random = new Random();
- int x = 20;
- int y = 20;
- for(int i=0;i<4;i++){
- // void rotate(double theta, double x, double y)
- // theta 弧度
- // hudu = jiaodu * Math.PI / 180;
- // 获取正负30之间的角度
- int jiaodu = random.nextInt(60)-30;
- double hudu = jiaodu * Math.PI / 180;
- g.rotate(hudu, x, y);
- // 获取下标
- int index = random.nextInt(words.length());
- // 返回指定下标位置的字符,随机获取下标
- char ch = words.charAt(index);
- // 写字符串
- g.drawString(""+ch, x, y);
- g.rotate(-hudu, x, y);
- x += 20;
- }
- // 设置颜色
- g.setColor(Color.GREEN);
- int x1,x2,y1,y2;
- // 画干扰线
- for(int i=0;i<4;i++){
- x1 = random.nextInt(width);
- y1 = random.nextInt(height);
- x2 = random.nextInt(width);
- y2 = random.nextInt(height);
- g.drawLine(x1, y1, x2, y2);
- }
- // 输出到客户端
- ImageIO.write(image, "jpg", response.getOutputStream());
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- public static void main(String[] args) {
- System.out.println("\u9fa5");
- System.out.println("\u9fa4");
- System.out.println("\u9fa3");
- System.out.println("\u9fa2");
- }
- }
DownloadServlet.java 简单实现文件下载(中文名乱码)
[java] view plain copy
- package cn.itcast.response;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URLEncoder;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 文件下载
- * @author Administrator
- *
- */
- public class DownloadServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 先获取到文件,读入输入流中
- // 获取文件的绝对磁盘路径
- String path = getServletContext().getRealPath("/img/外国美女.jpg");
- // 包含文件的名称 c:\tomcat\webapps\day10\img\girl7.jpg
- // 截取文件的名称 girl7.jpg
- String filename = null;
- // 获取最后一个\的位置
- int index = path.lastIndexOf("\\");
- if(index != -1){
- filename = path.substring(index+1);
- }
- // 判断是什么浏览器
- // 解决各浏览器的中文乱码问题
- String agent = request.getHeader("User-Agent");
- // 处理safari的乱码问题
- byte[] bytes = agent.contains("MSIE") ? filename.getBytes() : filename
- .getBytes("UTF-8");
- filename = new String(bytes, "ISO-8859-1");// 各浏览器基本都支持ISO编码
- if(filename != null){
- // 设置头信息
- response.setHeader("Content-Disposition", "attachment;filename="+filename);
- System.out.println(request.getRemoteAddr());
- System.out.println(path);
- InputStream in = new FileInputStream(path);
- // 通过response读出到客户端
- OutputStream os = response.getOutputStream();
- // io的拷贝
- byte [] b = new byte[1024];
- int len = 0;
- while((len = in.read(b)) != -1){
- os.write(b, 0, len);
- }
- in.close();
- // os.close();服务器管理流
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
OutServlet.java (处理HttpServletResponse 响应输出中文的乱码问题 包括字节和字符)
[java] view plain copy
- package cn.itcast.response;
- import java.io.IOException;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 输出中文的乱码的问题
- * @author Administrator
- *
- */
- public class OutServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- run2(response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- /**
- * 字符输出中文是否乱码呢?
- * * 肯定乱码
- * response缓冲区的编码,默认值ISO-8859-1
- * * 设置response缓冲编码
- * response.setCharacterEncoding("UTF-8");
- * * 设置浏览器打开文件所采用的编码
- * response.setHeader("Content-Type", "text/html;charset=UTF-8");
- * * 简写方式
- * response.setContentType("text/html;charset=UTF-8");
- *
- * @param response
- * @throws IOException
- */
- public void run2(HttpServletResponse response) throws IOException{
- // 设置response缓冲区的编码
- //response.setCharacterEncoding("UTF-8");
- // 设置浏览器打开文件所采用的编码
- //response.setHeader("Content-Type", "text/html;charset=UTF-8");
- // 简写的形式(等于上面两句)
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().write("哈罗卧得");
- }
- /**
- * 字节的输出中文的乱码
- * * 输出哈罗我的是否乱码呢?
- * * 不一定乱码。
- * * 解决办法
- * * 设置浏览器打开文件时所采用的编码
- * response.setHeader("Content-Type", "text/html;charset=UTF-8");
- * * 获取字符串byte数组时编码和打开文件时编码一致。
- * "哈罗我的".getBytes("UTF-8")
- * @throws IOException
- */
- public void run1(HttpServletResponse response) throws IOException{
- // 设置浏览器打开文件时编码
- response.setHeader("Content-Type", "text/html;charset=UTF-8");
- // 获取字节输出流
- OutputStream os = response.getOutputStream();
- // 输出中文
- os.write("哈罗我的".getBytes("UTF-8"));
- }
- }
RefreshServlet.java (页面自动定时跳转)
[java] view plain copy
- package cn.itcast.response;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 页面的定时跳转
- * @author Administrator
- *
- */
- public class RefreshServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 读秒操作
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().write("<h1>页面将在5秒后跳转</h1>");
- // 通过refresh头完成页面刷新
- response.setHeader("refresh", "5;url=/day10/response/login.html");
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
[java] view plain copy
- package cn.itcast.response;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 重定向到登陆页面
- * @author Administrator
- *
- */
- public class LoginServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- /**
- * 先获取用户输入的内容(request对象)
- * 判断姓名和密码是否都是admin,如果有一个不是,重定向到登陆页面,如果都是,就登陆成功。
- */
- // 获取用户输入的内容
- String username = request.getParameter("username"); // 程序入口
- // 获取密码
- String password = request.getParameter("password");
- // 判断
- if("admin".equals(username) && "admin".equals(password)){
- // 登陆成功
- // 重定向到登陆页面
- // response.getWriter().write("success");
- response.sendRedirect("/day10/response/refresh.html");
- }else{
- // 重定向到登陆页面
- // 设置302的状态码
- //response.setStatus(302);
- // 设置地址
- //response.setHeader("location", "/day10/response/login.html");
- // 重定向
- response.sendRedirect("/day10/response/login.html");
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
RequestServlet1.java (获取客户机内容)
[java] view plain copy
- package cn.itcast.request;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 获取客户机的内容
- * @author Administrator
- *
- */
- public class RequestServlet1 extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 获取IP
- String ip = request.getRemoteAddr();
- // 获取请求方式
- String method = request.getMethod();
- // 获取虚拟路径
- String path = request.getContextPath();
- System.out.println("IP地址:"+ip);
- System.out.println("请求方式:"+method);
- System.out.println("虚拟路径名称:"+path);
- // 获取请求头记住来源(防盗链)
- String referer = request.getHeader("referer");
- // 判断浏览器(文件下载)
- String agent = request.getHeader("user-agent");
- // 做操作
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
RegServlet.java (解决请求乱码 GET和POST请求乱码)
[java] view plain copy
- package cn.itcast.request;
- import java.io.IOException;
- import java.util.Arrays;
- import java.util.Map;
- import java.util.Set;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 获取请求参数
- * @author Administrator
- *
- */
- public class RegServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- /**
- * request获取中文的乱码
- * post请求(经常使用)
- * setCharacterEncoding(String env) 设置request的缓冲区的编码
- * get请求
- * username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
- */
- // 设置request缓冲区的编码(一定要在request.getParameter("username");之前)
- // request.setCharacterEncoding("UTF-8");
- // 获取内容,做其他操作
- // 获取姓名
- String username = request.getParameter("username");
- // 解析get方式乱码的问题
- username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
- // 获取密码
- String password = request.getParameter("password");
- // 获取性别
- String sex = request.getParameter("sex");
- // 获取城市
- String city = request.getParameter("city");
- // 获取爱好 返回是String数组
- String [] loves = request.getParameterValues("love");
- System.out.println("用户名:"+username);
- System.out.println("密码:"+password);
- System.out.println("性别:"+sex);
- System.out.println("城市:"+city);
- System.out.println("爱好:"+Arrays.toString(loves));
- System.out.println("===================================================================");
- // 获取map集合
- Map<String, String []> map = request.getParameterMap();
- // 循环遍历
- Set<String> keys = map.keySet();
- for (String key : keys) {
- String [] values = map.get(key);
- System.out.println(Arrays.toString(values));
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
RequestDemo3.java (转发和重定向)
[java] view plain copy
- package cn.itcast.request;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 重定向和转发
- * @author Administrator
- *
- */
- public class RequestDemo3 extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // request域设置内容
- request.setAttribute("name", "凤姐");
- // 完成重定向的工作(客户端端绝对路径)
- // response.sendRedirect("/day10/request4");
- // 转发(路径服务器的绝对路径)
- request.getRequestDispatcher("/request4").forward(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
RequestDemo4.java (测试request域)
[java] view plain copy
- package cn.itcast.request;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class RequestDemo4 extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- // 获取
- String value = (String) request.getAttribute("name");
- // 输出中文
- response.setContentType("text/html;charset=UTF-8");
- response.getWriter().write("访问到了demo4... "+value);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
使用转发效果如下:能获取request域中的值
使用重定向效果如下:是不能获取到request域中的值的
Login2Servlet.java (使用request域属性和转发 实现登录的错误信息提示)
[java] view plain copy
- package cn.itcast.request;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * 使用转发到登陆页面
- * @author Administrator
- *
- */
- public class Login2Servlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- /**
- * 先获取用户输入的内容(request对象)
- * 判断姓名和密码是否都是admin,如果有一个不是,重定向到登陆页面,如果都是,就登陆成功。
- */
- // 获取用户输入的内容
- String username = request.getParameter("username"); // 程序入口
- // 获取密码
- String password = request.getParameter("password");
- // 判断
- if("admin".equals(username) && "admin".equals(password)){
- // 登陆成功
- // 重定向到登陆页面
- response.sendRedirect("/day10/response/refresh.html");
- }else{
- // 在request域存入内容
- request.setAttribute("msg", "用户名或者密码错误!");
- // 重定向到登陆页面
- // 重定向
- // response.sendRedirect("/day10/response/login.html");
- request.getRequestDispatcher("/request/login.jsp").forward(request, response);
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
from: http://www.tk4479.net/u013087513/article/details/54601326
JAVAWEB开发之HttpServletResponse和HttpServletRequest详解(下)(各种乱码、验证码、重定向和转发)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。