我用来防止用户在没有登录的情况下访问URL的代码 如下:
的web.xml
<filter>
<filter-name>Filtro_Autenticar</filter-name>
<filter-class>Controlador.Filtro_Autenticar</filter-class>
</filter>
<filter-mapping>
<filter-name>Filtro_Autenticar</filter-name>
<url-pattern>/vistas/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
Filtro_Autenticar.java
public class Filtro_Autenticar implements Filter {
public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpSession session;
if (req instanceof HttpServletRequest){
session = ((HttpServletRequest)req).getSession();
//Eliminar la caché
HttpServletResponse hsr = (HttpServletResponse) res;
hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
hsr.setDateHeader("Expires", 0); // Proxies.
//Verificar si la sesion es diferente de null
if (session.getAttribute("user") != null) {
//solo deja pasar a la zona restringida al usuario
chain.doFilter(req, res);
} else {
((HttpServletResponse)res).sendRedirect(((HttpServletRequest)req).getContextPath()+ "/index.jsp");
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String exclude= filterConfig.getInitParameter("exclude");
}
@Override
public void destroy() {
}
}
使用此代码可能会限制对某些jsp页面的访问 取决于已登录的用户?
答案 0 :(得分:1)
您需要以某种方式在会话中存储usertype。如何将usertype引入会话取决于您的实现。例如,当用户登录时,您可以从数据库表中查找并将其放入会话中。
在您的登录代码中:
session.setAttribute("usertype", usertype_from_db);
在开始打印任何内容之前,您在限制访问权限的页面顶部:
String usertype = (String)session.getAttribute("usertype");
if(!"admin".equals(usertype))
{
response.sendRedirect("unauthorized.jsp");
return; //necessary to make the redirect happen right now
}