Java Web,是用Java技术来解决相关web互联网领域的技术总和。web包括:web服务器和web客户端两部分。Java在客户端的应用有java applet不过现在使用的很少,Java在服务器端的应用非常的丰富,比如Servlet,JSP和第三方框架等等。Java技术对Web领域的发展注入了强大的动力。

基本信息

  • 外文名:java web

  • 归属于:互联网

  • 类型:技术

  • 分类:服务器

目录

1主要框架

2关于Java

折叠编辑本段主要框架

Java的Web框架虽然各不相同,但基本也都是遵循特定的路数的:使用Servlet或者Filter拦截请求,使用MVC的思想设计架构,使用约定,XML或 Annotation实现配置,运用Java面向对象的特点,面向抽象实现请求和响应的流程,支持Jsp,Freemarker,Velocity等视图。

折叠JSP优点:


Java EE标准,这意味着有很大的市场需求和更多的工作机会

上手快速并且相对容易

有大量可用的组件库

折叠JSP缺点:


大量的JSP标签

对REST和安全支持不好

没有一个统一的实现。既有SUN的实现,又有Apache的实现–MyFaces。

折叠SpringMVC优点:


对Spring MVC覆盖绑定(overriding binding)、验证(validation)等提供生命周期管理

与许多表示层技术/框架无缝集成:JSP/JSTL、Tiles、Velocity、FreeMarker、Excel、XSL、PDF 等

便于测试–归功于IoC

折叠SpringMVC缺点:


大量的XML配置文件

太过灵活–没有公共的父控制器

没有内置的Ajax支持

折叠Stripes优点:


不需要书写XML配置文件

良好的学习文档

社区成员很热心

折叠Stripes缺点:


社区比较小

不如其他的项目活跃

ActionBean里面的URL是硬编码的

折叠Struts2优点:


架构简单–易于扩展

标记库很容易利用FreeMarker或者Velocity来定制

基于控制器或

者基于页面的导航

折叠Struts2缺点:


文档组织得很差

对新特征过分关注

折叠Tapestry优点:


一旦学会它,将极大地提高生产率

HTML模板–对页面设计师非常有利

每出一个新版本,都会有大量的创新

折叠Tapestry缺点:


文档过于概念性,不够实用

学习曲线陡峭

发行周期长–每年都有较大的升级

折叠Wicket优点:


对Java开发者有利(不是Web开发者)

页面和显示绑定紧密

社区活跃–有来自创建者的支持

折叠Wicket缺点:


HTML模板和Java代码紧挨着

需要对OO有较好的理解

Wicket逻辑–什么都用Java搞定

1创建项目

File+New+Project创建新的项目

然后

下一步:右键New选择Module项目

下一步和之前一样改名字看看JDK版本

下一步选择刚创建的项目右键

选择Web版本点击OK

创建一个新包lib加入jar包

右键全部打开

然后配置服务器 选择第一个

点击加号

找到Tomcat Local选择

然后谷歌浏览器标识的的地方可以修改浏览器下面是储存位置还有配置

后面选择旁边的位置

点击加号点击下面第一个

然后点击Apply最后OK

接下来实现增删改查

数据库

