过滤器的简单例子

过滤器的简单例子

设置过滤器;必须登录成功才能访问sys目录下的success.jsp

项目目录

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>登录</title>
</head>
<body>
<form action="/login" method="get">
  用户名:<input type="text" name="username">
   <input type="submit" value="登录">
</form>
</body>
</html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<h1>登录失败,用户名错误或没有权限访问</h1>

<a href="login.jsp">返回登录界面</a>
</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>主页</title>
</head>
<body>
<h1>主页</h1>
<h1>登录成功</h1>
<a href="/logout">注销</a>
</body>
</html>

loginServlet

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String name = req.getParameter("username");
       if("admin".equals(name)){
           req.getSession().setAttribute(constant.USER_SESSION,req.getSession().getId());
           resp.sendRedirect("/sys/success.jsp");
      }else{
           resp.sendRedirect("/error.jsp");
      }

logoutServlet

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Object user_session = req.getSession().getAttribute(constant.USER_SESSION);
       if(user_session!=null){
           req.getSession().removeAttribute(constant.USER_SESSION);
           resp.sendRedirect("/login.jsp");
      }else{
           resp.sendRedirect("/login.jsp");
      }

工具类utils包里存放session的名字,方便以后修改

public class constant {
   public final static String USER_SESSION="USER_SESSION";
}

web.xml

<filter>
       <filter-name>SysFilter</filter-name>
       <filter-class>com.bxb.filter.SysFilter</filter-class>
   </filter>
   <filter-mapping>
       <filter-name>SysFilter</filter-name>
       <url-pattern>/sys/*</url-pattern>
   </filter-mapping>

 

原文地址:https://www.cnblogs.com/bxbo/p/13453389.html