JavaWeb之Request/Response代码修炼篇(五)
1. 解决中文字符编码问题
String str = "我爱java"; //第一种方法 response.setContentType("text/html;charset=GBK");(推荐) //第二种方法 //response.setHeader("Content-Type","text/html;charset=UTF-8"); //第三种方法 //response.getOutputStream().write("<meta http-equiv=‘Content-Type‘ content=‘text/html;charset=UTF-8‘>".getBytes()); response.getOutputStream().write(str.getBytes());
2. Firefox中文文件名下载问题
String path = "/WEB-INF/classes/你好.jpg"; String filename = path.substring(path.lastIndexOf("/")+1); String absolutePath = getServletContext().getRealPath(path); if(request.getHeader("User-Agent").contains("Firefox")) { response.setHeader("Content-Disposition", "attachment;filename="+encodeDownloadFilename(filename, "Firefox")); } else { response.setHeader("Content-Disposition", "attachment;filename="+encodeDownloadFilename(filename, "ie")); } InputStream is = new FileInputStream(absolutePath); OutputStream os = response.getOutputStream(); int len = -1; byte buf[] = new byte[1024]; while((len=is.read(buf)) != -1) { os.write(buf, 0, len); } is.close(); public String encodeDownloadFilename(String filename, String agent) throws IOException { if(agent.contains("Firefox")) { filename = "=?UTF-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?="; } else { filename = URLEncoder.encode(filename,"UTF-8"); } return filename; }
3. 验证码图片
//控制浏览器定时刷新 response.setHeader("refresh", "10"); //定义高度和宽度 int width = 120, height = 25; //创建一个图像缓冲区 BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //得到画笔 Graphics g = bImage.getGraphics(); //设置画笔颜色画边框,填充背景,画线条,画字符串 g.setColor(Color.BLACK); g.drawRect(0, 0, width, height); //填充背景 g.setColor(Color.LIGHT_GRAY); g.fillRect(1, 1, width-2, height-2); //画线条 Random r = new Random(); g.setColor(Color.CYAN); for(int i=0; i<20; i++) { g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); } //字符串,设置字体样式 Font font = new Font("楷体",Font.BOLD|Font.ITALIC, 20); g.setFont(font); g.setColor(Color.RED); String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728"; for(int i=0; i<4; i++) { String ch = base.charAt(r.nextInt(base.length())) +""; g.drawString(ch, 20+(20*i), 20); } //设置头信息显示数据类型 response.setHeader("Content-Type", "image/jpeg"); //清空缓存信息 response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ImageIO.write(bImage, "jpg", response.getOutputStream());
4. 设置缓存时间
response.setContentType("text/html;charset=UTF-8"); response.setDateHeader("Expires", System.currentTimeMillis()+60*60*1000); PrintWriter out = response.getWriter(); out.write("刘若英-十年");
5.1 获取请求参数方式1
//1. 获取获取请求参数(文本框中的值) request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); Enumeration<String> names = request.getParameterNames(); while(names.hasMoreElements()) { /*String name = new String(names.nextElement().getBytes("ISO-8859-1"),"UTF-8"); String value = new String(request.getParameter(name).getBytes("ISO-8859-1"),"UTF-8");*/ String name = names.nextElement(); String value = request.getParameter(name); response.getWriter().write(name+": "+value); }
5.2 获取请求参数方式2
// 2. 通过反射获取请求参数 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); User user = new User(); Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String values[] = request.getParameterValues(name); Class clazz = user.getClass(); try { Field field = clazz.getDeclaredField(name); field.setAccessible(true); if (values != null & values.length > 1) { field.set(user, (Object) values); } else { field.set(user, values[0]); } } catch (Exception e) { throw new RuntimeException(e); } } response.getWriter().write(user.getUsername() + ">>"+ Arrays.toString(user.getPassword()));
5.3 获取请求参数方式3
// 3. 通过内省完成获取请求参数 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); User user = new User(); Map<String, String[]> map = request.getParameterMap(); for(Map.Entry<String, String[]> entry : map.entrySet()) { String name = entry.getKey(); String values[] = entry.getValue(); try { PropertyDescriptor pd = new PropertyDescriptor(name, User.class); Method m = pd.getWriteMethod(); if(values!=null && values.length>1) { m.invoke(user, (Object)values); } else { m.invoke(user, values[0]); } } catch (Exception e) { e.printStackTrace(); } } response.getWriter().write(user.getUsername() + ">>" +Arrays.toString(user.getPassword()));
5.4 获取请求参数方式4
// 4. 通过BeanUtils中setProperty()方法 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); User user = new User(); Map<String, String[]> map = request.getParameterMap(); for(Map.Entry<String, String[]> entry : map.entrySet()) { String name = entry.getKey(); String values[] = entry.getValue(); try { if(values!=null && values.length>1) { BeanUtils.setProperty(user, name, (Object)values); } else { BeanUtils.setProperty(user, name, values[0]); } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } response.getWriter().write(user.getUsername() + ">>" + Arrays.toString(user.getPassword()));
5.5 获取请求参数方式5
// 5. 通过BeanUtils中的populator()方法 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); User user = new User(); try { BeanUtils.populate(user, request.getParameterMap()); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } response.getWriter().write(user.getUsername() + ">>" + Arrays.toString(user.getPassword()));
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。