1、servlet
1.ServletContext
1.共享数据源
1.先写两个javaweb程序,一个
set
一个get
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// this.getInitParameter(); 从配置文件中获取初始化参数
// this.getServletConfig(); 从配置文件中获取这个servlet配置
// this.getServletContext(); servlet上下文 ,中间商--->**重点讲这个**
/*
web容器在启动的时候,他会为每个web程序都创建一个对应的ServletContext对象,他代表了当前的web应用
1.共享数据源
我在这个servlet中保存的数据,可以在另一个servlet中拿到;
*/
//保存(设置)数据
ServletContext context = this.getServletContext();
String username = "孔继浩";
context.setAttribute("username",username);
//向ServletContext 中存入数据,以方便下一个servlet获取相应的数据,避免用户重复输入数据
//ServletContext,就相当于中间的一个存储容器,他在所有的servlet之上
System.out.println("Hello servletContext!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//请求数据
ServletContext context = this.getServletContext();
//此处因为和HelloServlet一样都是this.getServletContext()得到的context,所以里面的数据是一样的
String username = (String) context.getAttribute("username");
//这里必须要进行强转,因为返回的是Object类型
//response响应回来的数据要进行文本格式及编码格式的设置
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
writer.print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.atkong.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>com.atkong.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
</web-app>
2.获取初始化参数
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.atkong.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//读取默认参数配置
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.请求转发
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.atkong.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入到了ServletDemo04...");
//请求重定向---》1
// RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
// requestDispatcher.forward(req,resp);//调用forward(req,resp)实现请求或转发
//请求重定向---》2
context.getRequestDispatcher("/gp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4.读取资源文件
Properties
- 在java目录下新建properties
- 在resource目录下新建properties
发现:都被打包到了同一路径下:/WEB-INF/classes/db.properties,我们俗称这个路径为classpath
思路:需要一个文件流:。。。。
username=root
password=123456
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>com.atkong.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("username");
String pwd = prop.getProperty("password");
resp.getWriter().print(user+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
**注意:**在这里模拟了properties文件(配置文件)Maven导出失败的例子,即在java目录下创建properties文件Maven不会自动导出,此时需要在servlet02项目下的pom.xml文件中build代码块中配置如下语句:
<!--在build中配置resource,来防止我们资源导出失败,
因为有时候XML文件可能导出失败,所以建议每次创建maven都加上-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
2.HttpServletResponse
response 向web端写出数据:resp.getWriter();resp.getOutputStream();
1.response文件下载
<servlet>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.kong.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取下载路径
// String realPath = this.getServletContext().getRealPath("/src/resources/1.jpg");
String realPath = "E:\\IDEA 2019.3.2\\Code\\JavaWeb\\javaweb-02-maven\\response\\src\\main\\resources\\企鹅.jpg";
System.out.println("下载文件的路径为"+realPath);
//2.下载的文件名是啥?--->此处用了一个巧妙地办法就是截取上面的真实路径的最后以“\”结尾的字符串即为该文件的文件名
//注意下面的截取格式!!!
String filename = realPath.substring(realPath.lastIndexOf("\\")+1);
// String filename = "BeautifulGirl";
//3.设置想办法让浏览器能够用支持下载我们需要的东西
//设置响应的消息头
//resp.setContentType("image/jpeg");
//设置响应类型中包括的文件附件-->设置web下载文件的一个头信息
resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取response的OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileOutputStream流写入到buffer缓冲区。并使用OutputStream将缓冲区的数据输出到客户端!
while ((len=in.read(buffer)) != -1){
out.write(buffer,0,len);
}
//8.关闭流资源。
out.close();
in.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.验证码功能
验证码怎么来的?–>意义不大
- 1.前端实现–>JS
- 2.后端实现,需要用到java的图片类,生产一个图片
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.kong.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
stringbuffer类:http://c.biancheng.net/view/852.html
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器每3秒刷新一下
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();//创建了一个“笔”
//设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);//将全部分图片背景填充为白色
//给图片写数据
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存的,所以不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999)+"";
//StringBuffer 类是可变字符串类,创建 StringBuffer 类的对象后可以随意修改字符串的内容。
// 每个 StringBuffer 类的对象都能够存储指定容量的字符串,如果字符串的长度超过了 StringBuffer 类对象的容量,
// 则该对象的容量会自动扩大。
StringBuffer sb = new StringBuffer();
//此处循环的作用是random生产随机数如果不是7位的,则少于7位的数将用0填充
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.实现响应重定
常见场景:
- 用户登录:
void sendRedirect(String var1) throws IOException;
测试:
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*原理:
resp.setHeader("Location","/r/image");
resp.setStatus(302);
*/
resp.sendRedirect("/r/image");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
请你聊聊重定向与转发的区别:
相同点:
- 页面都会实现跳转
不同点:
- 请求转发的时候url不会产生变化; 307
- 重定向时候,url地址栏会发生变化; 302
3.HttpServletRequest
HttpServletRequest:代表客户端的请求,用户通过http协议请求的访问服务器,http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
1.初试request:
public class Request extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("已进入请求....");
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向的时候一定要注意路径问题,否则就会404-->说明代码正确只是路径不对,500开头的说明服务器代码错误
resp.sendRedirect("/r/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>Request</servlet-name>
<servlet-class>com.kong.servlet.Request</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Request</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<%--index.jsp--%>
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}这句java代码代表的是当前的项目,之后请求当前项目下的login文件类--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
<%--success.jsp--%>
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2021/8/6
Time: 16:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Successful!</h1>
</body>
</html>
2.request应用:
-
1.获取前端传递的参数
-
2.请求转发
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.kong.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2021/8/7
Time: 12:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<h1 style="text-align: center ; color: purple" >欢迎登录!</h1>
<div style="text-align: center ; color: purple">
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:<input type="checkbox" name="hobbys" value="女孩"> 女孩
<input type="checkbox" name="hobbys" value="代码"> 代码
<input type="checkbox" name="hobbys" value="音乐"> 音乐
<input type="checkbox" name="hobbys" value="电影"> 电影
<br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2021/8/7
Time: 12:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>successful</title>
</head>
<body>
<h1 style="text-align: center; color:purple" >恭喜:登陆成功!</h1>
</body>
</html>
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//解决后台接受参数值的乱码问题
resp.setCharacterEncoding("utf-8");
//打印后台接受的参数值
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("==============================================");
System.out.println("账号密码:"+username+":"+password);
System.out.println("爱好:"+Arrays.toString(hobbys));
System.out.println("==============================================");
req.getRequestDispatcher("/success.jsp").forward(req,resp);//请求转发-->他和响应重定向在转发路径上有区别
/*
请求转发:不用写项目路径:直接写要转发到那个文件的路径即可;
响应重定:写项目路径和要转发到的文件的路径
*/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2、Cookie 、Session
2.1、会话(Session)
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这一过程可以称之为会话;
有状态会话:一个同学来过教师,下次再来教室,我们会知道这个同学,曾经来过。称之为有状态会话;
eg:你能怎么证明你是西部开源的学生?
你 西开
- 发票 西开给你发票
- 学校登记 西开标记你来过了
类比来:网站,怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件 客户端下次访问服务端带上信件就可以了;
2.服务器登记你来过了 下次你来的时候我来匹配你;
2.2、保存会话的两种技术
cookie:
- 客户端技术(响应,请求)
session:
- 服务器技术,利用这个技术可以保存用户的会话信息,我们可以把信息或者数据放在session中;
常见场景:网站登录后,你下次再登陆,第二次访问直接就上去了!
2.3、Cookie
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Yf2K7AtZ-1628657191415)(C:\Users\DELL\AppData\Roaming\Typora\typora-user-images\image-20210807231346808.png)]
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie
3.用到的cookie方法:
Cookie[] cookies = req.getCookies();//从服务器端获取cookies
cookie.getName();//获取cookie中的key
cookie.getValue()//获取cookie中的value
Cookie cookie = new Cookie();//新建一个cookie
cookie.setMaxAge(24*60*60);//设置cookie有效期为1天
resp.addCookie(cookie);//服务器端响应给客户端一个cookie
//cookie能保存下来信息是因为系统盘下存在cookie的一个缓存文件
<servlet>
<servlet-name>cookiedemo01</servlet-name>
<servlet-class>com.kong.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookiedemo01</servlet-name>
<url-pattern>/c1</url-pattern>
</servlet-mapping>
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器告诉你你来的时间,把这个时间封装成一个信件,你下次再来你把这个信带来,我就知道你来了
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
//响应输出对象
PrintWriter out = resp.getWriter();
//cookie,服务器端从客户端获取--->request-->cookie
Cookie[] cookies = req.getCookies();//这里返回数组,说明cookie可能存在多个
//判断cookie是否存在。。。
if (cookies != null){
out.print("您上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的name
if (cookie.getName().equals("LastLoginTime")){
//获取cookie的value
//解码:URLDecoder.decode
long LastLoginTime = Long.parseLong(URLDecoder.decode(cookie.getValue(),"UTF-8"));//将字符串转化为长整型时间戳
Date date = new Date(LastLoginTime);//再将长整型的数转化为日期类型
out.print(date.toLocaleString());//再以时间字符串的形式输出
}
}
}else{
out.print("这是您第一次访问本站...");
}
//服务器给客户端响应一个cookie
//编码 URLEncoder.encode
Cookie cookie = new Cookie("LastLoginTime", URLEncoder.encode(System.currentTimeMillis()+"","UTF-8"));
//设置cookie有效期为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
一个网站的cookie是否存在上限?
- 一个cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
- 300个cookie----浏览器存放上限
- cookie大小有限制:4kb
删除cookie:
- 1.不设置有效期,关闭浏览器自动失效
- 2.设置有效期时间为0
<servlet>
<servlet-name>cookiedemo02</servlet-name>
<servlet-class>com.kong.servlet.CookieDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookiedemo02</servlet-name>
<url-pattern>/c2</url-pattern>
</servlet-mapping>
public class CookieDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
Cookie cookie = new Cookie("lastlogintime",System.currentTimeMillis()+"");
//删除cookie-->将cookie有效期设置为0
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.4、Session(重点!!)
什么是Session:(session四大作用域之一)
- 服务器回个每一个用户(浏览器)创建一个对象;
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登录后,整个网站他都可以访问!—>保存用户信息、保存购物车信息等…这些长久需要保存的东西
Session和Cookie的区别:
-
Cookie是把用户的数据写给用户的浏览器,浏览器本地保存(可以保存多个)
-
Session是把用户的数据写到用户独占的Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
-
Session对象由服务器创建(服务器端的)
-
Cookie对象自己java代码中创建
Session使用场景:
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据,我们将它保存在Session中
使用Session:
<servlet>
<servlet-name>session01</servlet-name>
<servlet-class>com.kong.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session01</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
//从服务器得到一个session
HttpSession session = req.getSession();
//给session里存东西-->存放Object
session.setAttribute("name",new Person("孔继浩",1));
//获取session的ID
String id = session.getId();
//判断一个session是否是新创建的
if (session.isNew()){
resp.getWriter().print("session创建成功,Session的ID为:"+id);
}else{
resp.getWriter().print("session已经在服务器中存在了,Session的ID为:"+id);
}
//JSESSIONID=3FAEB15148DEEBD6BD09B26D4AF5F738-->cookie/session都一直有,而且session中的放在了cookie中
//session在创建的时候做了什么事情:
// Cookie cookie = new Cookie("JSESSIONID", id);
// resp.addCookie(cookie);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>session02</servlet-name>
<servlet-class>com.kong.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session02</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
//获取session中的值
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
//从服务器得到一个session
HttpSession session = req.getSession();
//获取session中的值
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
// resp.getWriter().print("Session的参数为:"+name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>session03</servlet-name>
<servlet-class>com.kong.servlet.SessionDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session03</servlet-name>
<url-pattern>/s3</url-pattern>
</servlet-mapping>
<!--设置session默认的失效时间-->
<session-config>
<!--15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
//注销session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从服务器得到一个session
HttpSession session = req.getSession();
//将session中的存的参数给移除
session.removeAttribute("name");
//手动注销session
//将session注销-->注销之后sessionID就没了,但是会立马生成一个新的(注销就相当于关闭了浏览器)
session.invalidate();
//服务默认注销session-->在web.xml文件下
//在做业务时手动注销与自动注销都要写,因为用户有需求
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
设置sessio会话自动过期:web.xml
<!--设置session默认的失效时间-->
<session-config>
<!--15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
3.JSP
3.1什么是JSP
4.MVC三层架构
MVC:model、view、controller 模型、视图、控制器
4.1、早些年
4.2 MVC三层架构
5.Filter(过滤器)
Filter:过滤器,用来过滤网站的数据
- 处理中文乱码
- 验证登录…
- 垃圾请求…
Filter开发步骤:两步:
-
1.导maven的jar包
-
2.编写过滤器:
1.导包(filter的包)
2.编写代码:
实现filter接口重写对应的方法
public class CharacterEncodingFilter implements Filter {
//初始化:
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter已经初始化...");
}
//过滤部分
//filterChain:过滤器的链--》放行作用
/*
1.过滤器中的所有代码,在过滤特定请求的时候都会被执行
2.必须要让过滤器通行
filterChain.doFilter(servletRequest,servletResponse);
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
System.out.println("CharacterEncodingFilter执行前....");
//让我们的请求继续走,如果不写,我们的程序到这里就被拦截停止了
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("CharacterEncodingFilter执行后....");
}
//销毁:
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁!");
}
}
3.在web.xml中配置过滤器
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kong.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern> <!--将servlet目录下的所有文件都过一遍过滤器-->
<!--<url-pattern>/*</url-pattern>--> <!--这样写不可取,因为耗费服务器资源太大-->
</filter-mapping>
6.监听器(Listener)
GUI编程中经常用,这里没学
7.JDBC复习
7.1、试验环境搭建
<!--连接数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
1.JDBC固定步骤:
-
加载驱动
-
连接数据库
-
向数据库发送SQL的对象Statement:CURD
-
编写SQL(根据业务,不同的SQL)
-
执行SQL(接收结果集)
-
关闭连接
事务:
2.Junit单元测试:
依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
import org.junit.Test;
public class Test01 {
@Test //一定要加上这个Test注解
public void hello(){
System.out.println("hello world!");
}
}
简单使用:
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!–>前提:导Junit包
运行成功:
运行失败:
8.文件上传
CSDN:
https://blog.csdn.net/Dream_6666/article/details/115875131
哔哩哔哩:遇见狂神说----javaweb
需要到导入jar包环境。------前提
UUID
9.邮件发送
哔哩哔哩:遇见狂神说----javaweb
环境:
csdn:
https://blog.csdn.net/qq_26709459/article/details/77809112?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162864873616780271549448%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162864873616780271549448&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-77809112.first_rank_v2_pc_rank_v29&utm_term=Java%E5%AE%9E%E7%8E%B0%E9%82%AE%E4%BB%B6%E5%8F%91%E9%80%81&spm=1018.2226.3001.4187
10.SSM
持久化:
容器思想:
springMVC:重点