#判断存在即删除数据库drop database if exists mydb;#创建数据库create database mydb;#使用数据库use mydb;#创建表create table t_user(uid int primary key auto_increment,username varchar(20),password varchar(20),phone varchar(11),address varchar(50));insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');select * from t_user where username=" />数据库连接代码

 */public class UserDao {//连接数据库的四大参数private String jdbcDriver="com.mysql.cj.jdbc.Driver";private String jdbcUrl="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&serverTimezone=UTC";private String jdbcUser="root";private String jdbcPwd="root";private Connection con=null;//数据库连接对象private PreparedStatement pstm=null;//预处理对象private ResultSet rs=null;//结果集对象private int row=0;//增删改受影响的行数

增删改查

/** * 根据用户名和密码完成数据库的登录查询 * @param username * @param password * @return 数据库中查询到的用户信息对象 */public User login(String username, String password){User login=null;try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="select * from t_user where username=? and password=?";pstm=con.prepareStatement(sql);pstm.setObject(1,username);pstm.setObject(2,password);rs=pstm.executeQuery();if(rs.next()){//从结果集中取出数据,封装到User对象中login=new User();login.setUid(rs.getInt("uid"));login.setUsername(rs.getString("username"));login.setPassword(rs.getString("password"));login.setPhone(rs.getString("phone"));login.setAddress(rs.getString("address"));}} catch (Exception e){e.printStackTrace();} finally {try{if(rs!=null){rs.close();}if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return login;}/** * 用户信息的注册,即数据库的添加操作 * @param user * @return */public int add(User user){try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="insert into t_user(username,password,phone,address) values(?,?,?,?)";pstm=con.prepareStatement(sql);pstm.setObject(1,user.getUsername());pstm.setObject(2,user.getPassword());pstm.setObject(3,user.getPhone());pstm.setObject(4,user.getAddress());row=pstm.executeUpdate();} catch (Exception e){e.printStackTrace();} finally {try{if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return row;}}
/** * 对应商品表的实体类 */public class Goods {private Integer gid;private String gname;private Double price;private String mark;public Integer getGid() {return gid;}public void setGid(Integer gid) {this.gid = gid;}public String getGname() {return gname;}public void setGname(String gname) {this.gname = gname;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}public String getMark() {return mark;}public void setMark(String mark) {this.mark = mark;}@Overridepublic String toString() {return "Goods{" +"gid=" + gid +", gname='" + gname + '\'' +", price=" + price +", mark='" + mark + '\'' +'}';}}
/** * 对应用户信息表的实体类 */public class User {private Integer uid;private String username;private String password;private String phone;private String address;public Integer getUid() {return uid;}public void setUid(Integer uid) {this.uid = uid;}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 getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User{" +"uid=" + uid +", username='" + username + '\'' +", password='" + password + '\'' +", phone='" + phone + '\'' +", address='" + address + '\'' +'}';}}
import com.chen.bean.Goods;import java.sql.*;import java.util.ArrayList;import java.util.List;/** * 用来完成t_goods表的JDBC操作 */public class GoodsDao {//连接数据库的四大参数private String jdbcDriver="com.mysql.cj.jdbc.Driver";private String jdbcUrl="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&serverTimezone=UTC";private String jdbcUser="root";private String jdbcPwd="root";private Connection con=null;//数据库连接对象private PreparedStatement pstm=null;//预处理对象private ResultSet rs=null;//结果集对象private int row=0;//增删改受影响的行数public List selectAll(){List goodsList=new ArrayList();try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="select * from t_goods";pstm=con.prepareStatement(sql);rs=pstm.executeQuery();while (rs.next()){//从结果集中获取数据,封装到Goods对象中Goods goods=new Goods();goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));//把当前行对应的对象存储到集合中goodsList.add(goods);}} catch (Exception e){e.printStackTrace();} finally {try{if(rs!=null){rs.close();}if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return goodsList;}public List seach(String keyword){List goodsList=new ArrayList();try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="select * from t_goods where gname like concat('%',?'%')";pstm=con.prepareStatement(sql);pstm.setObject(1,keyword);rs=pstm.executeQuery();while (rs.next()){//从结果集中获取数据,封装到Goods对象中Goods goods=new Goods();goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));//把当前行对应的对象存储到集合中goodsList.add(goods);}} catch (Exception e){e.printStackTrace();} finally {try{if(rs!=null){rs.close();}if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return goodsList;}public Goods selectById(int gid){Goods goods=null;try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="select * from t_goods where gid=?";pstm=con.prepareStatement(sql);pstm.setObject(1,gid);rs=pstm.executeQuery();if (rs.next()){//从结果集中获取数据,封装到Goods对象中goods=new Goods();goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));}} catch (Exception e){e.printStackTrace();} finally {try{if(rs!=null){rs.close();}if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return goods;}public int add(Goods goods){try{Class.forName(jdbcDriver);con=DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="insert into t_goods(gname,price,mark) values(?,?,?)";pstm=con.prepareStatement(sql);pstm.setObject(1,goods.getGname());pstm.setObject(2,goods.getPrice());pstm.setObject(3,goods.getMark());row=pstm.executeUpdate();} catch (Exception e){e.printStackTrace();} finally {try{if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return row;}public int deleteById(int gid){try{Class.forName(jdbcDriver);con=DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql="delete from t_goods where gid=?";pstm=con.prepareStatement(sql);pstm.setObject(1,gid);row=pstm.executeUpdate();} catch (Exception e){e.printStackTrace();} finally {try{if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return row;}public int update(Goods goods){Goods tow=null;try{Class.forName(jdbcDriver);con= DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPwd);String sql = "update t_goods set gname=?,price=?,mark=? where gid = ?";pstm=con.prepareStatement(sql);rs=pstm.executeQuery();if (rs.next()){//从结果集中获取数据,封装到Goods对象中goods=new Goods();goods.setGid(rs.getInt("gid"));goods.setGname(rs.getString("gname"));goods.setPrice(rs.getDouble("price"));goods.setMark(rs.getString("mark"));}} catch (Exception e){e.printStackTrace();} finally {try{if(rs!=null){rs.close();}if(pstm!=null){pstm.close();}if(con!=null){con.close();}} catch (Exception e){e.printStackTrace();}}return tow.getGid();}}
import com.chen.bean.User;import com.chen.dao.UserDao;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.util.List;@WebServlet("/login")public class Login extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.设置请求和响应的编码格式,以及响应的格式request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文response.setCharacterEncoding("utf-8"); //设置响应的编码格式//2.获取请求的参数String username = request.getParameter("username");//根据表单的name属性获取用户输入的值String password = request.getParameter("password");System.out.println(username);System.out.println(password);//3.执行业务处理---jdbc操作UserDao userDao=new UserDao();User login = userDao.login(username, password);System.out.println(login);//4.判断登录的用户信息是否为空if(login!=null){//把用户信息存储到session中HttpSession session = request.getSession();session.setAttribute("user",login);//登录成功,当前servlet的业务处理完毕----后续执行查询商品的操作应该由别人来完成---请求转发给别的servlet处理request.getRequestDispatcher("selectAllGoods").forward(request,response);//请求别的地址} else{//登录失败,跳转到错误页request.setAttribute("error_msg","用户名或密码错误!");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
import com.chen.bean.User;import com.chen.dao.UserDao;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;//设置当前类用来处理 /register 的请求@WebServlet("/register")public class Register extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.设置编码request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//2.获取请求参数String username=request.getParameter("username");String password=request.getParameter("password");String phone=request.getParameter("phone");String address=request.getParameter("address");//封装:把上面所有的变量装载到User对象中User user=new User();user.setUsername(username);user.setPassword(password);user.setPhone(phone);user.setAddress(address);System.out.println(user);//3.执行业务处理---jdbc的操作UserDao userDao=new UserDao();int row=userDao.add(user);//4.做出响应if(row>0){//注册成功跳转到登录页response.sendRedirect("login.jsp");} else{//注册失败继续跳转回注册页request.setAttribute("error_msg","注册出现了一些问题,稍后再试!");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
import com.chen.bean.Goods;import com.chen.dao.GoodsDao;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.util.List;@WebServlet("/selectAllGoods")public class SelectAllGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//查询所有商品信息GoodsDao goodsDao=new GoodsDao();List goodsList = goodsDao.selectAll();//把数据传递到前端页面//通过request获取session对象,该对象可以向前端传输数据的容器HttpSession session = request.getSession();//向session中存入商品信息集合session.setAttribute("goodsList",goodsList);//登录成功,跳转到主页response.sendRedirect("zhuye.jsp");//指定跳转的页面}}
import com.chen.bean.Goods;import com.chen.dao.GoodsDao;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/addGoods")public class AddGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获取请求参数并封装到Goods对象中Goods goods=new Goods();goods.setGname(request.getParameter("gname"));//使用Double包装类把request.getParameter获取到字符串数字 转换为 double类型的数据goods.setPrice(Double.parseDouble(request.getParameter("price")));goods.setMark(request.getParameter("mark"));//执行JDBC的添加操作GoodsDao goodsDao=new GoodsDao();int row = goodsDao.add(goods);if(row>0){//添加成功,请求selectAllGoods地址,执行对应的Servlet(查询商品信息、存入session中、跳转到主页)request.getRequestDispatcher("selectAllGoods").forward(request,response);} else{request.setAttribute("error_msg","添加商品出错啦!");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
import com.chen.dao.GoodsDao;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/dell")public class DellGoods extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取要删除的商品idint gid=Integer.parseInt(request.getParameter("gid"));//执行JDBC根据gid删除操作GoodsDao goodsDao=new GoodsDao();int row = goodsDao.deleteById(gid);if(row>0){request.getRequestDispatcher("selectAllGoods").forward(request,response);} else{request.setAttribute("error_msg","删除出现了异常!");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
import com.chen.bean.Goods;import com.chen.dao.GoodsDao;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/findById")public class FindGoodsById extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int gid=Integer.parseInt(request.getParameter("gid"));//根据gid查询该商品信息GoodsDao goodsDao=new GoodsDao();Goods goods = goodsDao.selectById(gid);if(goods!=null){//把数据存储到request域对象中,然后请求转发到页面request.setAttribute("goods",goods);request.getRequestDispatcher("showGoods.jsp").forward(request,response);} else{//登录失败,跳转到错误页request.setAttribute("error_msg","修改出现异常");request.getRequestDispatcher("error.jsp").forward(request,response);}}}
import com.chen.bean.Goods;import com.chen.dao.GoodsDao;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.awt.*;import java.io.IOException;import java.util.List;public class seach extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");//设置请求的编码格式为中文response.setCharacterEncoding("utf-8"); //设置响应的编码格式//根据用户输入的搜索关键词String keyword=request.getParameter("keyword");System.out.println(keyword);//根据关键词执行jdbc的模糊查询GoodsDao goodsDao=new GoodsDao();List goodsList = goodsDao.seach(keyword);//向session中存入模糊查询到的商品信息集合HttpSession session=request.getSession();session.setAttribute("goodsList",goodsList);//登录成功,跳转到主页response.sendRedirect("zhuye.jsp");//指定跳转页面}}
import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/test01")public class Test01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//作用域对象//1.pageContext--(页面级作用域)//2.request--(请求间作用域)request.setAttribute("name","request");//3.session--(会话间作用域)用户使用同一个浏览器在任何页面都可以共享sessionHttpSession session = request.getSession();session.setAttribute("name","session");//4.application--(服务器级作用域)ServletContext application = request.getServletContext();application.setAttribute("name","application");//重定向---让浏览器重新请求test01.jspresponse.sendRedirect("test01.jsp"); //session//请求转发---浏览器当前的请求还没断开,还是同一次请求//request.getRequestDispatcher("test01.jsp").forward(request,response);//request}}
import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;@WebServlet("/test01")public class Test01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//作用域对象//1.pageContext--(页面级作用域)//2.request--(请求间作用域)request.setAttribute("name","request");//3.session--(会话间作用域)用户使用同一个浏览器在任何页面都可以共享sessionHttpSession session = request.getSession();session.setAttribute("name","session");//4.application--(服务器级作用域)ServletContext application = request.getServletContext();application.setAttribute("name","application");//重定向---让浏览器重新请求test01.jspresponse.sendRedirect("test01.jsp"); //session//请求转发---浏览器当前的请求还没断开,还是同一次请求//request.getRequestDispatcher("test01.jsp").forward(request,response);//request}}
登录

登录

账号:
密码:
没有账号?请注册
第一个Web项目

欢迎学习Java Web!

去登录
注册页

进行注册

账号:
密码:
电话:
地址:
已有账号?请登录
主页

欢迎来自${user.address}的${user.username}访问项目主页

添加商品
商品编号商品名称商品价格商品说明操作
${goods.gid}${goods.gname}${goods.price}${goods.mark}修改删除

一、Filter过滤器简介

Filter也称之为过滤器,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。

Filter 过滤器它是 JavaWeb 的三大组件之一。三大组件分别是:Servlet 程序、Listener 监听器、Filter

过滤器

Filter 过滤器它是 JavaEE 的规范。也就是接口

Filter 过滤器它的作用是:拦截请求,过滤响应。

二、Filter拦截原理

Filter接口中有一个doFilter方法,当我们编写好Filter,并配置对哪个web资源进行拦截后,WEB服务器每次在调用web资源的service方法之前,都会先调用一下filter的doFilter方法。web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法。调用filterChian对象的doFilter方法,web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。相反,如果不调用该方法,web资源不会被访问。

三、创建Filter步骤

创建Filter必须实现Filter接口,实现Filter接口必须重写三个方法:

(1)过滤器初始化:init(FilterConfig filterConfig)

(2)重写doFilter(ServletRequest req, ServletResponse resp, FilterChain

filterChain);Filter中的doFilter()方法主要写实现过滤器功能的代码,doFillter方法中可以一句需求决定是否调用filterChain的doFilter方法放行

(3)注销过滤器:destroy()

除此之外,需要在xml文件中配置需要过滤的web资源。

Filter开发步骤:

(1)导入相关依赖包

javax.servlet

servlet-api

2.5

javax.servlet.jsp

javax.servlet.jsp-api

2.3.3

javax.servlet.jsp.jstl

jstl-api

1.2

taglibs

standard

1.1.2

mysql

mysql-connector-java

5.1.47

(2)编写过滤器

实现Filter接口(注意导包不要导错!)javax.servlet包下的Filter,实现对应的方法即可

public class CharacterEncodingFilter implements Filter {

//初始化:web服务器启动就初始化了

public class CharacterEncodingFilter implements Filter {

//初始化:web服务器启动就初始化了

public void init(FilterConfig filterConfig) throws ServletException {

System.out.println("CharacterEncodingFilter初始化");

}

/*

- 1.过滤中的所有代码,在过滤特定请求的时候都会执行

- 2.必须要让过滤器继续前行

- chain.doFilter(request,response);

- */

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

//在这里统一处理编码问题

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

System.out.println("CharacterEncodingFilter执行之前");

chain.doFilter(request,response);//让我们的请求继续走,如果不写,程序到这里就会被拦截停止!

System.out.println("CharacterEncodingFilter执行之后");

}

//销毁:web服务器关闭的时候,过滤会销毁

public void destroy() {

System.out.println("CharacterEncodingFilter销毁");

}

}

public void destroy() {

System.out.println("CharacterEncodingFilter销毁");

}

}

(3)在web.xml配置Filter

charset

com.xiaoyao.filter.CharacterEncodingFilter

charset

/servlet/*

四、Filter的生命周期

Filter的创建和销毁由WEB服务器负责。web应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作,filter对象只会创建一次,init方法也只会执行一次。过滤器的注销会随着服务器的关闭而关闭。除此之外,Web容器还可以通过调用destroy方法销毁Filter。destroy方法在Filter的生命周期中仅执行一次。在destroy方法中,可以释放过滤器使用的资源。

Filter 的生命周期包含几个方法:

(1)构造器方法

(2)**init 初始化方法:**第 1,2 步,在 web 工程启动的时候执行(Filter 已经创建)

(3)**doFilter 过滤方法:**第 3 步,每次拦截到请求,就会执行(访问 admin 目录下的 a.jsp

页面,访问一次,拦截一次请求)

(4)**destroy 销毁:**第 4 步,停止 web 工程的时候,就会执行(停止 web 工程,也会销毁 Filter 过滤器)

有些不足还需改善!望海涵!