JSP
Servlet
网络路径@WebServlet("/ReadCookieServlet")
文章目录
Servlet拦截数据(自动配置)
<!--制作节点-->
<servlet>
<description></description>
<display-name>StudentServlet</display-name>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>nuc.wcy.servlet.StudentServlet</servlet-class>
</servlet>
<!-- 拦截节点 -->
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/StudentServlet</url-pattern>
</servlet-mapping>
1.编码问题
//1.修改请求对象编码
request.setCharacterEncoding("utf-8");
//2.1使用
//response.setCharacterEncoding("utf-8");//发的是utf-8,但浏览器会误解为GBK
//2.2
response.setContentType("text/html;charset=utf-8");
3.下载文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1.读取文件
//类加载器
//File file = new File("imgage/003.gif");
//类加载器
//System.out.println(file.getAbsolutePath());
//InputStream is = DownLoadServlet.class.getClassLoader().getResourceAsStream("imgage/003.gif");
//File file = new File("G:\\soft\\doc\\JavaEE\\day12web1\\WebContent\\imgage\\003.gif");
ServletContext application=getServletContext();
String realpath = application.getRealPath("imgage\\003.gif");
System.out.println(realpath);
FileInputStream fis = new FileInputStream(realpath);
//String filename =new String(file.getName().getBytes("utf-8"),"iso-8859-1");
String filename = URLEncoder.encode(file.getName(),"utf-8");
//4设置头(告诉浏览器我是一个文件
response.setHeader("content-disposition", "attachment;filename="+filename );
ServletOutputStream sos= response.getOutputStream();
byte[] buf = new byte[1024*4];
int len = 0;
while((len=fis.read(buf))!=-1) {
sos.write(buf,0,len);
}
}
4.接收和发送信息
<form action="/day12web1/LoginServlet" method="host">
用户名:<input type="text" name="username"/><br/>
密码: <input type="password" name="pwd"/>
<input type="submit" value="登录"/>
</form>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1.编码问题
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2.接收数据
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println("用户名:"+username+"密码:"+pwd);
//3.判断
if(username.equals("jojn")&&pwd.equals("8888")) {
//重定向
//response.sendRedirect("/day12web1/index.html");
RequestDispatcher dispatcher=request.getRequestDispatcher("/ListServlet");
dispatcher.forward(request, response);
return;
} else {
response.sendRedirect("/day12web1/login.html");
}
}
转发信息
//ListServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2.接收数据
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println("用户名:..."+username+"密码:"+pwd);
PrintWriter out=response.getWriter();
out.print("这是listServlet返回的数据");
}
5.路径问题
//写路径
response.sendRedirect(request.getServletContext().getContextPath()+"/index.html");
response.sendRedirect(request.getContextPath()+"/index.html");
//获取路径
String path = application.getRealPath("imgage\\003.jpg");
System.out.println(path);
//3.获取路径信息
String contextpath = application.getContextPath();
String contextpath1 = request.getContextPath();
System.out.println(contextpath1);
一.获取Servlet的相应
1.获取servlet相应
//1.获取Servlet
//1.1使用getServletContext();
ServletContext application = this.getServletContext();
System.out.println(application.hashCode());
//1.2使用ServletConfig的getServletContext
ServletContext application2 = getServletConfig().getServletContext();
System.out.println(application2.hashCode());
//1.3使用session获取
ServletContext application3 = request.getSession().getServletContext();
System.out.println(application3.hashCode());
//1.4使用request获取
ServletContext application4 = request.getServletContext();
System.out.println(application4.hashCode());
//4.当容器使用
application.setAttribute("welcome", "huanxing");
ServletContext application = request.getServletContext();
String welcome = (String)application.getAttribute("welcome");
System.out.println(welcome);
//Servlret3.java
package com.qf.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlret3
*/
@WebServlet("/Servlret3")
public class Servlret3 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Servlret3() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stu
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ServletContext application = request.getServletContext();
Integer count = (Integer) application.getAttribute("count");
if(count==null) {
count = 1;
application.setAttribute("count", count);
}else {
count++;
application.setAttribute("count", count);
}
PrintWriter out = response.getWriter();
out.write("你是第"+count+"次访问");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
二.Cookie(状态管理)
Cookie(复数形态Cookies),又称为“小甜饼”。类型为“小型文本文件”[1],指某些网站为了辨别用户身份而储存在用户本地终端(Client Side)上的数据(通常经过加密)
用途
因为[HTTP协议](https://zh.wikipedia.org/wiki/HTTP)是无状态的,即[服务器](https://zh.wikipedia.org/wiki/服务器)不知道用户上一次做了什么,这严重阻碍了[交互式Web应用程序](https://zh.wikipedia.org/wiki/交互式Web应用程序)的实现。在典型的网上购物场景中,用户浏览了几个页面,买了一盒饼干和两瓶饮料。最后结帐时,由于HTTP的无状态性,不通过额外的手段,服务器并不知道用户到底买了什么,所以Cookie就是用来绕开HTTP的无状态性的“额外手段”之一。服务器可以设置或读取Cookies中包含信息,借此维护用户跟服务器[会话](https://zh.wikipedia.org/wiki/会话_(计算机科学))中的状态。
在刚才的购物场景中,当用户选购了第一项商品,服务器在向用户发送网页的同时,还发送了一段Cookie,记录着那项商品的信息。当用户访问另一个页面,浏览器会把Cookie发送给服务器,于是服务器知道他之前选购了什么。用户继续选购饮料,服务器就在原来那段Cookie里追加新的商品信息。结帐时,服务器读取发送来的Cookie就行了
Cookie另一个典型的应用是当登录一个网站时,网站往往会请求用户输入用户名和密码,并且用户可以勾选“下次自动登录”。如果勾选了,那么下次访问同一网站时,用户会发现没输入用户名和密码就已经登录了。这正是因为前一次登录时,服务器发送了包含登录凭据(用户名加密码的某种[加密](https://zh.wikipedia.org/wiki/加密)形式)的Cookie到用户的硬盘上。第二次登录时,如果该Cookie尚未到期,浏览器会发送该Cookie,服务器验证凭据,于是不必输入用户名和密码就让用户登录了。
创建
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("欢迎访问我的小店");
//3.添加cookie
//Cookie myCookie = new Cookie("username", "xiaocang");
//3.0如果有中文,编码url编码
Cookie myCookie = new Cookie("username2",URLEncoder.encode("小白","utf-8"));
//3.1设置cookie的有效期
System.out.println(myCookie.getMaxAge()) ;
myCookie.setMaxAge(60*10);//10分钟的有效期
//3.2设置cookie的有效路径
//myCookie.setPath("/");
System.out.println(myCookie.getPath());
//4.把cookie加入到response
response.addCookie(myCookie);
//5.读取cookie的信息
System.out.println("..............读取cookie的内容...........");
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for (Cookie cookie :cookies) {
System.out.println(cookie.getName()+".........."+URLDecoder.decode(cookie.getValue(),"utf-8"));
}
}
}
读取
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
if(request.getCookies()!=null) {
for (Cookie cookie :request.getCookies()) {
System.out.println(cookie.getName()+".........."+URLDecoder.decode(cookie.getValue(),"utf-8"));
}
}
}
cookie的路径问题
cookie一般都是由于用户访问页面而创建,可并不是只有在这个cookie创建页面时才可以访问。
1.如何设置Cookie设置路径
通过Cookie的setPath方法设置路径
2.缺陷
-
Cookie会被附加在每个HTTP请求中,所以无形中增加了流量。
-
由于在HTTP请求中的Cookie是明文传递的,所以安全性成问题,除非用HTTPS。
-
Cookie的大小限制在4KB左右,对于复杂的存储需求来说是不够用的。
防治方法
Cookie的setHttpOnly(true)方法
三.状态管理-Session
1.什么是Session
在计算机科学领域来说,尤其是在网络领域,会话(session,Microsoft Windows 中文版译作工作阶段)是一种持久网络协议,在用户(或用户代理)端和服务器端之间创建关联,从而起到交换数据包的作用机制,session在网络协议(例如telnet或FTP)中是非常重要的部分。
在不包含会话层(例如UDP)或者是无法长时间驻留会话层(例如HTTP)的传输协议中,会话的维持需要依靠在传输数据中的高级别程序。例如,在浏览器和远程主机之间的HTTP传输中,HTTP cookie就会被用来包含一些相关的信息,例如session ID,参数和权限信息等。
2.如何获得Session
HttpSession session = request.getSession();//系统会自动创建cookie
System.out.println("sessionId:"+session.getId());
System.out.println("session创建时间:"+new Date(session.getCreationTime()).toLocaleString());
System.out.println("session最后一次访问时间:"+new Date(session.getLastAccessedTime()).toLocaleString());
System.out.println("session过时时间:"+session.getMaxInactiveInterval());
//3.向session存放数据
session.setAttribute("username" , "zhangsan");
3.接收Session
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String name = (String)session.getAttribute("username");
System.out.println(name);
}
4.自定义Session
Cookie cookie = new Cookie("JSESSIONID",session.getId());
cookie.setMaxAge(60*5);
cookie.setPath("/day13web1");
cookie.setHttpOnly(true);
response.addCookie(cookie);
5.退出登录
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.设置session失效
HttpSession session = request.getSession();
session.removeAttribute("username");//从session中移除
session.invalidate();
PrintWriter out = response.getWriter();
out.write("推出成功");
}
6.用户失效
1.设置时间
1 使用HttpSession的session.setMaxInactiveInterval(20*60);设置,单位秒
2 在WEB—IF的web.xml中配置,单位分
<session-config>
<session-timeout>20</session-timeout>
</session-config>
2.失效的几种方法:
1.超过设置的时间
2.主动调用invalidate方法
3.服务器主动或异常关闭
注意:浏览器关闭不会让Session失效
应用:
//UserServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1.读取cookie
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(Cookie cookie :cookies) {
if(cookie.getName().equals("userinfo")) {
String val = cookie.getValue();
String[] vals = val.split("#");
if(vals[0].equals("admin")&&vals[1].equals("8888")) {
HttpSession session=request.getSession();
session.setAttribute("username", vals[0]);
request.getRequestDispatcher("/day13web2/index.html").forward(request, response);
return;
}
}
}
}
response.sendRedirect("/day13web2/login.html");
}
//LoginServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub、
//1.乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2,获取数据
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("admin")&&password.equals("8888")) {
//3.获取session
HttpSession session = request.getSession();
session.setAttribute("username", username);
//4.创建
Cookie cookie = new Cookie("userinfo","admin#888");
cookie.setMaxAge(5*60);
cookie.setPath("/day13web2");
cookie.setHttpOnly(true);
response.addCookie(cookie);
//5重定向
response.sendRedirect("/day13web2/index.html");
return;
}else {
response.sendRedirect("/day13web2/login.html");
}
}
Web
四.过滤器
1.什么是过滤器
Filter在英文中是过滤器的意思,当然在此处的使用也是完美的切合了它的意思,我们使用filter的主要目的就是完成一个过滤的作用。可以在一个请求到达servlet之前,将其截取进行逻辑判断,然后决定是否放行到请求的servlet。也可以在一个response到达客户端之前,截取结果进行逻辑判断,然后决定是否允许返回给客户端。
2.如何编写
1.编写Java类实现Filter接口
2.重写doFile方法
3.设置拦截的url
3.过滤器的配置
注解式配置
在自定义的Filter类中使用注解 @WebFilter(“/*”)确定为全局规则
xml配置
//起名(导入文件)
<filter>
<filter-name>myfilter1</filter-name>
<filter-class>com.qf.filter.MyFilter1</filter-class>
</filter>
<filter>
<filter-name>myfilter2</filter-name>
<filter-class>com.qf.filter.MyFilter2</filter-class>
</filter>
//应用 (编写顺序)
<filter-mapping>
<filter-name>myfilter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>myfilter1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
filter的使用默认按照类名的字符串顺序来排
第一次访问时,把index.html读取发送欸浏览器,并在服务其中缓存一份
第二次访问时,由于服务器中已有一份,比对时间,如果时间一样直接返回304
![服务器缓存303](https://i-blog.csdnimg.cn/blog_migrate/8679c0ca05f51a3d66643cd0296f87e1.png)
控制从服务器缓存
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//控制器浏览器缓存(控制第一次不走浏览器缓存)
res.setDateHeader("Expires", -1);
res.setHeader("Cache-Control", "no-cache");//过期时间
res.setHeader("Pragma", "no-cache");//批注
System.out.println("jj");
//放行
chain.doFilter(req, res);
//控制器浏览器缓存(控制第一次不走浏览器缓存)
res.setDateHeader("Expires", System.currentTimeMillis()+20000);
res.setHeader("Cache-Control", "no-cache");//过期时间
res.setHeader("Pragma", "no-cache");//批注
System.out.println("yyy");
chain.doFilter(request, response);
压缩文件
五.监听器
package com.qf.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletRequestListener implements ServletRequestListener{
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
System.out.println("请求对象销毁了"+sre.getServletRequest().hashCode());
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
System.out.println("请求对象初始化了了"+sre.getServletRequest().hashCode());
}
}
package com.qf.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
public class MyServletRequestAttributeListener implements ServletRequestAttributeListener{
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
System.out.println("request对象中添加数据"+srae.getName()+"..."+srae.getValue());
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
System.out.println("request对象中移除数据"+srae.getName()+"..."+srae.getValue());
}
}