教你一步步做 Restful程序(5)

时间:2020-11-28 20:58:49

教你一步步做 Restful程序(5)

2012年12月28日

  加入简单的安全控制:

  写一个过滤器,对非法用户进行过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest)request;
String path = req.getRequestURI();

System.out.println("你访问的资源路径是:" + req.getRequestURI());

if (req.getSession().getAttribute("session_key") != null) {
chain.doFilter(request, response);
return;
} else {

if (path.indexOf("/userManager/") != -1) {
HttpServletResponse resp = (HttpServletResponse)response;
resp.sendRedirect(req.getContextPath() + "/error.html");
return;
}

chain.doFilter(request, response);
}


}

  并在web.xml中添加:

web.xml
1
2
3
4
5
6
7
8
9
 <filter>
<display-name>AuthFilter</display-name>
<filter-name>AuthFilter</filter-name>
<filter-class>com.my.jxc.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

本文转载于:http://yanyaner.com/blog/2012/12/28/restful5/

刘江华的博客