1. 重定向(Redirect)和转发(forward)区别:
相同点:
都可以实现请求的跳转
不同点;
> 语法不同:
重定向: response.sendRedirect("main.html");
转发: request.getRequestDispatcher("main.html").forward(req,resp);
> 请求次数不同:
重定向一共浏览器发送了2次请求
转发是服务器内部跳转,只发送了1次请求
> 是否可以共享Request作用域中值:
重定向因为发送了2次去请求,所以Request中存储的值,不能跨请求共享!
转发因为是服务器内部跳转,使用的是同一个request对象,所以可以共享request中的值!
存值转发!
2. 今日相关代码:
Cookie 以及 Session 都是键值对的形式储存数据的
Cookie c = new Cookie(String name, Object obj);
Cookie构造方法, 创建一个新的Cookie对象
c.setMaxAge(int age);
设置cookie对象的存活时间, 单位为秒, 如果设置为-1代表消除当前cookie对象
c.setPath(String path);
设置cookie对象的作用域, 例如:"/view" 代表view文件夹下都可使用该cookie
"/" 代表全区域
HttpServletResponse response:
response.addCookie(Cookie c);
将cookie对象传入response中使其能在其他页面被获取到
HttpServletRequest request:
Cookies[] cookies = request.getCookies();
从request中获取到所有的cookies数组
String cookie.getName();
获取到当前cookie的Key值
Object cookie.getValue();
获取到当前cookie的Value值
HttpSession session = request.getSession();
创建一个HttpSession对象session
session.setMaxInactiveInterval(int age);
创建session对象的存活时间, 单位为秒
session.setAttribute(String key, Object value);
设置session中要进行传递的参数的key,value;
session.getAttribute(String key);
通过key值获取session中传递的参数
web.xml中配置HttpSession对象存活时间的方法为:
<session-config>age</session-config> age的单位为分钟!
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width=80;
int height=25;
BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
char[] array = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
Random r=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<6;i++){
int red=r.nextInt(255);
int green=r.nextInt(255);
int blue=r.nextInt(255);
g.setColor(new Color(red,green,blue));
int x1=r.nextInt(width);
int y1=r.nextInt(height);
int x2=r.nextInt(width);
int y2=r.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
for(int i=1;i<=4;i++){
int index=r.nextInt(62);
String str = array[index]+"";
sb.append(str);
/获取三个随机色值
int red=r.nextInt(255);
int green=r.nextInt(255);
int blue=r.nextInt(255);/
g.setColor(new Color(red,green,blue));
g.setFont(new Font("黑体", Font.BOLD, 18));
g.drawString(str, i*16, 18);
}
HttpSession session = request.getSession();
session.setAttribute("uCode", sb.toString());
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpeg", out);
}
}