[javaweb]重点总结大全
javaweb
web:网页
静态web:html,css 数据不会发生变化
动态web:servlet/jsp,asp,php每个人在不同的时间看到数据都不同
web应用程序编写完毕后,若想提供给外界访问,就需要一个服务器统一管理
静态web的缺点:
- web页面无法动态更新,所有的用户看到的都是同一个页面。
- 它无法和数据库交互,数据无法持久化。
1. web服务器
技术
asp:
- 微软:国内最早流行的asp;
- 在html中嵌入了vb的脚本,asp+com
- 在asp开发中,基本一个页面都有几千行的业务代码,页面极其混乱。
- 维护成本太高。
php:
- 开发速度很快,功能强大,跨平台,代码很简单。
- 无法承载大的访问量的情况
jsp/servlet:
- sun公司主推的B/S架构
- 基于java语言
- 可以承载三高问题带来的影响
服务器
用来处理请求和给用户一些响应信息。
-
lls:微软的
-
tomcat:Apache的,给初学者很友好。
2.tomcat
文件夹作用
bin目录下的startup启动tomcat
3.http
超文本传输协议,是一个简单的请求响应协议,运行在tcp之上。
- 文本:html,字符串……
- 超文本:图片,音乐,视频,定位,地图……
https:安全的连接
两个时代
-
http1.0
- 客户端与web服务器连接后,只获得一个web资源,断开连接
-
http2.0
- 客户端与服务端连接后,可以获取多个web资源。
请求响应
- 请求:客户端->发请求给服务器
- 响应:服务器->客户端响应信息
4.Maven
在javaweb中需要使用大量的jar包,我们手动去导入。由此maven诞生了。
它是一个项目架构管理工具。
-
1.下载安装,直接在官网下载即可
-
2.配置环境变量
-
3.配置镜像,可以提升下载jar包速度,在conf配置文件中的setting文件中配置
<mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors>
-
4.在setting中配置本地仓库
<localRepository>E:\browserDownloads\apache-maven-3.8.5\maven-repo</localRepository>
创建maven项目在idea中
5.servlet
sun公司提供两种实现类:
1.实现servlet接口
2.继承Httpservlet
- sun公司用来开发动态web的一门技术
- sun在这些API中提供了一个接口叫servlet,如果你想开发一个servlet程序,只需要完成两个小步骤。
- 编写一个类,实现servlet类接口
- 把开发好的java类部署到web服务器中
把实现了servlet接口的程序叫做servlet
创建一个helloservlet
导入maven依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.2-b01</version>
</dependency>
</dependencies>
敲一个servlet
package com.javaweb;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author panglili
* @create 2022-07-19-8:18
*/
public class HelloServlet extends HttpServlet {
//由于get和post只是请求的方式不一样,因此只需要实现一个,在另一个里面调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("******doget");
PrintWriter writer = resp.getWriter();
writer.print("hello,servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册在web上
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.javaweb.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
6.servletContext
web容器在启动的时候,会为每个web程序都创建一个servletcontext对象,代表当前web应用。全局唯一!
- 可以实现各个servlet之间的通信,统一的管理所有servlet的数据(一般不用此方法,增加浏览器负担)。
- servletcontext:调用servlet实现数据共享
测试一下:
(1)创建一个servlet使用context设置属性
package com.javaweb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-8:18
*/
public class HelloServlet extends HttpServlet {
//由于get和post只是请求的方式不一样,因此只需要实现一个,在另一个里面调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username="ssss";
context.setAttribute("username",username);
System.out.println("******doget");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)创建另一个servlet使用context获取属性值
package com.javaweb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-16:28
*/
public class getServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username =(String) context.getAttribute("username");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
resp.getWriter().print(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(3)然后配置servlet在web中就可以在网页访问了
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.javaweb.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.javaweb.servlet.getServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
(4)在网页请求getc可以拿到hello的属性值
- servletcontext获取web初始化参数
(1)web初始化数据
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
(2)servlet中获取
package com.javaweb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-17:02
*/
public class ServletDemo extends HttpServlet {
//由于get和post只是请求的方式不一样,因此只需要实现一个,在另一个里面调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
System.out.println("******doget");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(3)网页数据
- servletcontext:实现页面请求转发:
(1)写请求转发的servlet
此请求被转发到getIni
package com.javaweb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-17:02
*/
public class ServletDemo2 extends HttpServlet {
//由于get和post只是请求的方式不一样,因此只需要实现一个,在另一个里面调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/getIni").forward(req,resp);
System.out.println("******doget");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)web配置
请求demo2
<servlet>
<servlet-name>demo2</servlet-name>
<servlet-class>com.javaweb.servlet.ServletDemo2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo2</servlet-name>
<url-pattern>/demo2</url-pattern>
</servlet-mapping>
(3)网页实现
返回的是getIni数据
7.HttpServletResponse
web服务器接受到客户端的http请求之后,针对这个请求,分别创建一个代表请求的httpServletRequest和代表响应的HttpServletResponse
-
文件下载
package com.javaweb.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; /** * @author panglili * @create 2022-07-19-18:17 */ public class Response extends HelloServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取下载路径 String path="C:\\Users\\塔塔\\Pictures\\Camera Roll\\1.jpg"; //下载的文件名 String fileName = path.substring(path.lastIndexOf("\\") + 1); //设置想办法让浏览器支持下载需要的 resp.setHeader("Content-Disposition","attachment;fileName="+fileName); //获取下载文件的输入流 FileInputStream stream = new FileInputStream(path); //创建缓冲区 int len=0; byte[] buffer = new byte[1024]; //获取OutputStream ServletOutputStream out = resp.getOutputStream(); //将文件写到buffer缓冲区 while((len=stream.read(buffer))>0){ out.write(buffer,0,len); } //关闭流 stream.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
验证码实现
package com.javaweb.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* @author panglili
* @create 2022-07-19-18:39
*/
public class ImageServlet extends HelloServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//每三秒刷新一次
resp.setHeader("refresh","3");
//在内存创建一个图片
BufferedImage image=new BufferedImage(80,20,BufferedImage.TYPE_INT_BGR);
//得到图片
Graphics2D g=(Graphics2D)image.getGraphics();
//设置背景颜色
g.setColor(Color.red);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.BLACK);
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 str = new StringBuffer();
for (int i=0;i<7-num.length();i++){
str.append("0");
}
num=str.toString()+num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>img</servlet-name>
<servlet-class>com.javaweb.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>img</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
-
请求重定向
package com.javaweb.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author panglili * @create 2022-07-19-18:46 */ public class Redirect extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("/img"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<servlet> <servlet-name>redi</servlet-name> <servlet-class>com.javaweb.servlet.Redirect</servlet-class> </servlet> <servlet-mapping> <servlet-name>redi</servlet-name> <url-pattern>/redi</url-pattern> </servlet-mapping>
请求redi则会请求到img请求的页面
9.HttpServletrRequest
HttpServletRequest代表 客户端的请求,用户通过http协议访问服务器,http请求中的所有信息会被封装到HttpServletRequest中,通过它的方法就可以拿到所有的信息。
request获取前端传的数据
package com.javaweb.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-19:10
*/
public class Request extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String pwd = req.getParameter("pwd");
String[] hobbies = req.getParameterValues("hobby");
System.out.println("===========");
System.out.println(username);
System.out.println(pwd);
for(String s:hobbies){
System.out.println(s);
}
System.out.println("===========");
resp.sendRedirect("/success.jsp");
}
}
前端
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/19
Time: 16:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
<!--表单框架 -->
<form action="${pageContext.request.contextPath}/req" method="post">
<p>名字:<input type="text" name="username" value="默认初始值" maxlength="8"></p>
<p>密码:<input type="password" name="pwd"> </p>
<p>
性别:
<input type="radio" value="nan" name="sex">男
<input type="radio" value="nv" name="sex">女
</p>
<p>
爱好:
<input type="checkbox" value="sleep" name="hobby">睡觉
<input type="checkbox" value="sport" name="hobby">运动
<input type="checkbox" value="study" name="hobby">学习
</p>
<p>
下拉框
<select name="列表名称">
<option value="选项的值">印度</option>
<option value="选项的值">中国</option>
<option value="选项的值">朝鲜</option>
<option value="选项的值">美国</option>
<option value="选项的值">瑞士</option>
</select>
</p>
<p>
下拉框
<textarea name="textarea" cols="30" rows="50">文本neir</textarea>
</p>
<p>
文件域
<input type="file" name="files">
<input type="submit" value="上传" name="upload" >
</p>
<p>
<input type="submit">
<input type="reset">
</p>
</form>
</body>
</html>
10.cookie,session
会话:用户打开一个浏览器,点击了很多按钮,访问多个web资源,关闭浏览器,这个过程可以称为会话。
客户端 服务端
- 1.服务端给客户端一个信件,客户端下次访问服务器的时候带上信件就可以了;cookie
- 2.服务器登记你来过,下次来的时候我来匹配你;session
保存客户端信息的两种方式:
- cookie
- 客户端技术:请求和响应
- session
- 服务器端技术,保存客户端信息,把信息或者数据放在session中
package com.javaweb.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* @author panglili
* @create 2022-07-19-19:39
*/
public class Cookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();
javax.servlet.http.Cookie[] cookies = req.getCookies();
if(cookies!=null){
writer.write("time:");
for(int i=0;i<cookies.length;i++){
javax.servlet.http.Cookie cookie=cookies[i];
if(cookie.getName().equals("lastLoginTime")){
long lastLoginTime=Long.parseLong(cookie.getValue());
Date date = new Date(lastLoginTime);
System.out.println("*******");
writer.write(date.getDate());
writer.write(date.toLocaleString());
}
System.out.println("$$$$$$$$");
}
}else{
writer.write("first inter");
}
javax.servlet.http.Cookie cookie1;
cookie1 = new javax.servlet.http.Cookie("lastLoginTime", System.currentTimeMillis()+"");
//cookie1.setMaxAge(24*60*60);
resp.addCookie(cookie1);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
session实现:
- 服务器给每个用户创建一个session对象。
- 一个session独占一个浏览器,只要浏览器没关,session就可以存在
package com.javaweb.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-19-20:32
*/
public class Session 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;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//给session存值,可以通过其他session获取
session.setAttribute("name","heihe");
//获取session的id
String id = session.getId();
//判断是不是第一次创建
if(session.isNew()){
resp.getWriter().write("session创建成功"+id);
}else{
resp.getWriter().write("session已经存在"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>session</servlet-name>
<servlet-class>com.javaweb.servlet.Session</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session</servlet-name>
<url-pattern>/session</url-pattern>
</servlet-mapping>
<!--session失效时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
11.jsp
java server page:java服务器前端页面,和servlet一样,用于动态web开发。
特点:
- 写jsp页面就像在写html
- html只给用户提供静态数据,jsp中可以加入java代码,为用户提供动态数据
jsp最终会被转换成一个java类。jsp继承了一个HttpJspBase,这个类经常间接又继承了servlet,因为jsp的本质还是一个servlet。
但是通过继承使得jsp大大简化了,servlet与前端交互的语句。
- 在jsp中只要是java代码就会原封不动的输出;
·out.print(name);
- 如果是html代码就会进行转换为
out.write("success\r\n");
说到底,就相当于在后台用java语言的servlet给前端传输数据一样只不过它使用了前端化的语言使得操作更加简单,在运行的时候它本身还是转化成了java。
jsp语法
作为一个java语言的应用它支持所有的java语法,并且有许多自己的语法。
也可以用el表达式取值:${}等价于<%=%>
脚本片段:
<%
int sum=0;
for(int i=1;i<=100;i++){
sum+=i;
}
out.print("<h1>sum="+sum+"</h1>");
%>
<%! static {
System.out.println("loading^");
}
public void tata(){
System.out.println("sda");
}
%>
jsp指令
错误界面定制:
<%@ page errorPage="success.jsp" %>
包含其他页面:
<%@ include file=""%>
九大内置对象
- session //存值在一个session中
- request //存值在一次请求中
- application //存值在当前项目
- pageContext //存值当前页面
- Response
- config
- jspContext
- out //输出
- page
jsp标签,jstl标签,EL表达式
使用之前要先导包
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
el表达式:${ }
- 获取数据
- 执行运算
- 获取web开发的常用对象
jsp标签
<body>
<jsp:forward page="hello1.jsp">
<jsp:param name="name" value="tata"></jsp:param>
<jsp:param name="age" value="221"></jsp:param>
</jsp:forward>
</body>
jstl标签
弥补html标签的不足,它有许多自定义的标签
导入标签头才能使用该标签
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
在使用标签时遇到此问题
将jar包手动复制到tomcat服务器中
成功
核心标签
使用c开头
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/20
Time: 10:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="demo1.jsp" method="get">
name<input type="text" name="username" value="${param.username}">
<input type="submit" value="submit">
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="admin you are wercome"></c:out>
</c:if>
</form>
</body>
</html>
javaBean
- 必须有一个无参构造
- 属性私有
- 有对应的get、set
一般和数据库的表映射:字段映射属性!
表people
id | name | age |
---|---|---|
1 | tata | 18 |
2 | meigu | 17 |
@Data
public class people{
private int id;
private String name;
private int age;
}
三层架构
model view controller
视图,模型,控制器
早期历史
- servlet可以直接编辑crud,访问数据库,程序十分臃肿,不利于维护。
model:
- 业务处理:业务逻辑(server)
- 数据持久层:crud(dao)
view:
- 展示数据
- 提供连接发起servlet请求
controller:
-
接受用户请求:(req:请求参数,session信息)
-
交给业务层处理对应的代码
-
控制视图的跳转
12.过滤器
有一些信息不应该被处理,要被过滤的。
1.导包
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.2-b01</version>
</dependency>
2.继承过滤器的接口
package com.javaweb.controller;
import javax.servlet.*;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-20-20:32
*/
public class FilterDemo1 implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
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("****before:");
//让请求继续执行,如果不写请求到这里就会停止
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("####after:");
}
public void destroy() {
System.out.println("destory……");
}
}
3.写一个没有处理编码的请求
package com.javaweb.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author panglili
* @create 2022-07-20-8:26
*/
public class tets extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username="弄啥嘞~";
context.setAttribute("username",username);
resp.getWriter().write(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
此时还没有配置过滤器,看看网页效果
意料之中的乱码。
4.将过滤器注册到web配置
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.javaweb.controller.FilterDemo1</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/filter</url-pattern>
</filter-mapping>
5.经过过滤器的处理
13.监听器
1.配置监听器
package com.javaweb.controller;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.PushbackInputStream;
/**
* @author panglili
* @create 2022-07-20-21:03
*/
public class Listener implements HttpSessionListener {
//session创建
public void sessionCreated(HttpSessionEvent hE) {
ServletContext context = hE.getSession().getServletContext();
Integer o = (Integer)context.getAttribute("onlinecount");
if(o==null){
o=new Integer(1);
}else{
int count=o.intValue();
o=new Integer(count+1);
}
context.setAttribute("o",o);
}
public void sessionDestroyed(HttpSessionEvent hE) {
ServletContext context = hE.getSession().getServletContext();
Integer o = (Integer)context.getAttribute("onlinecount");
if(o==null){
o=new Integer(1);
}else{
int count=o.intValue();
o=new Integer(count+1);
}
context.setAttribute("o",o);
}
}
2.前台实现人数统计
<%--
Created by IntelliJ IDEA.
User: 塔塔
Date: 2022/7/20
Time: 21:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>people count:<%= getServletConfig().getServletContext().getAttribute("o")%>...</h1>
</body>
</html>
3.配置web
<listener>
<listener-class>com.javaweb.controller.Listener</listener-class>
</listener>