(二十四)权限控制(粗粒度)-通过filter
Posted Michael2397
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(二十四)权限控制(粗粒度)-通过filter相关的知识,希望对你有一定的参考价值。
扩展:权限控制(粗粒度)-通过filter 过滤器编写步骤: 1.编写一个类 实现filter接口 重写方法 2.编写配置文件 <filter> <filter-mapping> 编写一个privilegeFilter 判断用户是否登录(session) 若为空 请求转发到msg.jsp 携带信息
com.louis.web.filter.PrivilegeFilter
package com.louis.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.louis.dao.UserDao; import com.louis.domain.User; public class PrivilegeFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { //1.强转 HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response=(HttpServletResponse) resp; //2.业务逻辑 //从session中获取user 判断user是否为空 若为空 请求转发 User user=(User) request.getSession().getAttribute("user"); if(user==null){ request.setAttribute("msg", "没有权限,请先登录!"); request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response); return; } //3.放行 chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } }
/store/WebContent/WEB-INF/web.xml
<filter> <filter-name>PrivilegeFilter</filter-name> <filter-class>com.itheima.web.filter.PrivilegeFilter</filter-class> </filter> <filter-mapping> <filter-name>PrivilegeFilter</filter-name> <servlet-name>OrderServlet</servlet-name> <url-pattern>/jsp/order_info.jsp</url-pattern> <url-pattern>/jsp/order_list.jsp</url-pattern> <!-- <url-pattern>/jsp/cart.jsp</url-pattern> --> </filter-mapping>
以上是关于(二十四)权限控制(粗粒度)-通过filter的主要内容,如果未能解决你的问题,请参考以下文章