response、request对象
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象。
request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向客户机输出数据,只需要找response对象就行了。
HttpServletResponse对象服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。
setHeader(java.lang.String name, java.lang.String value) Sets a response header with the given name and value. |
setStatus(int sc) Sets the status code for this response. |
getWriter() Returns a PrintWriter object that can send character text to the client. |
getOutputStream() Returns a ServletOutputStream suitable for writing binary data in the response. |
Tip:response常见应用
向客户端输出中文数据
分别以OutputStream和PrintWriter输出
String data="中国 "; //程序以什么码表输出,一定要控制浏览器以什么码表打开 response.setHeader("Content-type", "text/html;charset=UTF-8"); OutputStream out=response.getOutputStream(); //out.write(data.getBytes()); out.write(data.getBytes("UTF-8")); |
String data="中国2 "; //html: <meta>标签模拟一个http响应头 OutputStream out=response.getOutputStream(); //out.write(data.getBytes()); out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes()); out.write(data.getBytes("UTF-8")); |
|
String data="中国q"; //设置response使用的码表,以控制response以什么码表向浏览器输入数据,默认为ISO-8859-1 response.setCharacterEncoding("GB2312"); //指定浏览器以什么码表打开服务器发送的数据 response.setHeader("Content-type", "text/html;charset=GB2312"); //response.setHeader("Content-type", "text/html;charset=ISO-8859-1"); PrintWriter out=response.getWriter(); out.write(data);// |
String data="中国q"; //该句代码等价于其后面两句 response.setContentType("text/html;charset=GB2312"); //response.setCharacterEncoding("GB2312"); //response.setHeader("Content-type", "text/html;charset=ISO-8859-1"); PrintWriter out=response.getWriter(); out.write(data);// |
用OutputStream输出1,客户端看到的是什么?
package com.tinghou.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//服务器中默认的编码为ISO-8859-1,它不支持中文,tomcat规定的
/* //告诉服务器应用使用UTF-8解析文本
response.setCharacterEncoding("UTF-8");
//告诉客户端要使用什么编码
response.setHeader("content-type", "text/html;charset=UTF-8");*/
//告诉服务器应用使用UTF-8解析文本,告诉客户端要使用什么编码
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();//得到一个字符输出流
out.write("你好!");//向客户端响应文本内容
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.tinghou.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream sos = response.getOutputStream();
sos.write("你好123".getBytes("UTF-8"));//getBytes默认编码为本地编码(即:gbk)
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
文件下载
String path=this.getServletContext().getRealPath("/download/new.jpg"); //C:\apache-tomcat-7.0.22\webapps\day06\download\new.jsp String filename=path.substring(path.lastIndexOf("\\")+1);
InputStream in=null; OutputStream out=null; response.setHeader("content-disposition", "attachment;filename="+filename); //如果下载文件是中文文件,则文件名需要经过url编码 response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8")); try { in=new FileInputStream(path); int len=0; byte buffer[]=new byte[1024]; out=response.getOutputStream(); while((len=in.read(buffer))>0){ out.write(buffer,0,len); } }finally{ if(in!=null){ try{ in.close(); }catch(Exception e){ e.printStackTrace(); } } } |
package com.tinghou.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//通过路径得到一个输入流
String path = this.getServletContext().getRealPath("/WEB-INF/classes/photo.jpg");
System.out.println("path="+path);
FileInputStream fis = new FileInputStream(path);
//创建字节输出流
ServletOutputStream sos = response.getOutputStream();
//得到要下载的文件名
String filename = path.substring(path.lastIndexOf("\\")+1);
//设置文件名的编码
filename = URLEncoder.encode(filename, "UTF-8");//将不安全的文件名改为UTF-8格式
//告知客户端要下载文件
response.setHeader("content-disposition", "attachment;filename="+filename);
response.setHeader("content-type", "image/jpeg");
//执行输出操作
int len = 1;
byte[] b = new byte[1024];
while((len=fis.read(b))!=-1){
sos.write(b,0,len);
}
sos.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
生成随机图片,验证码
package com.tinghou.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
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;
import cn.dsna.util.images.ValidateCode;
public class ServletDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//告诉客户端不使用缓存
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setIntHeader("expires", 0);
ValidateCode vc = new ValidateCode(110, 25, 4, 9);
String code = vc.getCode();//得到生成的字符
vc.write(response.getOutputStream());
}
private void test1(HttpServletResponse response) throws IOException {
int width = 110;
int height = 25;
//在内存中创建一个图像对象
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建一个画笔
Graphics g = img.getGraphics();
//给图片添加背景色
g.setColor(Color.PINK);//设置一个颜色
g.fillRect(1, 1, width-2, height-2);//填充颜色
//给边框一个色
g.setColor(Color.RED);
g.drawRect(0, 0, width-1, height-1);//设置边框的显示坐标
//设置文本样式
g.setColor(Color.BLUE);
g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 15));
//给图片添加文本
Random rand = new Random();
int position = 20;
for (int i = 0; i < 4; i++) {
g.drawString(rand.nextInt(10)+"", position, 20);//给图片填充文本
position+=20;
}
//添加9条干扰线
for (int i = 0; i < 9; i++) {
g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
//将图片对象以流的方式输出的客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
效果:
实现简单登录
<!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>
<script type="text/javascript">
function changeCode(){
//得到图片元素
var img = document.getElementsByTagName("img")[0];
//img.setAttribute("src","/day09_00_HttpServletResponse/servlet/demo4");//XML Dom 语法
img.src = "/day09_00_HttpServletResponse/servlet/demo4?time="+new Date().getTime();
}
</script>
</head>
<body>
<form action="#" method="post">
用户名:<input type="text" name="userName"/><br>
密码:<input type="password" name="pwd"/><br>
验证码:<input type="text" name="code"/>
<img src="/day09_00_HttpServletResponse/servlet/demo4" οnclick="changeCode()"/><a href="javascript:changeCode()" >看不清换一张</a><br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>
发送http头,控制浏览器定时刷新网页(REFRESH)
response.setHeader("refresh", "3"); String data = new Random().nextInt(100000)+""; response.getWriter().write(data); |
response.setHeader("refresh", "3;url='/day06/index.jsp'"); response.setContentType("text/html;charset=GB2312"); String data = new Random().nextInt(100000)+""; response.getWriter().write("登录成功,将在3秒后跳转,如果没有,请点<a href=''>超链接</a>"); |
String message="<meta http-equiv='refresh' content='3;url=/day06/index.jsp'>登录成功,将在3秒后跳转,如果没有,请点<a href=''>超链接</a>"; request.setAttribute("message",message); this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); |
package com.tinghou.servlet;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*response.setIntHeader("refresh", 1);//设置1秒钟刷新一次
Random r = new Random();
response.getWriter().write(r.nextInt()+"");*/
response.getWriter().write("注册成功!3秒钟跳到主页");
//设置3秒钟跳转
response.setHeader("refresh", "3;url=/day09_00_HttpServletResponse/servlet/demo6");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.tinghou.servlet;
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 ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("i'm homePage!");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
发送http头,控制浏览器缓存当前文档内容
String data="aaaaa"; response.setDateHeader("expires", System.currentTimeMillis()+3600*1000); response.getWriter().write(data); |
多学一招:使用HTML语言里面的<meta>标签来控制浏览器行为
通过response实现请求重定向。
response.setStatus(302);// 302状态码和location头即可实现重定向 response.setHeader("location", "/day06/index.jsp"); |
response.sendRedirect("/day06/index.jsp"); |
请求重定向指:一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这称之为请求重定向。
应用场景:用户注册,让用户知道注册成功,重定向到首页。
购物网站购完后,转到购物车显示页面,用转发按刷新又买一个,所以用重定向。
package com.tinghou.servlet;
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 ServletDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("A:我要借钱!");
System.out.println("B:我不有,但是我可以告诉你谁有");
/*//告诉客户端要重新定向新的资源
response.setStatus(302);
//告诉浏览器要去访问哪个URL
response.setHeader("location", "/day09_00_HttpServletResponse/servlet/demo8");*/
//请求重定向
response.sendRedirect("/day09_00_HttpServletResponse/servlet/demo8");
System.out.println("A: 我去了");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
response细节
getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOuputStream、Printwriter对象。
getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法,包括转发时。
Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Servlet引擎将这些数据当作响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。
Serlvet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎将调用close方法关闭该输出流对象。
HttpServletRequest
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。
getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. |
getParameter(java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. |
getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. |
getRequestURL() Reconstructs the URL the client used to make the request. |
Http://www.sina.com/news/1.html URL 子 /news/1.html URI 父 |
获得客户机信息
getRequestURL方法返回客户端发出请求时的完整URL。
getRequestURI方法返回请求行中的资源名部分。
getQueryString 方法返回请求行中的参数部分。
getPathInfo方法返回请求URL中的额外路径信息。额外路径信息是请求URL中的位于Servlet的路径之后和查询参数之前的内容,它以“/”开头。
getRemoteAddr方法返回发出请求的客户机的IP地址
getRemoteHost方法返回发出请求的客户机的完整主机名
getRemotePort方法返回客户机所使用的网络端口号
getLocalAddr方法返回WEB服务器的IP地址。
getLocalName方法返回WEB服务器的主机名
获得客户机请求头
getHeader方法
getHeaders方法
getHeaderNames方法
获得客户机请求参数(客户端提交的数据)
getParameter方法
getParameterValues(String name)方法
getParameterNames方法
getParameterMap方法
package com.tinghou.servlet;
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 ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// getMethod(); 获得请求方式
// ***getRequestURL();返回客户端发出请求时的完整URL。
// ***getRequestURI(); 返回请求行中的资源名部分。
// *****getContextPath(); 当前应用的虚拟目录 /day09_01_HttpServletRequest
// getQueryString() ; 返回请求行中的参数部分。
System.out.println(request.getMethod());// GET
System.out.println(request.getRequestURL()); // http://localhost:8080/e_day09_01_HttpServletRequest/servlet/demo1
System.out.println(request.getRequestURI()); // /e_day09_01_HttpServletRequest/servlet/demo1
System.out.println(request.getContextPath()); // /e_day09_01_HttpServletRequest
System.out.println(request.getQueryString()); // username=tom
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
发送请求:请求结果:
package com.tinghou.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// test1(request);
test2(request);
//获得相关name的消息头
Enumeration headers = request.getHeaders("accept-language");
while(headers.hasMoreElements()){
String e = (String) headers.nextElement();
System.out.println(e+":"+request.getHeader(e)); //zh-CN,zh;q=0.8:null
}
}
private void test2(HttpServletRequest request) {
//获得所有请求消息头的name
Enumeration names = request.getHeaderNames();
while(names.hasMoreElements()){
String e = (String) names.nextElement();
System.out.println("test2"+e+":"+request.getHeader(e));
}
}
private void test1(HttpServletRequest request) {
//获得请求消息头的信息
String header = request.getHeader("User-Agent");
System.out.println(header);
if(header.toLowerCase().contains("msie")){
System.out.println("你使用的是IE浏览器");
}else if(header.toLowerCase().contains("firefox")){
System.out.println("你使用的是火狐浏览器");
}else if(header.toLowerCase().contains("chrome")){
System.out.println("你使用的是谷歌浏览器");
}else{
System.out.println("你使用的是其它浏览器");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
与获取表单数据相关的方法
<input type="text"name="username" />
*** getParameter(name) 根据表单中name属性的名,获取value属性的值方法
*** getParameterValues(String name)专业为复选框取取提供的方法
getParameterNames() 得到表单提交的所有name的方法
*** getParameterMap 到表单提交的所有值的方法 //做框架用,非常实用
getInputStream 以字节流的方式得到所有表单数据
与操作非表单数据相关的方法(request也是一个域对象)
*** void setAttribute(String name, Object value);
*** Object getAttribute(String name);
Void removeAttribute(String name);
与请求转发相关的方法
//得到请求转发或请求包含的协助对象
RequestDispatcher getRequestDispatcher(String path)
*** forward(ServletRequest request, ServletResponse response) //转发的方法
include(ServletRequest request, ServletResponse response) //请求包含
与请求编码相关的方法:
//解决post方式编码
*****request.setCharacterEncoding("UTF-8"); //告诉服务器客户端什么编码,只能处理post请求方式
//解决get方式编码
String name = new String(name.getBytes(“iso-8859-1”),”UTF-8”);
Tip: request常见应用1
防盗链
String headValue=request.getHeader("Accept-Encoding"); Enumeration e=request.getHeaderNames(); while(e.hasMoreElements()){ String value=(String) e.nextElement(); System.out.println(value); }
e=request.getHeaderNames(); while(e.hasMoreElements()){ String name=(String) e.nextElement(); String value=request.getHeader(name); System.out.println("name="+name+",value="+value); } } |
|
String value=request.getParameter("username"); System.out.println(value);
Enumeration e=request.getParameterNames(); while(e.hasMoreElements()){ String name=(String) e.nextElement(); value=request.getParameter(name); System.out.println(name+"="+value); }
String value2[]=request.getParameterValues("username"); for(String v:value2){ System.out.println("u="+v); }
Map<String,String[]> map=request.getParameterMap(); User user=new User(); User formbean=new User(); try { BeanUtils.populate(user, map);//用map集合填充bean BeanUtils.copyProperties(user, formbean);//bean的拷贝 } catch (Exception e1) { e1.printStackTrace(); } System.out.println(user);
InputStream in=request.getInputStream(); byte buffer[]=new byte[1024]; int len=0; while((len=in.read(buffer))>0){ System.out.println(new String(buffer,0,len)); } |
|
各种表单输入项数据的获取
text、password、radio、checkbox、file、select、textarea、hidden、image、button给js编程用
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>带数据给requestDemo3</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <br> <!-- Url后跟中文数据要编码后提交--> <form action="/day06/servlet/requestDemo3" method="post"> 用户名1 :<input type="text" name="username"/><br/> 密码: <input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="male" />男 <input type="radio" name="gender" value="female" />女<br/>
所在地:<select name="city"> <option value="beijing">北京</option> <option value="shanghai">上海</option> <option value="cs">长沙</option> </select><br/> 爱好: <input type="checkbox" name ="likes" value="single" />唱歌 <input type="checkbox" name ="likes" value="dance" />跳舞 <input type="checkbox" name ="likes" value="basketball" />篮球 <input type="checkbox" name ="likes" value="football" />足球 <br/> 备注:<textarea rows="5" cols="60" name="description" ></textarea> <br/> 大头照<input type="file" name="image" /><br/> <input type="hidden" name="id" value="123456"/>
<input type="submit" value="提交"/> </form> </body> </html> | request.getParameter("username"); request.getParameter("password"); request.getParameter("gender"); request.getParameter("city"); request.getParameter("city"); String[] likes=request.getParameterValues("likes"); for(int i=0;likes!=null && i<likes.length;i++){ System.out.println(likes[i]); } request.getParameter("description");
request.getParameter("id"); |
编写测试表单:
<!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="/e_day09_01_HttpServletRequest/servlet/demo3" method="post">
用户名:<input type="text" name="userName"/><br/>
密码:<input type="password" name="pwd"/><br/>
性别:<input type="radio" name="sex" value="男" checked="checked"/>男
<input type="radio" name="sex" value="女"/>女 <br/>
爱好 :
<input type="checkbox" name="hobby" value="篮球"/>篮球
<input type="checkbox" name="hobby" value="唱歌"/>唱歌
<input type="checkbox" name="hobby" value="编码"/>编码
<br/>
所在城市:
<select name="city">
<option>------请选择------</option>
<option value="bj">北京</option>
<option value="sh">上海</option>
<option value="gz">广州</option>
</select>
<br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>
编写代码获取上面的表单数据:
package com.tinghou.servlet;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.tinghou.entity.User;
public class ServletDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//告诉服务器要使用什么编码,注:浏览器使用的是什么编码传过来的就是什么编码
request.setCharacterEncoding("UTF-8");//只能解决post方式的乱码
test1(request);
}
private void test4(HttpServletRequest request) {
try {
User u = new User();
System.out.println("封装数据前:"+u);
BeanUtils.populate(u, request.getParameterMap());
System.out.println("封装数据后:"+u);
} catch (Exception e) {
e.printStackTrace();
}
}
private void test3(HttpServletRequest request) {
try {
User u = new User();
System.out.println("封装数据前:"+u);
//获取表单数据
Map<String,String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> m : map.entrySet()) {
String name = m.getKey();
String[] value = m.getValue();
//创建一属性描述器
PropertyDescriptor pd = new PropertyDescriptor(name, User.class);
//得到setter属性
Method setter = pd.getWriteMethod();
if(value.length==1){
setter.invoke(u, value[0]);//给一个值的变量赋值
}else{
setter.invoke(u, (Object)value);//相关于给复选框赋值
}
}
System.out.println("封装数据后:"+u);
} catch (Exception e) {
e.printStackTrace();
}
}
private void test2(HttpServletRequest request) {
//获取所有的表单name的名子
Enumeration names = request.getParameterNames();
while(names.hasMoreElements()){
String name = (String) names.nextElement();//得到每一个name名
String[] values = request.getParameterValues(name);//根据name名,得到value值
for (int i = 0;values!=null && i < values.length; i++) {
System.out.println(name+"\t"+values[i]);
}
}
}
private void test1(HttpServletRequest request) throws UnsupportedEncodingException {
//获取表单数据
//根据表单中name属性的名,获取value属性的值方法
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String[] hobbys = request.getParameterValues("hobby");
String city = request.getParameter("city");
userName = new String(userName.getBytes("iso-8859-1"),"UTF-8");
System.out.println(userName);
System.out.println(pwd);
System.out.println(sex);
for (int i = 0;hobbys!=null && i < hobbys.length; i++) {
String hobby = hobbys[i];
hobby = new String(hobby.getBytes("iso-8859-1"),"UTF-8");
System.out.print(hobbys[i]+"\t");
// System.out.print(hobby+"\t");
}
System.out.println();
System.out.println(city);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.tinghou.entity;
import java.util.Arrays;
//在实体类中的字段要与表单中的name名一致。约定优于编码
public class User {
private String userName;
private String pwd;
private String sex;
private String[] hobby;
private String city;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "User [userName=" + userName + ", pwd=" + pwd + ", sex=" + sex
+ ", hobby=" + Arrays.toString(hobby) + ", city=" + city + "]";
}
}
package com.tinghou.entity;
import java.util.Arrays;
//在实体类中的字段要与表单中的name名一致。约定优于编码
public class User {
private String userName;
private String pwd;
private String sex;
private String[] hobby;
private String city;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "User [userName=" + userName + ", pwd=" + pwd + ", sex=" + sex
+ ", hobby=" + Arrays.toString(hobby) + ", city=" + city + "]";
}
}
请求参数的中文乱码问题
浏览器已什么编码向服务器提交数据,在查看/编码下可看到,是你在做网页时指定的。
//解决POST乱码 request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); System.out.println(username); | // 解决Get方式提交的乱码 String username2=request.getParameter("username2"); username2=new String(username2.getBytes("iso-8859-1"),"UTF-8"); System.out.println(username2); |
The HTTP Connector URIEncoding This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used. | <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" /> |
useBodyEncodingForURI This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitly set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false. | <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" useBodyEncodingForURI ="true" /> |
//无乱码 request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); response.setCharacterEncoding("gb2312"); response.setContentType("text/htm;charset=gb2312"); response.getWriter().write(username); |
Javascript防止表单重复提交
URL地址的编码
request对象实现请求转发:请求转发指一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理。
请求转发的应用场景:MVC设计模式
request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。
request对象同时也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理。
setAttribute方法
getAttribute方法
removeAttribute方法
getAttributeNames方法
//servlet中 String message="aaaaaa"; request.setAttribute("data", message); request.getRequestDispatcher("/mesage.jsp").forward(request, response); |
Jsp中 <% String mess=(String)request.getAttribute("message"); out.write(mess); %> |
请求转发的细节
forward方法用于将请求转发到RequestDispatcher对象封装的资源。
如果在调用forward方法之前,在Servlet程序中写入的部分内容已经被真正地传送到了客户端,forward方法将抛出IllegalStateException异常。
如果在调用forward方法之前向Servlet引擎的缓冲区中写入了内容,只要写入到缓冲区中的内容还没有被真正输出到客户端,forward方法就可以被正常执行,原来写入到输出缓冲区中的内容将被清空,但是,已写入到HttpServletResponse对象中的响应头字段信息保持有效。
请求重定向和请求转发的区别
一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理,称之为请求转发。
一个web资源收到客户端请求后,通知浏览器去访问另外一个web资源,称之为请求重定向。
RequestDispatcher.forward方法只能将请求转发给同一个WEB应用中的组件;而HttpServletResponse.sendRedirect方法还可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源。
如果传递给HttpServletResponse.sendRedirect 方法的相对URL以“/”开头,它是相对于整个WEB站点的根目录;如果创建RequestDispatcher对象时指定的相对URL以“/”开头,它是相对于当前WEB应用程序的根目录。
调用HttpServletResponse.sendRedirect方法重定向的访问过程结束后,浏览器地址栏中显示的URL会发生改变,由初始的URL地址变成重定向的目标URL;调用RequestDispatcher.forward方法的请求转发过程结束后,浏览器地址栏保持初始的URL地址不变。
HttpServletResponse.sendRedirect方法对浏览器的请求直接作出响应,响应的结果就是告诉浏览器去重新发出对另外一个URL的访问请求;RequestDispatcher.forward方法在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求并得到了响应结果,并不知道在服务器程序内部发生了转发行为。
RequestDispatcher.forward方法的调用者与被调用者之间共享相同的request对象和response对象,它们属于同一个访问请求和响应过程;而HttpServletResponse.sendRedirect方法调用者与被调用者使用各自的request对象和response对象,它们属于两个独立的访问请求和响应过程。
RequestDispatcher
include方法:
RequestDispatcher.include方法用于将RequestDispatcher对象封装的资源内容作为当前响应内容的一部分包含进来,从而实现可编程的服务器端包含功能。
被包含的Servlet程序不能改变响应消息的状态码和响应头,如果它里面存在这样的语句,这些语句的执行结果将被忽略。
request.getRequestDispatcher("/public/head.jsp").include(request, response); response.getWriter().write("hahaha"); request.getRequestDispatcher("/public/foot.jsp").include(request, response); |
//给服务器用 /代表当前应用 //给浏览器用 /代表网站,网站下有多个应用 request.getRequestDispatcher("/form1.html").include(request, response); response.sendRedirect("/day06/form1.html"); this.getServletContext().getRealPath("/form1.html"); this.getServletContext().getResourceAsStream("/fomr1.html"); /** * <a href="/day06/form.html">xx</a>
<form action="/day06/form.html"> </form> */ |
String referer=request.getHeader("referer");//利用referer防盗链 if(referer==null && !referer.startsWith("http://localhost")) { response.sendRedirect("/day06/index.jsp"); return; } response.getOutputStream().write("bbb".getBytes()); |
package com.tinghou.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.tinghou.entity.User;
public class ServletDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String str = "aaaaa";
System.out.println("A:我想办事");
System.out.println("B:我办不了,但我可以找人帮你办");
//将非表单的数据添加到request的域中
request.setAttribute("s", str);
//将请求转发到demo6中
//request.getRequestDispatcher("/servlet/demo6").forward(request, response);
//注:请求转发不能跳转到其它应用
//request.getRequestDispatcher("http://www.baidu.com").forward(request, response);
//使用重定向
//response.sendRedirect(request.getContextPath()+"/servlet/demo6");
//可以跳转到其它应用
//response.sendRedirect("http://www.baidu.com");
System.out.println("B:事办完了");
//请求包含
request.getRequestDispatcher("/servlet/demo6").include(request, response);
}
private void test1() {
// TODO Auto-generated method stub
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.tinghou.servlet;
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 ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("这个事我能办");
//将request对象中的移除
//request.removeAttribute("s");
//从request对象中获取s的值
String s = (String) request.getAttribute("s");
System.out.println(s);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
测试:
package com.tinghou.servlet;
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 ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("这个事我能办");
//将request对象中的移除
//request.removeAttribute("s");
//从request对象中获取s的值
String s = (String) request.getAttribute("s");
System.out.println(s);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
各种表单输入项数据的获取
text、password、radio、checkbox、file、select、textarea、hidden、image、button给js编程用
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>带数据给requestDemo3</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <br> <!-- Url后跟中文数据要编码后提交--> <form action="/day06/servlet/requestDemo3" method="post"> 用户名1 :<input type="text" name="username"/><br/> 密码: <input type="password" name="password"/><br/> 性别: <input type="radio" name="gender" value="male" />男 <input type="radio" name="gender" value="female" />女<br/>
所在地:<select name="city"> <option value="beijing">北京</option> <option value="shanghai">上海</option> <option value="cs">长沙</option> </select><br/> 爱好: <input type="checkbox" name ="likes" value="single" />唱歌 <input type="checkbox" name ="likes" value="dance" />跳舞 <input type="checkbox" name ="likes" value="basketball" />篮球 <input type="checkbox" name ="likes" value="football" />足球 <br/> 备注:<textarea rows="5" cols="60" name="description" ></textarea> <br/> 大头照<input type="file" name="image" /><br/> <input type="hidden" name="id" value="123456"/>
<input type="submit" value="提交"/> </form> </body> </html> | request.getParameter("username"); request.getParameter("password"); request.getParameter("gender"); request.getParameter("city"); request.getParameter("city"); String[] likes=request.getParameterValues("likes"); for(int i=0;likes!=null && i<likes.length;i++){ System.out.println(likes[i]); } request.getParameter("description");
request.getParameter("id"); |