一、常用表单数据的获取(复习表单,取数据用BeanUtils获取)
<
form
action =
"/day05_requestparameter/servlet/RegistServlet"
method =
"get" >
姓名: < input type = "text" name = "name" />< br />
性别: < input type = "radio" name = "gender" value = "male" checked = "checked" /> 男
< input type = "radio" name = "gender" value = "female" /> 女 < br />
已婚: < input type = "checkbox" name = "married" value = "on" />< br />
爱好: < input type = "checkbox" name = "hobby" value = "fb" /> 足球
< input type = "checkbox" name = "hobby" value = "bb" /> 篮球
< input type = "checkbox" name = "hobby" value = "ppb" /> 乒乓球 < br />
籍贯: < select name = "city" >
< option value = "BJ" > 北京 </ option >
< option value = "SD" > 山东 </ option >
< option value = "HB" > 湖北 </ option >
</ select >< br />
描述: < textarea rows = "3" cols = "38" name = "description" ></ textarea >< br />
< input type = "hidden" name = "id" value = "438" />< br />
< input type = "image" src = "/day05_requestparameter/xps.png" /> </ form >
姓名: < input type = "text" name = "name" />< br />
性别: < input type = "radio" name = "gender" value = "male" checked = "checked" /> 男
< input type = "radio" name = "gender" value = "female" /> 女 < br />
已婚: < input type = "checkbox" name = "married" value = "on" />< br />
爱好: < input type = "checkbox" name = "hobby" value = "fb" /> 足球
< input type = "checkbox" name = "hobby" value = "bb" /> 篮球
< input type = "checkbox" name = "hobby" value = "ppb" /> 乒乓球 < br />
籍贯: < select name = "city" >
< option value = "BJ" > 北京 </ option >
< option value = "SD" > 山东 </ option >
< option value = "HB" > 湖北 </ option >
</ select >< br />
描述: < textarea rows = "3" cols = "38" name = "description" ></ textarea >< br />
< input type = "hidden" name = "id" value = "438" />< br />
< input type = "image" src = "/day05_requestparameter/xps.png" /> </ form >
二、请求转发和重定向(ServletRequest也是一个域对象)
![](d54d977c-d174-4587-aaa3-b90a1bdabd5a_files/162000265.png)
ServletRequest也是一个域(范围)对象
void setAttribute(String key,Object value);:设置消息头
Object getAttribute(String key);获取消息头key的value
void removeAttribute(String key);删除消息头key
RequestDispatcher:
区别在于参数path路径的写法。
ServletContext.getRequestDispatcher(String path):只能以/开头。/就代表当前应用。(绝对路径)
ServletRequest.getRequestDispatcher(String path):如果以/开头。/就代表当前应用。(绝对路径)。如果不以/开头,就表示相对路径。
请求重定向
//源
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute( "p" , "ppp" );
// response.setStatus(302);//请求重定向:是客户端的行为
// response.setHeader("Location", "/day05_requestparameter/ servlet /ServletDemo2");
//请求重定向,简化代码
response. sendRedirect ( "/day05_requestparameter/servlet/ServletDemo2" ); }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute( "p" , "ppp" );
// response.setStatus(302);//请求重定向:是客户端的行为
// response.setHeader("Location", "/day05_requestparameter/ servlet /ServletDemo2");
//请求重定向,简化代码
response. sendRedirect ( "/day05_requestparameter/servlet/ServletDemo2" ); }
//目标
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//请求转发,目标肯定得不到消息头
System. out .println(request.getAttribute( "p" ));
response.setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我给你办" ); }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//请求转发,目标肯定得不到消息头
System. out .println(request.getAttribute( "p" ));
response.setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我给你办" ); }
请求转发
//源:转发。是服务器端行为
//转发时,源组件任何输出都无效。头有效
//用转发时:源组件请不要输出任何内容。输出也白输。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我不给你办" );
request.setAttribute( "p" , "ppppp" );
// ServletContext sc = getServletContext();//ServletContext进行转发
// //得到转发的类RequestDispatcher 请求分发器
// RequestDispatcher rd = sc.getRequestDispatcher("/ servlet /ServletDemo4");
// rd.forward(request, response);//传递下去了
//转发简化的方式
// request.getRequestDispatcher("/ servlet /ServletDemo4").forward(request, response);//绝对路径
request.getRequestDispatcher( "ServletDemo4" ).forward(request, response); //相对路径 }
//转发时,源组件任何输出都无效。头有效
//用转发时:源组件请不要输出任何内容。输出也白输。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我不给你办" );
request.setAttribute( "p" , "ppppp" );
// ServletContext sc = getServletContext();//ServletContext进行转发
// //得到转发的类RequestDispatcher 请求分发器
// RequestDispatcher rd = sc.getRequestDispatcher("/ servlet /ServletDemo4");
// rd.forward(request, response);//传递下去了
//转发简化的方式
// request.getRequestDispatcher("/ servlet /ServletDemo4").forward(request, response);//绝对路径
request.getRequestDispatcher( "ServletDemo4" ).forward(request, response); //相对路径 }
//目标:转发
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System. out .println(request.getAttribute( "p" ));
response .setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我给你办" ); }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System. out .println(request.getAttribute( "p" ));
response .setContentType( "text/html;charset=UTF-8" );
response.getWriter().write( "我给你办" ); }
包含 下面的例子打印Demo5Demo6
//源:包含
//包含:目标输出结果会显示到源组件中(只包含正文)。目标设置的响应消息头无效。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "Demo5" );
request.getRequestDispatcher( "/servlet/ServletDemo6" ).include(request, response); }
//包含:目标输出结果会显示到源组件中(只包含正文)。目标设置的响应消息头无效。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "Demo5" );
request.getRequestDispatcher( "/servlet/ServletDemo6" ).include(request, response); }
//目标:包含
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "Demo6" ); }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "Demo6" ); }
request对象重点把握:
1、获取请求参数及如何解决中文乱码:注意设置编码。
2、理解请求转发和请求重定向的不同
3、request域范围是多大:每一次请求。
三、各种URL地址的写法
相对路径:
绝对路径:推荐使用。必须以"/"开头
绝对路径在使用时:如果地址给服务器端用的,"/"就代表当前应用。否则就需要加上当前应用名称。
form的action:要加应用名称
<a href=""/>:要加应用名称
<img src=""/>:要加应用名称
<script src=""></script>:要加应用名称
<link href=""/>:要加应用名称
HttpServletResponse.sendRedirect(String path):要加应用名称
ServletContext.getRealPath(String url):不要加
ServletRequest.getRequestDispatcher(String path):不要加
四、会话概述
1、什么是会话及会话的界定范围
2、会话过程中要结局的就是各个用户数据的保留问题。
五、Cookie详解
1、属性:
name:(必须)
value:(必须)不能是中文
maxage:(可选)最长存活时间.默认是会话。单位是秒
path:(可选)路径
一个cookie的默认路径是:写cookie的那个servlet的访问路径。
写cookie的servlet的路径是:String path = /day05_01_cookie/servlet/
如果访问的路径.startWith(path),浏览器就会把刚才写的cookie带给服务器。
domain :(可选)域名
comment:(可选)注释
version:(可选)版本号
2、服务器如何向客户端写Cookie:
HttpServletResponse.addCookie(javax.servlet.http.Cookie)(实际上就是写了一个Set-Cookie的响应消息头)
浏览器对于一个网站最多存20个cookie (Cookie的个数是有限的)
cookie总数不能超过300个。
每个Cookie大小不能超过4KB。
3、服务器如何取出客户端带来的cookie:HttpServletRequest.getCookies() (实际上就是获取 名字为cookie的请求消息头)
4、如何唯一确定一个Cookie
domain+path+name
localhost/day05_01_cookie/servlet/ + lastAccessTime
六、Cookie案例:
利用cookie技术记录用户最近一次访问的时间
public
void doGet(HttpServletRequest request , HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "上次访问的时间是:" );
//得到指定的cookie,该cookie中记录了上次访问的时间
Cookie[] cs = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
Cookie c = cs[i];
if ( "lastTime" .equals(c.getName())){
String value = c.getValue();
//把cookie里面字符串转成long,再由Date转成可读格式
long time = Long. parseLong (value);
String ti = new Date(time). toLocaleString() ;
out.write(ti);
}
}
//清除cookie
out.write( "<a href='/my_exericse_day05/servlet/MyCookieDemo2'>清除cookie</a>" );
//把当前时间写入到cookie里面
Cookie cookie = new Cookie( "lastTime" , System. currentTimeMillis () + "" );
//设置cookie的存货时间,单位是秒.如果是Long单位多半是毫秒
cookie.setMaxAge( 1 * 30 * 24 * 60 * 60);
//设置路径为当前应用的名称,意味着当前应用的任何资源都可以得到该cookie.
cookie.setPath(request.getContextPath());
response.addCookie(cookie); }
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
out.write( "上次访问的时间是:" );
//得到指定的cookie,该cookie中记录了上次访问的时间
Cookie[] cs = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
Cookie c = cs[i];
if ( "lastTime" .equals(c.getName())){
String value = c.getValue();
//把cookie里面字符串转成long,再由Date转成可读格式
long time = Long. parseLong (value);
String ti = new Date(time). toLocaleString() ;
out.write(ti);
}
}
//清除cookie
out.write( "<a href='/my_exericse_day05/servlet/MyCookieDemo2'>清除cookie</a>" );
//把当前时间写入到cookie里面
Cookie cookie = new Cookie( "lastTime" , System. currentTimeMillis () + "" );
//设置cookie的存货时间,单位是秒.如果是Long单位多半是毫秒
cookie.setMaxAge( 1 * 30 * 24 * 60 * 60);
//设置路径为当前应用的名称,意味着当前应用的任何资源都可以得到该cookie.
cookie.setPath(request.getContextPath());
response.addCookie(cookie); }
//删除指定的cookie
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
Cookie c = new Cookie( "lastAccesTime" , "" ); //和上面的一样的
c.setMaxAge( 0);
c.setPath(request.getContextPath());
response.addCookie(c);
out.write( "删除成功!" ); }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
Cookie c = new Cookie( "lastAccesTime" , "" ); //和上面的一样的
c.setMaxAge( 0);
c.setPath(request.getContextPath());
response.addCookie(c);
out.write( "删除成功!" ); }
提供选项让用户设置是否记录登录名
//提供登陆界面
//显示记住的用户名
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示记住的用户名
String username = "" ;
String checked = "" ;
//找到指定的cookie
Cookie cs[] = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
if (CookieStatics. LOGIN_USERNAME .equals(cs[i].getName())){
//找到了
String value = cs[i].getValue();
username = value;
checked = "checked='checked'" ;
break ; //不希望程序继续往下运行
}
}
//提供登陆界面
out.write( "<form action='" +request.getContextPath() + "/servlet/LoginServletDemo2' method='post'>" );
out.write( "用户名:<input type='text' name='username' value='" +username + "'/><br/>" );
out.write( "密码:<input type='password' name='password'/><br/>" );
out.write( "记住用户名:<input type='checkbox' name='remember' " +checked + " /><br/>" );
out.write( "<input type='submit' value='登陆'/>" );
out.write( "</form>" ); }
//显示记住的用户名
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示记住的用户名
String username = "" ;
String checked = "" ;
//找到指定的cookie
Cookie cs[] = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
if (CookieStatics. LOGIN_USERNAME .equals(cs[i].getName())){
//找到了
String value = cs[i].getValue();
username = value;
checked = "checked='checked'" ;
break ; //不希望程序继续往下运行
}
}
//提供登陆界面
out.write( "<form action='" +request.getContextPath() + "/servlet/LoginServletDemo2' method='post'>" );
out.write( "用户名:<input type='text' name='username' value='" +username + "'/><br/>" );
out.write( "密码:<input type='password' name='password'/><br/>" );
out.write( "记住用户名:<input type='checkbox' name='remember' " +checked + " /><br/>" );
out.write( "<input type='submit' value='登陆'/>" );
out.write( "</form>" ); }
//验证用户名或密码
//根据用户是否需要记住用户名来处理cookie
//是:添加cookie
//否:删除cookie
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//验证用户名或密码
String username = request.getParameter( "username" );
String remember = request.getParameter( "remember" );
//根据用户是否需要记住用户名来处理cookie
//用一个借口,来定义一个常量。直接引用,不容易出错
Cookie c = new Cookie(CookieStatics. LOGIN_USERNAME , username);
c.setPath(request.getContextPath());
if (remember == null ){
//否:删除cookie
c.setMaxAge( 0);
} else {
//是:添加cookie的失效时间为最大
c.setMaxAge(Integer. MAX_VALUE );
}
response.addCookie(c);
out.write( "登陆成功!" ); }
//根据用户是否需要记住用户名来处理cookie
//是:添加cookie
//否:删除cookie
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//验证用户名或密码
String username = request.getParameter( "username" );
String remember = request.getParameter( "remember" );
//根据用户是否需要记住用户名来处理cookie
//用一个借口,来定义一个常量。直接引用,不容易出错
Cookie c = new Cookie(CookieStatics. LOGIN_USERNAME , username);
c.setPath(request.getContextPath());
if (remember == null ){
//否:删除cookie
c.setMaxAge( 0);
} else {
//是:添加cookie的失效时间为最大
c.setMaxAge(Integer. MAX_VALUE );
}
response.addCookie(c);
out.write( "登陆成功!" ); }
记录用户的浏览记录
//显示所有的书籍,并提供查看详细的链接
//显示用户最近的浏览记录:保留3
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示所有的书籍,并提供查看详细的链接
out.write( "本站有以下好书,欢迎选购:<br/>" );
Map <String, Book > books = BookDB. findAllBooks ();
for (Map.Entry <String, Book > me :books.entrySet()){
out.write(me.getValue().getName() + " <a href='" +request.getContextPath() + "/servlet/ShowBookDetailServlet?id=" +me.getValue().getId() + "'>详情</a><br/>" );
}
//显示用户最近的浏览记录:保留3 bookHistory=3-2-1
out.write( "<hr/>您最近的浏览记录:<br/>" );
Cookie cs[] = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
Cookie c = cs[i];
if ( "bookHistory" .equals(c.getName())){
String bookIds = c.getValue(); //3-2-1
String ids[] = bookIds.split( "\\-" );
for (String id :ids){
Book book = BookDB. findBookById (id);
out.write(book.getName() + "<br/>" );
}
break ;
}
} }
//显示用户最近的浏览记录:保留3
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示所有的书籍,并提供查看详细的链接
out.write( "本站有以下好书,欢迎选购:<br/>" );
Map <String, Book > books = BookDB. findAllBooks ();
for (Map.Entry <String, Book > me :books.entrySet()){
out.write(me.getValue().getName() + " <a href='" +request.getContextPath() + "/servlet/ShowBookDetailServlet?id=" +me.getValue().getId() + "'>详情</a><br/>" );
}
//显示用户最近的浏览记录:保留3 bookHistory=3-2-1
out.write( "<hr/>您最近的浏览记录:<br/>" );
Cookie cs[] = request.getCookies();
for ( int i = 0;cs != null &&i <cs. length ;i ++){
Cookie c = cs[i];
if ( "bookHistory" .equals(c.getName())){
String bookIds = c.getValue(); //3-2-1
String ids[] = bookIds.split( "\\-" );
for (String id :ids){
Book book = BookDB. findBookById (id);
out.write(book.getName() + "<br/>" );
}
break ;
}
} }
//显示书籍的详细内容
//向客户端写cookie记录浏览历史
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示书籍的详细内容
String bookId = request.getParameter( "id" );
out.write( "详情:" +BookDB. findBookById (bookId).toString());
out.write( "<br/><a href='" +request.getContextPath() + "/servlet/ShowAllBooksServlet'>继续购物</a>" );
//向客户端写cookie记录浏览历史
String ids = makeIds(request,bookId); //用-分隔
Cookie c = new Cookie( "bookHistory" , ids);
c.setPath(request.getContextPath());
c.setMaxAge(Integer. MAX_VALUE );
response.addCookie(c);
}
//组织要写回的书的id
// 当前情况 新看的书 应写回的id
// cookie一个都没有 1 1
// cookie不为null,但没有bookHistory 1 1
// bookHistory=1 2 2-1
// bookHistory=2-1 1 1-2
// bookHistory=2-1 3 3-2-1
// bookHistory=2-1-3 3 3-2-1
// bookHistory=2-1-3 4 4-2-1
private String makeIds(HttpServletRequest request, String bookId) {
// cookie一个都没有 1 1
Cookie cs[] = request.getCookies();
if (cs == null ||cs. length == 0)
return bookId;
// cookie不为null,但没有bookHistory 1 1
Cookie bookHistoryCookie = null ;
for (Cookie c :cs){
if ( "bookHistory" .equals(c.getName())){
bookHistoryCookie = c;
break ;
}
}
if (bookHistoryCookie == null ){
return bookId;
}
// bookHistory=1 2 2-1
// bookHistory=2-1 1 1-2
// bookHistory=2-1 3 3-2-1
String id = bookHistoryCookie.getValue(); // 2-1
LinkedList <String > list = new LinkedList <String >(Arrays. asList (id.split( "\\-" ))); // 2 1
if (list.size() < 3){
if (list.contains(bookId)){
list.remove(bookId);
}
list.addFirst(bookId);
} else {
// bookHistory=2-1-3 3 3-2-1
// bookHistory=2-1-3 4 4-2-1
if (list.contains(bookId)){
list.remove(bookId);
} else {
list.removeLast();
}
list.addFirst(bookId);
}
//把list中的id组织成字符串
//3 2 1---->3-2-1
StringBuffer sb = new StringBuffer();
for ( int i = 0;i <list.size();i ++){
if (i > 0)
sb.append( "-" );
sb.append(list.get(i));
}
return sb.toString(); }
//向客户端写cookie记录浏览历史
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
//显示书籍的详细内容
String bookId = request.getParameter( "id" );
out.write( "详情:" +BookDB. findBookById (bookId).toString());
out.write( "<br/><a href='" +request.getContextPath() + "/servlet/ShowAllBooksServlet'>继续购物</a>" );
//向客户端写cookie记录浏览历史
String ids = makeIds(request,bookId); //用-分隔
Cookie c = new Cookie( "bookHistory" , ids);
c.setPath(request.getContextPath());
c.setMaxAge(Integer. MAX_VALUE );
response.addCookie(c);
}
//组织要写回的书的id
// 当前情况 新看的书 应写回的id
// cookie一个都没有 1 1
// cookie不为null,但没有bookHistory 1 1
// bookHistory=1 2 2-1
// bookHistory=2-1 1 1-2
// bookHistory=2-1 3 3-2-1
// bookHistory=2-1-3 3 3-2-1
// bookHistory=2-1-3 4 4-2-1
private String makeIds(HttpServletRequest request, String bookId) {
// cookie一个都没有 1 1
Cookie cs[] = request.getCookies();
if (cs == null ||cs. length == 0)
return bookId;
// cookie不为null,但没有bookHistory 1 1
Cookie bookHistoryCookie = null ;
for (Cookie c :cs){
if ( "bookHistory" .equals(c.getName())){
bookHistoryCookie = c;
break ;
}
}
if (bookHistoryCookie == null ){
return bookId;
}
// bookHistory=1 2 2-1
// bookHistory=2-1 1 1-2
// bookHistory=2-1 3 3-2-1
String id = bookHistoryCookie.getValue(); // 2-1
LinkedList <String > list = new LinkedList <String >(Arrays. asList (id.split( "\\-" ))); // 2 1
if (list.size() < 3){
if (list.contains(bookId)){
list.remove(bookId);
}
list.addFirst(bookId);
} else {
// bookHistory=2-1-3 3 3-2-1
// bookHistory=2-1-3 4 4-2-1
if (list.contains(bookId)){
list.remove(bookId);
} else {
list.removeLast();
}
list.addFirst(bookId);
}
//把list中的id组织成字符串
//3 2 1---->3-2-1
StringBuffer sb = new StringBuffer();
for ( int i = 0;i <list.size();i ++){
if (i > 0)
sb.append( "-" );
sb.append(list.get(i));
}
return sb.toString(); }
七、HttpSession原理详解
HttpSession借助Cookie技术的。
HttpSession getSession():服务器会根据用户带来的JSESSIONIDcookie的值,先查找。找到继续为你服务,没有找到,创建新的HttpSession对象。
HttpSession getSession(boolean b):
b为true:效果同getSession()
b为false:只是查询。