Java web项目中的强制登录功能实现代码
为了避免直接进入项目中存在的页面,使用filter过滤器
新建一个类loginFilter:
package com.tjcu.filter; import com.tjcu.entity.User; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class loginFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); HttpServletResponse response = (HttpServletResponse) servletResponse; if (user!=null) { filterChain.doFilter(request,response); }else { response.sendRedirect(request.getContextPath()+"/login.jsp"); } } @Override public void destroy() { } }
在web文件中通知服务器开发了这个过滤器
web.xml:
<filter> <filter-name>loginFilter</filter-name> <filter-class>com.tjcu.filter.loginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/main/*</url-pattern> </filter-mapping>
到此这篇关于Java web项目中的强制登录的文章就介绍到这了,更多相关Java web强制登录内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
【文章来源:http://www.yidunidc.com/mg.html 原文提供 欢迎转载】