我已经创建了一个web应用程序。一切正常。但是,如果用户还没有登录,他们可以通过url访问其他jsp页面。我想停止URL访问。我看到一些例子,它显示了过滤器的用法。我是新来的过滤器,我不知道如何实现它。我正在使用servlet,dao和jsp页面。如何防止从jsp页面的url直接访问页面
请告诉我该怎么做。我想为所有的jsp或servlets页面创建一个过滤器。
Web.XML:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>MBO</display-name>
<filter>
<filter-name>MyFiltersDAO</filter-name>
<filter-class>Model.MyFiltersDAO</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFiltersDAO</filter-name>
<url-pattern>/secret/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
类:
public class MyFiltersDAO {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String abc=(String) req.getSession().getAttribute("Username");
if(null==((String) req.getSession().getAttribute("Username")) || ((String) req.getSession().getAttribute("Username")).equals("")){
chain.doFilter(req, resp);
} else {
resp.sendRedirect("/Login.jsp");
}
}
public void destroy() {
}
}
当我运行的项目它显示HTTP404错误
有使用
做你尝试使用会话? –
这个链接可以为你使用:https://www.javatpoint.com/authentication-filter –
即使你不使用Spring,你也许会看看Spring Security(你真的不应该用手在有用的框架可用时编码servlet)。 – chrylis