response和reqest的相关用法
简介
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象,request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向客户机输出数据,只需要找response对象就行了
HttpServletResponse
HttpServletResponse对象服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法:
getWriter()
getOutputStream()
SetContentType()
下面给大家介绍一下关于服务器向客户端发送请求响应的例子:
1.重定向到登录页面;
首先写一个登录界面,form表单的提交为一个servlet程序,然后在servlet程序中做相关判断,首先从后台拿出数据,然后做数据校验,然后,最后达到重定向的目的
请求重定向指:一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这称之为请求重定向
302+Location ------ response.sendRedirect
案例:用户登陆时,用户名密码错误,重定向回登陆页面
<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="登陆"/>
</td>
</tr>
</table>
</form>
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request从后台拿出数据
String username = request.getParameter("username");//程序的入口,获得从后台拿到的数据
String password = request.getParameter("password");
//对你输入的数据进行校验
if (username.equals("admin") && password.equals("admin")) {
//如果能够登录成功 重定向到读秒页面
/* response.sendRedirect("/day_10/response/login.html");*/
response.getWriter().write("success");
} else {
//如果登录不成功,则重定向到登录界面 ,重定向简写方式:response.sendRedirect()
response.setStatus(302);
response.setHeader("location", "/day_10/response/refresh.html");
/*response.sendRedirect("/day_10/response/login.html");*/
}
}
2.发送http头,控制浏览器定时刷新网络,利用定时刷新,不时完成读秒操作
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置你要读取的数据的编码格式
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<h1>页面5秒的时间来跳转</h1>");
response.setHeader("refresh", "5;url=/day_10/response/login.html");
}
刷新网络页面
<!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">
<!-- 头文件定时完成读秒操作 -->
<meta http-equiv="refresh" content="5;url=/day_10/response/login.html">
<title>页面读秒跳转</title>
</head>
<body onload="run()">
<h1>页面将在<span id="spanId">5</span>秒后跳转</h1>
</body>
<script type="text/javascript">
/*
页面一加载 onload
执行读秒的操作,每隔一秒读一次
js读秒器.调用方法,调用递归方法
*/
var x = 5;
function run(){
var span = document.getElementById("spanId");
span.innerHTML = x; //为其span的读秒操作,完成数据的不断的变化
x--;
window.setTimeout("run()", 1000);
}
</script>
</html>
3.refresh向页面中输入中文
字符流输出中文:
response的字符流的缓冲区是ISO-8859-1编码.
设置response缓冲区的编码.
设置浏览器打开的默认的编码格式
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, 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("你好,中国");
}
4.输入一个验证码即验证码的生成
1.建立BufferedImage对象:指定图片的长度宽度和类型,即获取画布对象
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
2.取得Graphics对象,用来绘制图片,即获得画笔对象
Graphics graphics = image.getGraphics();
3.绘制背景颜色和填充矩形,便于给验证码创建颜色
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
4.绘制边界
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);
5.生成随机数据
Random random = new Random();
random.nextInt(n); // 生成0 到 n的随机数 前闭后开
6.绘制干扰线
graphics.drawLine(x1, y1, x2, y2);
7.通过ImageIo对象的静态方法将图片输出
ImageIO.write(image, “jpg”, resp.getOutputStream());
特别补充:
设置验证码字体
graphics.setFont(new Font(“Times New Roman”, Font.PLAIN, 18));
设置旋转
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.rotate(theta, x, y);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取画布
int width = 120;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//获取画笔对象(为了调用改变干扰线的方法,调用子类的方法,强制一下)
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.YELLOW);
//设置填充矩形
g.fillRect(0, 0, width, height);
//设置边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width-1, height-1);
//准备数据,随机获取字符串常用字符
String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
//常用汉字
//设置颜色
g.setColor(Color.RED);
//设置字体
g.setFont(new Font("隶书",Font.BOLD, 20));
Random random = new Random();
int x = 20;
int y = 20;
for(int i = 0;i < 4;i++){
//每个字符的旋转方向获取30到60之间的角度
int jiaodu = random.nextInt(30)-60;
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,y1,x2,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());
}
运行效果:
HttpServletRequest
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。
request获取请求参数和提交信息乱码问题:
getParameter(name) — String 通过name获得值
getParameterValues — String[ ] 通过name获得多值 checkbox
getParameterNames — Enumeration 获得所有name
getParameterMap — Map<String,String[ ]> key :name value: 多值
设置request的编码格式当表单的数据传递过来的是post提交方式
request.setCharacterEncoding(“utf-8”);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* request请求方式的乱码问题
* post请求
* setCharacterEncoding(String env) 设置request的编码
*/
//设置request的编码格式当表单的数据传递过来的是post提交方式
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[] loves = request.getParameterValues("love");
//获得map集合的方式
@SuppressWarnings("unchecked")
Map<String,String []> map = request.getParameterMap();
Set<String> set = map.keySet();
for (String key : set) {
String[] values = map.get(key);
System.out.println(Arrays.toString(values));
}
System.out.println("账号:"+username);
System.out.println("密码:"+password);
System.out.println("性别:"+sex);
System.out.println("城市:"+city);
System.out.println("爱好:"+Arrays.toString(loves));
}
重定向和转发的区别
1.RequestDispatcher.forward方法只能将请求转发给同一个WEB应用中的组件;而HttpServletResponse.sendRedirect 方法还可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源。
2.如果传递给HttpServletResponse.sendRedirect 方法的相对URL以“/”开头,它是相对于服务器的根目录;如果创建RequestDispatcher对象时指定的相对URL以“/”开头,它是相对于当前WEB应用程序的根目录。
3.调用HttpServletResponse.sendRedirect方法重定向的访问过程结束后,浏览器地址栏中显示的URL会发生改变,由初始的URL地址变成重定向的目标URL;调用RequestDispatcher.forward 方法的请求转发过程结束后,浏览器地址栏保持初始的URL地址不变。
4.HttpServletResponse.sendRedirect方法对浏览器的请求直接作出响应,响应的结果就是告诉浏览器去重新发出对另外一个URL的访问请求;RequestDispatcher.forward方法在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求并得到了响应结果,并不知道在服务器程序内部发生了转发行为。
5.RequestDispatcher.forward方法的调用者与被调用者之间共享相同的request对象和response对象,它们属于同一个访问请求和响应过程;而HttpServletResponse.sendRedirect方法调用者与被调用者使用各自的request对象和response对象,它们属于两个独立的访问请求和响应过程