我是网络编程新手。我要求一种通用模式来执行诸如检查身份验证之类的操作。这是场景:
该网站有一个供访问者登录的页面。它将获取用户名和加密密码并将其发送到服务器,然后从服务器获取错误代码(用户名/密码不匹配)或身份验证密钥。当用户登录成功时,我希望网站自动跳转到main.jsp
展示网站主要功能的页面。
在这种情况下,我想要main.jsp
检查用户身份验证。也就是说,我不希望发生这样的事情,比如用户可以直接打开www.example.com/main.jsp
,如果他们做了这样的事情,我想将他们重定向到登录页面。
那么如何跨页面传递身份验证信息,以及如何阻止用户直接访问main.jsp
无需登录?我需要使用会话或其他什么吗?
你可以尝试使用filters:
过滤器可以在请求到达 servlet 之前对其进行预处理,
对离开 servlet 的响应进行后处理,或两者兼而有之。
过滤器可以拦截、检查和修改请求和响应。
NOTE:确保在用户登录后添加会话属性,您可以在过滤器上使用该会话属性
on your 登录.jsp add:
session.setAttribute("LOGIN_USER", user);
//user entity if you have or user type of your user account...
//if not set then LOGIN_USER will be null
web.xml
<filter>
<filter-name>SessionCheckFilter</filter-name>
<filter-class>yourjavapackage.SessionCheckFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionCheckFilter</filter-name>
<!--url-pattern>/app/*</url-pattern-->
<url-pattern>/main.jsp</url-pattern> <!-- url from where you implement the filtering -->
</filter-mapping>
SessionCheckFilter.java
public class SessionCheckFilter implements Filter {
private String contextPath;
@Override
public void init(FilterConfig fc) throws ServletException {
contextPath = fc.getServletContext().getContextPath();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getSession().getAttribute("LOGIN_USER") == null) { //checks if there's a LOGIN_USER set in session...
res.sendRedirect(contextPath + "/login.jsp"); //or page where you want to redirect
} else {
String userType = (String) req.getSession().getAttribute("LOGIN_USER");
if (!userType.equals("ADMIN")){ //check if user type is not admin
res.sendRedirect(contextPath + "/login.jsp"); //or page where you want to
}
fc.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)