Java学习路线-49:Servlet过滤器Filter(2)

简介: Java学习路线-49:Servlet过滤器Filter

课时7 案例2:粗粒度权限管理

基于角色的权限控制RBAC

tb_user

tb_role

tb_userrole

tb_menu

tb_rolemenu

web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app>
    <servlet>
        <servlet-name>AServlet</servlet-name>
        <servlet-class>com.pengshiyu.servlet.AServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>AFilter</filter-name>
        <filter-class>com.pengshiyu.filter.AFilter</filter-class>
    </filter>
    <filter-mapping>
<!--        不能将过滤器设置在login.html上,不然没法登录了-->
        <filter-name>AFilter</filter-name>
        <url-pattern>/hello.html</url-pattern>
    </filter-mapping>
</web-app>

AServlet.java

package com.pengshiyu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("post: " + username);
        // 设置session
        request.getSession().setAttribute("username", username);
        // 跳转页面
        request.getRequestDispatcher("hello.html").forward(request, response);
    }
}

过滤器进行简单的权限校验

AFilter.java

package com.pengshiyu.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class AFilter implements Filter {
    private FilterConfig config;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse response, 
        FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        String username = (String) request.getSession().getAttribute("username");
        System.out.println("filter: " + username);
        if(username != null){
            // 放行
            filterChain.doFilter(request, response);
        } else{
            // 跳转到登录页
            request.getRequestDispatcher("login.html").forward(request, response);
        }
    }
    @Override
    public void destroy() {
    }
}

课时8 案例3:全站编码问题

// post编码
request.setCharacterEncoding("utf-8");
// get编码
String username = request.getParameter("username");
username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
// 响应编码
response.setContentType("text/html; charset=UTF-8");

HttpServletRequest装饰类

EncodingRequest.java

package com.pengshiyu.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.nio.charset.StandardCharsets;
// 装饰器
public class EncodingRequest extends HttpServletRequestWrapper {
    public EncodingRequest(HttpServletRequest request) {
        super(request);
    }
    @Override
    public String getParameter(String name) {
        // 处理编码问题
        String value = super.getParameter(name);
        value = new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        return value;
    }
}

过滤器AFilter.java

package com.pengshiyu.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class AFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String method = httpServletRequest.getMethod();
        // 设置响应编码
        response.setContentType("text/html; charset=UTF-8");
        if ("GET".equals(method)) {
            // 放行
            EncodingRequest encodingRequest = new EncodingRequest(httpServletRequest);
            filterChain.doFilter(encodingRequest, response);
        } else if ("POST".equals(method)) {
            request.setCharacterEncoding("utf-8");
            filterChain.doFilter(request, response);
        }
    }
    @Override
    public void destroy() {
    }
}

响应处理AServlet.java

package com.pengshiyu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
        System.out.println(request.getParameter("name"));
        response.getWriter().print("你好");
    }
}

web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app>
    <!-- 注册 Servlet,帮助web服务器反射该类 -->
    <servlet>
        <servlet-name>AServlet</servlet-name>
        <servlet-class>com.pengshiyu.servlet.AServlet</servlet-class>
    </servlet>
    <!-- 映射 Servlet 资源,用url-pattern元素标示 URL -->
    <servlet-mapping>
        <servlet-name>AServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>AFilter</filter-name>
        <filter-class>com.pengshiyu.filter.AFilter</filter-class>
    </filter>
    <filter-mapping>
<!--        不能将过滤器设置在login.html上,不然没法登录了-->
        <filter-name>AFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

课时9 案例4:页面静态化之准备工作(图书管理小项目)

功能:
查询所有
按分类查看
BookServlet
    findAll()       查询全部
    findByCategory() 按分类查询
BookService: 省略
BookDao:
    List<Book> findAll()
    List<Book> findByCategory()
Book:
    bid
    bname
    price
    category

静态化:

第一次访问从数据库取数据,保存到html中

第二次之后访问就直接从html中读取,不再从数据库中取数据

数据准备:

create table tb_book(
    bid int primary key auto_increment,
    bname varchar(50),
    price decimal(10, 2),
    category int
);
insert into tb_book(bname, price, category) values("Java", 12, 1);
insert into tb_book(bname, price, category) values("Python", 12, 1);
insert into tb_book(bname, price, category) values("JavaScript", 12, 1);
insert into tb_book(bname, price, category) values("Go", 12, 1);
insert into tb_book(bname, price, category) values("三国演义", 12, 2);
insert into tb_book(bname, price, category) values("西游记", 12, 2);
insert into tb_book(bname, price, category) values("水浒传", 12, 2);
insert into tb_book(bname, price, category) values("红楼梦", 12, 2);

创建对应的Book类

