代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,开发人员通过这个对象的方法,可以获得客户这些信息。
getRequestURL方法返回客户端发出请求时的完整URL。
getRequestURI方法返回请求行中的资源名部分。
getQueryString 方法返回请求行中的参数部分。
getRemoteAddr方法返回发出请求的客户机的IP地址
getRemoteHost方法返回发出请求的客户机的完整主机名
getRemotePort方法返回客户机所使用的网络端口号
getLocalAddr方法返回WEB服务器的IP地址。
getLocalName方法返回WEB服务器的主机名
getMethod得到客户机请求方式
实验:/day0900httpServletRequest工程 工程架构如下:
配置文件web.xml
ServletRequest1
com.heima.request.ServletRequest1
ServletRequest2
com.heima.request.ServletRequest2
ServletReqeust3
com.heima.request.ServletReqeust3
ServletReqeust4
com.heima.request.ServletReqeust4
ServletReqeust5
com.heima.request.ServletReqeust5
ServletRequest6
com.heima.request.ServletRequest6
ServletRequest7
com.heima.request.ServletRequest7
ServletRequest8
com.heima.request.ServletRequest8
ServletRequest9
com.heima.request.ServletRequest9
ServletRequest1
/servlet/ServletRequest1
ServletRequest2
/servlet/ServletRequest2
ServletReqeust3
/servlet/ServletReqeust3
ServletReqeust4
/servlet/ServletReqeust4
ServletReqeust5
/servlet/ServletReqeust5
ServletRequest6
/servlet/ServletRequest6
ServletRequest7
/servlet/ServletRequest7
ServletRequest8
/servlet/ServletRequest8
ServletRequest9
/servlet/ServletRequest9
index.jsp
User.java
import java.io.Serializable;
import java.util.Arrays;
//属性名和表单控件的名字一致
public class User implements Serializable {
private String username ;
private String[] password ;
private String gander ;
private String[] loves ;
private String graduation ;
private String bake ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String[] getPassword() {
return password;
}
public void setPassword(String[] password) {
this.password = password;
}
public String getGander() {
return gander;
}
public void setGander(String gander) {
this.gander = gander;
}
public String[] getLoves() {
return loves;
}
public void setLoves(String[] loves) {
this.loves = loves;
}
public String getGraduation() {
return graduation;
}
public void setGraduation(String graduation) {
this.graduation = graduation;
}
public String getBake() {
return bake;
}
public void setBake(String bake) {
this.bake = bake;
}
@Override
public String toString() {
return "User [username=" + username + ", password="
+ Arrays.toString(password) + ", gander=" + gander + ", loves="
+ Arrays.toString(loves) + ", graduation=" + graduation
+ ", bake=" + bake + "]";
}
// @Override
// public String toString() {
// return "User [username=" + username + ", password="
// + Arrays.toString(password) + "]";
// }
}
ServletRequest1.java
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 ServletRequest1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
String contextpath = request.getContextPath() ;
String localAddr = request.getLocalAddr() ;
int localport = request.getLocalPort() ;
StringBuffer url = request.getRequestURL() ;
String uri = request.getRequestURI() ;
String romoteaddr = request.getRemoteAddr() ;
int rport = request.getRemotePort() ;
String host = request.getRemoteHost() ;
String method = request.getMethod() ;
String query = request.getQueryString() ;
out.write("获得上下文路径: " + contextpath + "
") ; //"/" + 工程路径
out.write("获取服务器的IP地址:" + localAddr + "
") ;
out.write("获取服务器的端口号:" + localport + "
") ;
out.write("获取浏览器的请求地址:" + url + "
") ;
out.write("获取浏览器的ip地址:" + romoteaddr + "
") ;
out.write("获取浏览器访问的URI::" + uri + "
") ; // contextpath + "资源地址"
out.write("获取客户端访问的端口号:" + rport + "
") ;
out.write("获取客户端的机器Ip::" + host + "
") ;
out.write("获取请求方式:" + method + "
") ;
out.write("获取请求参数:" + query + "
") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器输入http://localhost:8080/day0900httpServletRequest/servlet/ServletRequest1,结果如下
getHead(name)方法
getHeaders(String name)方法
getHeaderNames方法
ServletRequest2.java
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 ServletRequest2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//获取单个请求头信息
// String value = request.getHeader("Accept-Language") ;
// System.out.println("Accept-Language:" + value);
//获取单个名称多个值的请求头
// Enumeration enu = request.getHeaders("Accept-Language") ;
// while(enu.hasMoreElements()){
// String value = enu.nextElement() ;
// System.out.println(value);
// }
//获取所有的请求头名称和值
Enumeration enu = request.getHeaderNames() ;
while(enu.hasMoreElements()){
String name = enu.nextElement() ;
Enumeration values = request.getHeaders(name) ;
while(values.hasMoreElements()){
String value = values.nextElement() ;
System.out.println(name + ":" + value);
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器输入:http://localhost:8080/day0900httpServletRequest/servlet/ServletRequest2,浏览器会发送以下一段http的头信息到服务器:
服务器接收到了这些头信息之后,servlet处理并输出以下结果:
getParameter(name)方法
getParameterValues(String name)方法
getParameterNames方法
getParameterMap方法 //做框架用,非常实用
getInputStream
register.html
register.html
ServletReqeust3.java
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
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;
//演示获取客户端的请求参数
public class ServletReqeust3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// tes1(request) ;
// tes2(request) ;
// tes3(request) ;
// tes4(request) ;
// tes5(request) ;
tes6(request) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
//1.拿到单个表单控件的的值:拿取姓名的值
public void tes1(HttpServletRequest request){
String name = request.getParameter("username") ;
System.out.println(name);
}
//2.拿到表单控件的的值(同名控件的多个值):拿取密码的值
public void tes2(HttpServletRequest request){
String[] password = request.getParameterValues("password") ;
for (String string : password) {
System.out.println(string);
}
}
//3.拿到所有控件的名字和值
public void tes3(HttpServletRequest request){
Enumeration names = request.getParameterNames() ;
while(names.hasMoreElements()){
String name = names.nextElement() ;
String[] values = request.getParameterValues(name) ;
System.out.println(name + ":" + Arrays.asList(values));
}
}
//4.将获取的参数应当封装到javabean中: 采用PropertyDesciptor
public void tes4(HttpServletRequest request){
User user = new User() ;
System.out.println("封装前: " + user);
//获取所有的表单控件的名字
Enumeration names = request.getParameterNames() ;
//循环封装
while(names.hasMoreElements()){
//拿取控件的名字
String name = names.nextElement() ;
//控件的值
String[] values = request.getParameterValues(name) ;
try {
PropertyDescriptor pd = new PropertyDescriptor(name, User.class) ; //拿到User对象的属性name的属性描述器
Method m = pd.getWriteMethod() ; //拿到属性的set方法
//为了兼容jdk1.4的版本,虚拟机会将values拆分成一个一个值进行传递
if(values !=null && values.length == 1)
m.invoke(user, values) ;
else{
//方法一:强转成一个object
//m.invoke(user, (Object)values) ;
//方法二:创建一个数组
m.invoke(user, new Object[]{values}) ;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("封装后: " + user);
}
//5.将获取的参数应当封装到javabean中: 采用BeanUtils
public void tes5(HttpServletRequest request){
User user = new User() ;
System.out.println("封装前: " + user);
//获取所有的表单控件的名字
Enumeration names = request.getParameterNames() ;
//循环封装
while(names.hasMoreElements()){
//拿取控件的名字
String name = names.nextElement() ;
//控件的值
String[] values = request.getParameterValues(name) ;
try {
BeanUtils.setProperty(user, name, values) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("封装后: " + user);
}
//6.将获取的参数应当封装到javabean中: 采用BeanUtils的另一种方式
public void tes6(HttpServletRequest request){
User user = new User() ;
System.out.println("封装前: " + user);
//拿到键值对的映射
Map map = request.getParameterMap() ;
for (Map.Entry entry : map.entrySet()) { //entry就是键值对
String name = entry.getKey() ; //拿到键
String[] values = entry.getValue() ; //拿到值
try {
BeanUtils.setProperty(user, name, values) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("封装后: " + user);
}
//7.终极必杀技 (采用beanUtils类)(推荐)
public void tes7(HttpServletRequest request){
User user = new User() ;
System.out.println("封装前: " + user);
try {
BeanUtils.populate(user, request.getParameterMap()) ;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("封装后: " + user);
}
}
在浏览器中输入:http://localhost:8080/day0900httpServletRequest/register.html,弹出以下页面,并输入信息:
输入信息之后,信息会提交到服务器并servlet处理之后得出以下结果:
text、password、radio、checkbox、file、select、textarea、 hidden、image、button给js编程用
register.html
register.html
ServletReqeust4.java
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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;
//演示封装所有表单控件的值
public class ServletReqeust4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
User user = new User() ;
System.out.println("封装前: " + user);
try {
BeanUtils.populate(user, request.getParameterMap()) ;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("封装后: " + user);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0900httpServletRequest/register1.html,弹出以下页面,并填写选项提交,把信息提交到了服务器中:
服务器反馈如下信息:
浏览器是什么编码就以什么编码传送数据?
解决:
request.setCharacterEncoding(“UTF-8”);//POST有效
new String(username.getBytes(“ISO-8859-1”),“UTF-8”);//GET方式
超链接:cn//GET方式
更改Tomcat的配置解决URL编码问题:
login.html
register.html
ServletReqeust5.java
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 ServletReqeust5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//post方式提交的乱码解决
//request.setCharacterEncoding("UTF-8"); //将请求数据用utf-8进行解码,只能针对post方式
//针对get方式解决
String name = request.getParameter("username") ;
name = new String(name.getBytes("iso-8859-1"),"UTF-8") ; //此种方式针对少量的中文
//当多个控件中都存在中文的时候,此时推荐修改服务器的编码,找出服务器server.xml文件,修改里的URIEncoding属性为"UTF-8"
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
来浏览器中输入:http://localhost:8080/day0900httpServletRequest/login.html,弹出以下页面:
输入信息后提交到了服务端,服务端的servlet处理完后得到以下结果:
请求转发指一个web资源收到客户端请求后,通知服务器去调用另外一个web资源进行处理。
request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。
request对象同时也是一个域对象,开发人员通过request对象在实现转发时,把数据通过request对象带给其它web资源处理。
setAttribute方法
getAttribute方法
removeAttribute方法
getAttributeNames方法
包含:
包含:Servelt(源组件)把其他web组件(目标组件)生成的响应结果包含到自身的响应结果中。
ServletRequest6.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示请求转发
public class ServletRequest6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//请求对象也是一个域对象
request.setAttribute("name", "任盈盈") ;
PrintWriter out = response.getWriter() ;
//out.write("哈哈哈啊啊") ; //页面上输不出来
//out.flush() ; //不能再转发之前提交
//请求转发 (先清空了缓冲区)
// RequestDispatcher rd = request.getRequestDispatcher("/servlet/ServletRequest7") ;
RequestDispatcher rd = request.getRequestDispatcher("ServletRequest7") ;
rd.forward(request, response) ;
/*
* ServletContext对象的请求转发与request对象的请求转发的不同:
* 1.request对象的请求转发可以写相对路径, ServletContext对象的请求转发只能写绝对路径
* */
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletRequest7.java
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 ServletRequest7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String name = (String) request.getAttribute("name") ;
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入: http://localhost:8080/day0900httpServletRequest/servlet/ServletRequest6,在服务器中输出的结果为: 任盈盈
forward():把请求转发给目标组件
public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
include():包含目标组件的响应结果
public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
1、ServletContext对象的getRequestDispather(String path1) path1必须用绝对路径,即以”/”开头,若用相对路径会抛出异常IllegalArgumentException
2、ServletRequest对象的getRequestDispatcher(String path2) path2可以用绝对路径也可以用相对路径
1、清空用于存放响应正文数据的缓冲区
2、如果目标组件为Servlet或JSP,就调用它们,把它们产生的响应结果发送到客户端;如果目标组件为文件系统中的静态HTML文档,就读取文档中的数据并把它发送给客户端。
特点:
1、由于forward()方法先清空用于存放响应正文数据的缓冲区,因此源组件生成的响应结果不会被发送到客户端,只有目标组件生成的响应结果才会被送到客户端。
2、如果源组件在进行请求转发之前,已经提交了响应结果(如调用了response的flush或close方法),那么forward()方法会抛出IllegalStateException。为了避免该异常,不应该在源组件中提交响应结果。
1、如果目标组件为Servlet或JSP,就执行它们,并把它们产生的响应正文添加到源组件的响应结果中;如果目标组件为HTML文档,就直接把文档的内容添加到源组件的响应结果中。
2、返回到源组件的服务方法中,继续执行后续代码块。
特点:
1、源组件与被包含的目标组件的输出数据都会被添加到响应结果中。
2、在目标组件中对响应状态代码或者响应头所做的修改都会被忽略。
ServletRequest8.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示请求包含
public class ServletRequest8 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
RequestDispatcher rd = request.getRequestDispatcher("ServletRequest9") ;
rd.include(request, response) ;
String name = (String) request.getAttribute("name" ) ;
System.out.println(name);
response.getWriter().write("你好") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletRequest9.java
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 ServletRequest9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
request.setAttribute("name", "令狐冲") ;
response.getWriter().write("中国") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0900httpServletRequest/servlet/ServletRequest8,页面返回的结果是:
同时,服务器也打印出了
1、web应用范围内的共享数据作为ServeltContext对象的属性而存在(setAttribute),只要共享ServletContext对象也就共享了其数据。
2、请求范围内的共享数据作为ServletRequest对象的属性而存在(setAttribute),只要共享ServletRequest对象也就共享了其数据。
重定向机制的运作流程
1、用户在浏览器端输入特定URL,请求访问服务器端的某个组件
2、服务器端的组件返回一个状态码为302的响应结果。
3、当浏览器端接收到这种响应结果后,再立即自动请求访问另一个web组件
4、浏览器端接收到来自另一个web组件的响应结果。
HttpServeltResponse的sendRedirect(String location)用于重定向
特点
a. Servlet源组件生成的响应结果不会被发送到客户端。response.sendRedirect(String location)方法一律返回状态码为302的响应结果。
b. 如果源组件在进行重定向之前,已经提交了响应结果,会抛出IllegalStateException。为了避免异常,不应该在源组件中提交响应结果。
c. 在Servlet源组件重定向语句后面的代码也会执行。
d. 源组件和目标组件不共享同一个ServletRequest对象。
e. 对于sendRedirect(String location)方法的参数,如果以“/”开头,表示相对于当前服务器根路径的URL。以“http"//”开头,表示一个完整路径。
f. 目标组件不必是同一服务器上的同一个web应用的组件,它可以是任意一个有效网页。
请求转发和请求重定向的区别:
会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话。
每个用户在使用浏览器与服务器进行会话的过程中,不可避免各自会产生一些数据,程序要想办法为每个用户保存这些数据。
例如:用户点击超链接通过一个servlet购买了一个商品,程序应该想办法保存用户购买的商品,以便于用户点结帐servlet时,结帐servlet可以得到用户购买的商品为用户结帐。
思考:用户购买的商品保存在request或servletContext中行不行?
Cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去。这样,web资源处理的就是用户各自的数据了。
Session是服务器端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的HttpSession对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务。
javax.servlet.http.Cookie类用于创建一个Cookie,response接口中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。 同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。
Cookie类的方法:
public Cookie(String name,String value)
setValue与getValue方法
setMaxAge与getMaxAge方法 (秒)
setPath与getPath方法
setDomain与getDomain方法
getName方法
1、一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。
2、一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。
3、浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
4、如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。
5、注意,删除cookie时,path必须一致,否则不会删除
6、浏览器到底带不带Cookie,谁说了算呢?
浏览器到底带不带Cookie是由浏览器说了算。
浏览器通过判断 你在地址栏中敲入的资源地址. starWith(在硬盘上存储的Cookie里面存储的路径) 为true ,那就带,否则就不带.
实验:/day0901cookie 工程架构:
配置文件web.xml内容如下:
ServletCookie1
com.heima.cookie.ServletCookie1
ServletCookie2
com.heima.cookie.ServletCookie2
ServletDemo1
com.heima.cookie1.ServletDemo1
ServletCookie3
one.ServletCookie3
ServletCookie4
one.ServletCookie4
MainServlet
one.MainServlet
ShowAllBookServlet
two.servlet.ShowAllBookServlet
ShowDetailInfoServlet
two.servlet.ShowDetailInfoServlet
ServletCookie1
/servlet/ServletCookie1
ServletCookie2
/servlet/ServletCookie2
ServletDemo1
/ServletDemo1
ServletCookie3
/servlet/ServletCookie3
ServletCookie4
/servlet/ServletCookie4
MainServlet
/servlet/MainServlet
ShowAllBookServlet
/servlet/ShowAllBookServlet
ShowDetailInfoServlet
/servlet/ShowDetailInfoServlet
index.jsp
ServletCookie1.java
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示记录上次访问的时间
public class ServletCookie1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
out.write("你上次访问的时间是: " ) ;
//获取浏览器携带的Cookie
Cookie[] cs = request.getCookies() ;
//循环判断
for (int i = 0; cs !=null && i < cs.length; i++) {
Cookie c = cs[i] ;
if(c.getName().equals("lastaccesstime")){
//找到了存储上次访问时间的Cookie
String time = c.getValue() ;
//转换成long
long t = Long.parseLong(time) ;
//采用SimpleDateformat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") ;
String s = sdf.format(new Date(t)) ;
out.write(s) ;
out.write("清空Cookie") ;
break ;
}
}
//创建一个Cookie对象
Cookie cookie = new Cookie("lastaccesstime",new Date().getTime() + "") ;
//设置存活时间,一旦设置存活时间之后,那么Cookie将会存储在客户端的硬盘上
cookie.setMaxAge(Integer.MAX_VALUE) ;
//设置携带Cookie的路径
cookie.setPath(request.getContextPath()) ;
//cookie.setPath("/") ; //表示服务器根路径,所以访问其他工程时,浏览器也带此Cookie
//发送到客户端
response.addCookie(cookie) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletCookie2.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示删除Cookie
public class ServletCookie2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//新建一个Cookie,设置生命周期为0,立刻失效
Cookie c = new Cookie("lastaccesstime","") ;
c.setMaxAge(0) ;
response.addCookie(c) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第一次在浏览器中输入:http://localhost:8080/day0901cookie/servlet/ServletCookie1,得到如下结果:
浏览器和服务器的信息头文件的内容如下:观察没有cookie产生
第二次输入:http://localhost:8080/day0901cookie/servlet/ServletCookie1,页面产生了时间的信息,cookie生成
查看信息头,显示cookie内容
从浏览器的Internet选项里点击设置选项,弹出网站数据设置框,点击查看文件,查看cookie文件,
文件夹显示输入工程路径后生成的cookie文件
打开文件后查看cookie内容
内容说明如下:
实验二、记住登录用户名
ServletCookie3.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//记住用户名
/**
* 产生一个登陆页面
* @author Administrator
*
*/
public class ServletCookie3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
String username = "" ;
String pass = "" ;
//拿到浏览器携带的Cookie
Cookie[] cs = request.getCookies() ;
for (int i = 0; cs != null && i < cs.length; i++) {
Cookie c = cs[i] ;
if(c.getName().equals("username")){
//找到了存储用户名的Cookie
username = c.getValue() ;
}
if(c.getName().equals("pass")){
//找到了存储密码的Cookie
pass = c.getValue() ;
}
}
//拿取错误信息
String error = (String) request.getAttribute("error") ;
if(error != null)
out.write(error) ;
//创建登陆页面
out.write("") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletCookie4.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 此类有两个功能:
* 1. 判断用户是否是合法用户
* 2. 发送Cookie
* */
public class ServletCookie4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
//用户名和密码的逆序相同就认为是合法用户
//拿到浏览器提交的数据
String username = request.getParameter("username") ;
String pass = request.getParameter("pass") ;
String remenber = request.getParameter("remenber") ;
//判断是否是合法用户
String pass1 = new StringBuffer(pass).reverse().toString() ;
if(username.equalsIgnoreCase(pass1)){
//说明是合法用户
//看是否要记录信息
Cookie c = new Cookie("username",username) ;
Cookie c1 = new Cookie("pass",pass) ;
if(remenber == null){
//说明要删除Cookie
c.setMaxAge(0) ;
c1.setMaxAge(0) ;
}else{
//记录信息
c.setMaxAge(2*7*24*3600) ;
c1.setMaxAge(2*7*24*3600) ;
}
c.setPath(request.getContextPath()) ;
c1.setPath(request.getContextPath()) ;
//发送Cookie
response.addCookie(c) ;
response.addCookie(c1) ;
request.getRequestDispatcher("MainServlet").forward(request, response) ;
}else{
request.setAttribute("error", "用户名或者密码错误") ;
request.getRequestDispatcher("ServletCookie3").forward(request, response) ;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
MainServlet.java
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 MainServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("欢迎进入主界面") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器输入:http://localhost:8080/day0901cookie/servlet/ServletCookie3,得到以下页面:
输入姓名:abcde,密码:edcba,点击checkbox对话框,点击登录: 得到以下画面:
如果在输入界面输入: 姓名:abcde,密码:sdasda,点击checkbox对话框,点击登录:
实验三、利用cookie实现浏览记录
工程架构如下:
Book.java
public class Book {
private String id ;
private String bookName ;
private String author ;
private float price ;
private String discription ;
public Book() {
}
public Book(String id, String bookName, String author, float price,
String discription) {
super();
this.id = id;
this.bookName = bookName;
this.author = author;
this.price = price;
this.discription = discription;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
@Override
public String toString() {
return "Book [id=" + id + ", bookName=" + bookName + ", author="
+ author + ", price=" + price + ", discription=" + discription
+ "]";
}
}
BookUtils.java
import java.util.HashMap;
import java.util.Map;
import two.bean.Book;
public class BookUtils {
public static Map map = new HashMap() ;
static{
map.put("1", new Book("1","葵花宝典","陈冠希",100,"欲练此功,必先练好java基础")) ;
map.put("2", new Book("2","金瓶梅","阿娇",80,"一本好书啊,。。。。。。。")) ;
map.put("3", new Book("3","水浒传","施耐庵",50,"3个女人和105个男人的故事")) ;
map.put("4", new Book("4","辟邪剑谱","安培晋三",70,"小日本的绝世神功")) ;
map.put("5", new Book("5","神雕侠侣","金庸",120,"一段感动天地的旷世绝恋")) ;
map.put("6", new Book("6","红楼梦","曹雪芹",40,"一群女人和一个男人的故事")) ;
map.put("7", new Book("7","韦小宝是怎么炼成的","屌丝",90,"羡慕啊。。。。。。。")) ;
}
//返回所有的书
public static Map getAllBook(){
return map ;
}
//返回根据id查找的书
public static Book findBookById(String id){
return map.get(id) ;
}
}
ShowDetailInfoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import two.bean.Book;
import two.utils.BookUtils;
/**
* 功能有两个:
* 1.显示书的详细信息
* 2.发送历史浏览记录
* @author Administrator
*
*/
public class ShowDetailInfoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
//显示书的详细信息
//拿到传递的参数名
String id = request.getParameter("id") ;
//获取书
Book book = BookUtils.findBookById(id) ;
//输出
out.write(book + "返回继续浏览") ;
//生成一个历史记录Cookie
String histroy = getHistory(request,id) ;
//创建Cookie
Cookie c = new Cookie("history", histroy) ;
c.setMaxAge(Integer.MAX_VALUE) ;
c.setPath(request.getContextPath()) ;
response.addCookie(c) ;
}
//生成历史记录的Cookie
/**
* 浏览器携带的Cookie 当前点击的id 需要形成的Id字符串
* 1. 无 1 1
* 2. 1 1 1
* 3. 1 2 2-1
* 4. 1-2 1 1-2
* 5 1-2 2 2-1
* 6 1-2 3 3-1-2
* 7 1-2-3 1 1-2-3
* 8 1-2-3 2 2-1-3
* 9 1-2-3 3 3-1-2
* 10 1-2-3 4 4-1-2
*/
private String getHistory(HttpServletRequest request,String id) {
Cookie history = null ;
Cookie[] cs = request.getCookies() ;
for (int i = 0; cs!=null && i < cs.length; i++) {
if(cs[i].getName().equals("history")){
//找到了历史记录的Cookie
history = cs[i] ;
break ;
}
}
//考虑情况1
if(history == null){
return id ;
}
//考虑情况2,3
String value = history.getValue() ;
if(value.length() == 1){
if(value.equals(id)){
//点击的就是存储的历史记录
return id ;
}else
return id + "-" + value ;
}
//考虑4,5,6
LinkedList list = new LinkedList(Arrays.asList(value.split("-"))) ;
if(value.length() == 3){
int index = list.indexOf(id) ;
if(index == -1){
//点击的是没有浏览过的
list.addFirst(id) ;
}else{
list.remove(index) ;
list.addFirst(id) ;
}
}
//考虑7,8,9,10
if(value.length() > 3){
int index = list.indexOf(id) ;
if(index == -1){
//点击的是没有浏览过的
list.removeLast() ;
list.addFirst(id) ;
}else{
list.remove(index) ;
list.addFirst(id) ;
}
}
//将list中的数据转换成需要的格式字符串
StringBuffer sb = new StringBuffer(list.get(0)) ;
for (int j = 1; j < list.size(); j++) {
sb.append("-" + list.get(j)) ;
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ShowAllBookServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import two.bean.Book;
import two.utils.BookUtils;
/**
* 功能;
* 1. 显示所有的书籍
* 2. 显示历史浏览记录
* @author Administrator
*
*/
public class ShowAllBookServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter() ;
//显示所有的书籍
out.write("本站有以下好书
") ;
Map map = BookUtils.getAllBook() ;
for (Map.Entry entry : map.entrySet()) {
Book b = entry.getValue() ;
out.write( b.getBookName() + "查看详细信息
") ;
}
out.write("
") ;
out.write("
") ;
out.write("
") ;
out.write("
") ;
//显示历史浏览记录: 记录浏览记录的最近的3条记录 假设记录的值的形式是1-2-3
Cookie[] cs = request.getCookies() ;
for (int i = 0; i < cs.length; i++) {
Cookie c = cs[i] ;
if(c.getName().equals("history")){
//找到了记录浏览记录的Cookie
out.write("您的浏览历史记录如下:
") ;
String s = c.getValue() ;
String[] ids = s.split("-") ;
for (String id : ids) {
//拿到对应的书
Book book = BookUtils.findBookById(id) ;
out.write(book.getBookName() + "
") ;
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0901cookie/servlet/ShowAllBookServlet。进入菜单栏界面,如下:
点击进入界面如下:
在点击完超链之后,页面随之会产生浏览历史记录:
资料下载