区别
- 要取得客户端为服务端提交过来的数据,需要找Request。
- 要从服务端向客户端传送数据,需要找Response。
服务器端设置编码
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");//更改服务器发送数据的默认编码
response.setHeader("Content-Type","text/html;charset=UTF-8");//还要通知客户端解码方式
//字节流
String data = "你好,中国";
OutputStream out = response.getOutputStream();
response.setContentType("text/html;charset=UTF-8");
out.write(data.getBytes("UTF-8"));//以UTF-8进行编码
或者
//字符流
PrintWriter writer = response.getWriter();//默认编码是iso-8859-1 创建该对象前必须设置好编码方式
writer.write(data);
}
指定数据以下载的方式打开
通过设置response的响应头就可以实现,content-disposition服务器通过这个响应头告诉浏览器通过下载方式打开文件。
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
String path = "C:\\Users\\wwhhf\\Pictures\\Camera Roll\\QQ图片20160210090519.jpg";
String filename = path.substring(path.lastIndexOf("\\") + 1);
arg1.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(path);
int len = 0;
byte[] buffer = new byte[1024];
out = arg1.getOutputStream();
while((len = in.read(buffer)) > 0) {
out.write(buffer,0,len);
}
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
if(in != null) {
try {
in.close();
}catch(Exception e) {
throw new RuntimeException(e);
}
}
}
}
生成验证码图片
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.service(arg0, arg1);
arg1.addHeader("Pragma", "no-cache");
arg1.setHeader("Cache-Control", "no-cache");
arg1.setHeader("Expires", "0");
//1.内存图像 BufferedImage
BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
//2.创建画笔
Graphics g = image.getGraphics();
//2.1画边框
g.setColor(Color.GRAY);//设置边框颜色
g.drawRect(0, 0, WIDTH, HEIGHT);//画矩形边框
//2.2填充边框
g.fillRect(1, 1, WIDTH-1, HEIGHT-1);
//2.3输出验证随机数字4个
Random r = new Random();
g.setColor(Color.BLUE);
int x = 5;
for(int i=0;i<4;i++)
{
g.setFont(new Font("宋体",Font.BOLD,20));
g.drawString(r.nextInt(10)+"", x, 20);
x+=30;
}
//2.4画干扰线
g.setColor(Color.YELLOW);
for(int i = 0;i<9;i++)
{
g.drawLine(r.nextInt(WIDTH),r.nextInt(HEIGHT),r.nextInt(WIDTH), r.nextInt(HEIGHT));
}
//3 利用response输出流输出image
ImageIO.write(image,"jpeg",arg1.getOutputStream());
arg1.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);
}
在后台生成验证码的一般处理程序中除了在session写入验证码的内容,在cookie中也写一个验证码的内容
控制url跳转(延迟跳转)
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.service(arg0, arg1);
arg1.setHeader("Refresh", "5;URL=http://www.qq.com/");//5秒后跳转,url是跳转的链接
}
缓存作用:Expires实体报头域给出响应过期的日期和时间。为了让代理服务器或浏览器在一段时间以后更新缓存中(再次访问曾访问过的页面时,直接从缓存中加载,缩短响应时间和降低服务器负载)的页面,我们可以使用Expires实体报头域指定页面过期时间
用response实现请求重定向(状态码302重定向)
response.sendRedirect("login.jsp")
->http://localhost:8080/xxxSearch/login.jsp
需用绝对路径,因为重定向是发生在客户端的
[重定向]http://blog.chinaunix.net/uid-11121450-id-3221825.html)
获取客户端请求的信息
String locale = request.getLocalName();//传输协议
String url = request.getRequestURL().toString();//请求的地址
String uri = request.getRequestURI();//没有主机名的地址
String protocol = request.getProtocol();//获取协议
String add = request.getRemoteAddr();//客户端IP
String host = request.getRemoteHost();//客户端主机名
String port = request.getRemotePort()+"";//客户端端口号
String method = request.getMethod();//客户端的请求方式
String localAddr = request.getLocalAddr();//获取服务器地址
String username = request.getParameter("username");//地址后面?请求的参数
String serverPort = request.getServerPort()+"";//服务器端口号
String serverName = request.getServerName();//服务器名
获取请求参数的值
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.service(arg0, arg1);
Enumeration names = arg0.getParameterNames();
while(names.hasMoreElements()) { //根据参数名得到值
String name = (String)names.nextElement();
System.out.println(name+"------->"+arg0.getParameter(name));
}
}
显示图片在html上
private static final String PNG = "image/png;charset=utf-8";// 设定输出的类型
private static final String JPG = "image/jpeg;charset=utf-8";
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
String imagePath = "C:\\Users\\wwhhf\\Pictures\\Camera Roll\\zen-icons.png";
Image img=ImageIO.read(new File(imagePath));
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(img.getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH), 0, 0, null);
arg1.reset();
if (imagePath.toLowerCase().endsWith(".jpg"))// 使用编码处理文件流的情况:
{
arg1.setContentType(JPG);// 设定输出的类型
ImageIO.write(bi,"jpeg",arg1.getOutputStream());
arg1.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);
}
if (imagePath.toLowerCase().endsWith(".png"))// 使用编码处理文件流的情况:
{
arg1.setContentType(PNG);// 设定输出的类型
ImageIO.write(bi,"png",arg1.getOutputStream());
arg1.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);
}
}