package com.pengshiyu.bean;
public class Book {
    private int bid;
    private String bname;
    private double price;
    private int category;
    public Book() {
    }
    public int getBid() {
        return bid;
    }
    public void setBid(int bid) {
        this.bid = bid;
    }
    public String getBname() {
        return bname;
    }
    public void setBname(String bname) {
        this.bname = bname;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getCategory() {
        return category;
    }
    public void setCategory(int category) {
        this.category = category;
    }
    @Override
    public String toString() {
        return "Book{" +
                "bid=" + bid +
                ", bname='" + bname + '\'' +
                ", price=" + price +
                ", category=" + category +
                '}';
    }
}

BookDao.java

package com.pengshiyu.dao;
import com.pengshiyu.bean.Book;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import util.TxQueryRunner;
import java.sql.SQLException;
import java.util.List;
public class BookDao {
    private QueryRunner qr = new TxQueryRunner();
    public  List<Book> findAll() {
        String sql = "select * from tb_book";
        try {
            List<Book> list = qr.query(sql, new BeanListHandler<Book>(Book.class));
            System.out.println(list);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public  List<Book> findByCategory(int category) {
        String sql = "select * from tb_book where category = ?";
        try {
            return qr.query(sql, new BeanListHandler<Book>(Book.class), category);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

BookServlet

package com.pengshiyu.servlet;
import com.pengshiyu.dao.BookDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class BookServlet extends BaseServlet {
    private BookDao bookDao = new BookDao();
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute("bookList", bookDao.findAll());
        request.getRequestDispatcher("book.jsp").forward(request, response);
    }
    public void findByCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int category = Integer.parseInt(request.getParameter("category"));
        request.setAttribute("bookList", bookDao.findByCategory(category));
        request.getRequestDispatcher("book.jsp").forward(request, response);
    }
}

用到的工具类 TxQueryRunner.java

package util;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
public class TxQueryRunner extends QueryRunner {
    @Override
    public int[] batch(String sql, Object[][] params) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        int[] result = super.batch(con, sql, params);
        JdbcUtil.releaseConnection(con);
        return result;
    }
    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
            throws SQLException {
        Connection con = JdbcUtil.getConnection();
        T result = super.query(con, sql, rsh, params);
        JdbcUtil.releaseConnection(con);
        return result;
    }
    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        T result = super.query(con, sql, rsh);
        JdbcUtil.releaseConnection(con);
        return result;
    }
    @Override
    public int update(String sql) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        int result = super.update(con, sql);
        JdbcUtil.releaseConnection(con);
        return result;
    }
    @Override
    public int update(String sql, Object param) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        int result = super.update(con, sql, param);
        JdbcUtil.releaseConnection(con);
        return result;
    }
    @Override
    public int update(String sql, Object... params) throws SQLException {
        Connection con = JdbcUtil.getConnection();
        int result = super.update(con, sql, params);
        JdbcUtil.releaseConnection(con);
        return result;
    }
}
相关文章
|
2月前
|
JavaScript Java 容器
servlet过滤器Filter简要回顾-过滤请求字符编码,/和/*和/**的区别
本文简要回顾了Servlet过滤器Filter的概念和使用,通过实例演示了如何创建过滤器以过滤请求字符编码,并解释了在web.xml中配置过滤器时使用`/`、`/*`和`/**`的区别。
servlet过滤器Filter简要回顾-过滤请求字符编码,/和/*和/**的区别
|
3月前
|
存储 前端开发 Java
servlet过滤器--使用过滤器统计网站访问人数的计数(注解形式)
该文章展示了如何使用Servlet过滤器(Filter)通过注解方式创建一个网站访问人数统计功能,通过`@WebFilter`注解定义过滤器及其URL模式,并在`doFilter`方法中实现计数逻辑,将访问次数存储在`ServletContext`中,最后在JSP页面展示访问人数。
servlet过滤器--使用过滤器统计网站访问人数的计数(注解形式)
|
5月前
|
NoSQL Java Redis
深入理解Servlet Filter及其限流实践
深入理解Servlet Filter及其限流实践
163 44
|
3月前
|
C# 数据可视化 开发者
WPF开发者福音:深度解析OxyPlot与LiveCharts图表库,轻松实现数据可视化不再是难题!
【8月更文挑战第31天】在WPF应用中,数据可视化对提升用户体验至关重要。本文介绍并演示了两种流行图表库OxyPlot和LiveCharts的集成与使用方法。OxyPlot是一款适用于.NET应用的开源图表库,提供多种图表类型,易于集成。LiveCharts则以其丰富的图表类型和动画效果,特别适合实时数据展示。通过具体代码示例,本文展示了如何利用这两种图表库创建折线图和柱状图,并详细说明了安装和配置步骤。希望本文能帮助开发者在WPF应用中轻松实现高效、美观的数据可视化。
149 0
|
3月前
|
安全 Java API
Java 8 流库的魔法革命:Filter、Map、FlatMap 和 Optional 如何颠覆编程世界!
【8月更文挑战第29天】Java 8 的 Stream API 通过 Filter、Map、FlatMap 和 Optional 等操作,提供了高效、简洁的数据集合处理方式。Filter 用于筛选符合条件的元素;Map 对元素进行转换;FlatMap 将多个流扁平化合并;Optional 安全处理空值。这些操作结合使用,能够显著提升代码的可读性和简洁性,使数据处理更为高效和便捷。
70 0
|
3月前
|
监控 前端开发 Java
揭秘Web开发神器:Servlet、过滤器、拦截器、监听器如何联手打造无敌博客系统,让你的用户欲罢不能!
【8月更文挑战第24天】在Java Web开发中,Servlet、过滤器(Filter)、拦截器(Interceptor,特指Spring MVC中的)及监听器(Listener)协同工作,实现复杂应用逻辑。以博客系统为例,Servlet处理文章详情请求,过滤器(如LoginFilter)检查登录状态并重定向,Spring MVC拦截器(如LoggingInterceptor)提供细粒度控制(如日志记录),监听器(如SessionListener)监控会话生命周期事件。这些组件共同构建出高效、有序的Web应用程序。
36 0
|
4月前
|
Java
图解java工程师学习路线
图解java工程师学习路线
215 0
|
5月前
|
安全 Java 容器
Java 1.8新特性使用记录:Filter、数据容器的转换、排序Sorted
Java 1.8新特性使用记录 有些方法一段时间不使用会忘记,这里要记录一下,方便以后使用 一、过滤Filter 二、数据容器的转换 三、List 排序
40 0
|
5月前
|
Java
java中Stream流中的forEach、filter、map、count、limit、skip、concat
java中Stream流中的forEach、filter、map、count、limit、skip、concat
141 0
|
3月前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
Java服务器端技术:Servlet与JSP的集成与扩展
31 3