Servlet对象生命周期
Servlet对象什么时候生,什么时候死.
生命周期相关的三个方法, init,service,destroy
- init(ServletConfig config)Servlet对象的初始化方法,对象被创建的时候调用
- service(request,response)客户端访问一次,执行一次
- destory()Servlet对象销毁之前调用
- Servlet对象什么时候被创建
- Servlet默认第一次访问的时候,对象被创建
- Tomcat服务器启动的时候创建对象,需要修改web.xml (一般不配置)
优先级,数值越小,优先级越高
<load-on-startup>5</load-on-startup>
- Servlet对象什么时候被销毁
- 停止Tomcat服务器
- WEB项目从服务器移除
Servlet的Web.xml配置
<!--
Servlet的详细配置
-->
<servlet>
<!-- name,定义名字,随意-->
<servlet-name>path</servlet-name>
<!-- class 配置类的全名,反射-->
<servlet-class>com.itheima.servlet.PathServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- name 必须和上面name相同-->
<servlet-name>path</servlet-name>
<!-- url-pattern 配置的是浏览器访问的虚拟路径-->
<url-pattern>/path</url-pattern>
</servlet-mapping>
url-pattern的配置三种方法
-
完全匹配(常用)
/abc : 浏览器地址栏必须写 /abc
<url-pattern>/path</url-pattern>
-
目录匹配
/aaa/bbb/* : 浏览器地址栏可以写 /aaa/bbb/任意
-
后缀名匹配
*.abc : 浏览器地址栏可以写 任意.abc
注意:目录匹配和后缀名匹配不能同时使用
Tomcat的全局web.xml (了解)
tomcat目录中/conf/web.xml 是全局配置文件,所有的WEB项目都使用
自己的写web.xml只有你自己的项目使用
当全局配置web.xml和自己的web.xml冲突了,听自己的
会话窗口的超时时间设置为30分钟
<session-config>
<session-timeout>30</session-timeout>
</session-config>
获取WEB应用程序下任意资源的绝对路径
- 方法: String getRealPath(“资源相对路径”)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 获取ServletContext对象
* 父类的方法
* org.apache.catalina.core.ApplicationContextFacade实现接口ServletContext
*/
ServletContext context = getServletContext();
System.out.println(context);
//context对象,获取配置文件中的初始化参数
String value = context.getInitParameter("heima");
System.out.println(value);
//context对象,方法getRealPath获取任意资源的绝对路径
//获取web目录下的a.txt绝对路径
String aPath = context.getRealPath("a.txt");
System.out.println(aPath);
//获取web目下WEB-INF目录下的b.txt绝对路径
String bPath = context.getRealPath("WEB-INF/b.txt");
System.out.println(bPath);
//获取src目录下的c.txt绝对路径
String cPath = context.getRealPath("WEB-INF/classes/c.txt");
System.out.println(cPath);
//获取WEB03 module下的d.txt绝对路径,获取不到
}
域对象
ServletContext对象是一个容器,可以存储数据.
对象有个作用域问题,ServletContext作用域是整个WEB应用程序
- 向域对象存储数据: setAttribute(String key, Object value)
- 取出域对象数据: Object getAttribute(String key)
- 移除域对象数据: removeAttribute(String key)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 域对象的存储和取出
*/
ServletContext context = getServletContext();
//域对象存储数据,键值对
context.setAttribute("heima","java");
//取出域对象存储的键值对
Object value = context.getAttribute("heima");
System.out.println(value);
}
注解开发取代web.xml
@WebServlet,注解添加到自己定义的Servlet中的类声明上即可
注解的属性 urlPatterns,属性值就是浏览器的访问地址
@WebServlet(urlPatterns = "/test")
Response设置响应体
HTTP的响应体,就是页面的正文部分
-
getWriter() 返回值是打印流PrintWrite
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * response对象方法getWriter() * 打印流的响应体 * write() 使用字符串数据,没有差别, 输出是整数,查询编码表 * print() 无论是什么,原样打印 */ PrintWriter pw = response.getWriter(); pw.write(100); pw.print(100); }
-
响应中的中文乱码问题
产生乱码原因: 编码和解码不一致
//设置响应回去的编码为utf-8,不能写到过滤器中,担心响应图片回去的时候,引起问题 response.setContentType("text/html;charset=UTF-8");
-
getOutputStream() 返回字节输出流OutputStream
返回字节流,响应非文本类型的数据
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * response对象的方法getOutputStream,响应非文本类型的数据 */ //获取图片的绝对路径 String aFile = getServletContext().getRealPath("a.jpg"); FileInputStream fis = new FileInputStream(aFile); OutputStream out = response.getOutputStream(); int len = 0; byte[] bytes = new byte[1024]; while ((len = fis.read(bytes))!=-1){ out.write(bytes,0,len); } fis.close(); }
重定向
response.sendRedirect("/WEB03/servlet2");
转发的实现步骤
- request对象方法获取转发器 RequestDispatcher getRequestDispatcher(“转发地址”)返回值就是转发器
- 使用转发器对象的方法 forward
//获取转发器对象,传递转发的路径
RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");
//转发器方法
dispatcher.forward(request,response);
转发和重定向区别
转发:携带request,response域中的数据,跳转页面。
重定向:不携带数据,重新指向一个链接。
文件的下载
客户端浏览器从服务器下载文件
超链接,连接的地址是服务器端文件的路径
文件: 浏览器识别文件,不是下载,直接打开运行
浏览器不识别文件,直接下载
编写服务器端代码,告诉浏览器下载,不要打开
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 编写程序,通知浏览器请你下载,不要打开
* 指导浏览器干什么,响应头
* 浏览器下载是HTTP协议规定
*/
String agent = request.getHeader("User-Agent");
String filename="美女.jpg";
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
response.setHeader("Content-Disposition","attachment;filename="+filename);
String aFile = getServletContext().getRealPath("download/a.jpg");
FileInputStream fis = new FileInputStream(aFile);
OutputStream out = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes))!=-1){
out.write(bytes,0,len);
}
fis.close();
}
验证码案例
验证码的本质是个图片,图片里面是个随机生成字符串
String str =“abcdefABCDE1234567890”;
Random.nextInt( str.length() )产生整数随机数
str.charAt(索引)
<img src="/WEB03/code" onclick="fnChange()" id="code">
<script type="text/javascript">
function fnChange() {
/*
* 页面打开的时候,请求服务器资源/WEB03/code
* 点击图片js函数中,发了请求/WEB03/code
*
* 请求的资源没有变化,服务器端程序也没有变化
* 浏览器拿缓存吧
*
* 每次请求不一样就行,添加参数
*/
//点击图片,修改src的属性值
var code = document.getElementById("code");
var date = new Date().getTime();
code.src="/WEB03/code?a="+date;
}
</script>
Cookie中使用中文问题(扩展)
Cookie数据,值可以使用中文,建议不要使用中文
在Cookie使用中文,Tomcat低版本不支持,从Tomcat8开始支持中文
你好-> %AE%3A%CD
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "哈哈";
name = URLEncoder.encode(name,"utf-8");
System.out.println(name);
Cookie cookie = new Cookie("haha",name);
response.addCookie(cookie);
Cookie[] cookies = request.getCookies();
for (Cookie cookie2: cookies){
String value = URLDecoder.decode( cookie2.getValue(),"utf-8");
System.out.println(cookie2.getName()+"=="+value);
}
}
Cookie的生存时间
浏览器中Cookie是有生存时间,默认是当前会话.浏览器关闭,会话结束
设置生存时间,Cookie对象方法 setMaxAge(int 秒)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("heima","java");
cookie.setPath(request.getContextPath());
//设置生存时间
cookie.setMaxAge(60);
response.addCookie(cookie);
}
记录上一次的访问时间:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取客户端携带的Cookie
Cookie[] cookies = request.getCookies();
//获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
String time = sdf.format(new Date());
//判断数组
if (cookies==null){
//没有数据,第一次访问
response.getWriter().write("欢迎第一次访问");
//当前时间,存储到Cookie中
Cookie cookie = new Cookie("time",time);
cookie.setMaxAge(60*10);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}else {
//有数据,获取cookie中存储时间
for(Cookie cookie :cookies){
String key = cookie.getName();
String value = cookie.getValue();
response.getWriter().write("上次访问时间是:"+value);
Cookie cookie2 = new Cookie("time",time);
cookie2.setMaxAge(60*10);
cookie2.setPath(request.getContextPath());
response.addCookie(cookie2);
}
}
}
持久化Session对象
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("testSession","testSession");
//session方法,getId() 获取session对象的唯一编码,返回String
String id = session.getId();
System.out.println(id);
//id值,存储到Cookie中
Cookie cookie = new Cookie("JSESSIONID",id);
cookie.setMaxAge(60*10);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
session生命周期
session域对象生命时候生,什么时候销毁
- session对象什么时候创建
- request.getSession()方法,Cookie中id和服务器的id匹配不上就创建
- session对什么时候销毁
- 默认30分钟销毁, tomcat全局配置文件web.xml
- 调用方法session.invalidate();
- 关闭 (非正常关闭) 服务器
如何清空Cookie
- 覆盖的方式情况
- 保证同名键
- 保证相同的携带路径
- setMaxAge(0)
JSP九大内置对象
- request
- response
- ServletContext对象,在JSP写对象,只能写 application
- ServletConfig对象,在JSP写对象,只能写config
- session
- out
- page
- pageContext 最小域对象,作用范围是当前页面
- exception异常