java入門でFilterインターフェースの作成、設定の方法

1.Filterの設定
@WebFilter(filterName="authority"
, urlPatterns={“/*"}
, initParams={
@WebInitParam(name="encoding", value="utf8″),
@WebInitParam(name="loginPage", value="/login.jsp"),
@WebInitParam(name="noLogin", value="/noLogin.jsp")})
public class AuthorityFilter implements Filter
{
private FilterConfig config;
//初期化
public void init(FilterConfig config)
{
this.config = config;
}
public void destroy()
{
this.config = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException,ServletException
{
//Filterのパラメータの取得
String encoding = config.getInitParameter(“encoding");
String loginPage = config.getInitParameter(“loginPage");
String noLogin = config.getInitParameter(“noLogin");
//requestのエンコード
request.setCharacterEncoding(encoding);
HttpServletRequest requ = (HttpServletRequest)request;
HttpSession session = requ.getSession(true);
//アクセスページ
String requestPath = requ.getServletPath();
if( session.getAttribute(“user") == null
&& !requestPath.endsWith(loginPage)
&& !requestPath.endsWith(noLogin))
{
//forwardログイン画面
request.setAttribute(“tip" , “ログインしてない");
request.getRequestDispatcher(loginPage)
.forward(request, response);
}
else
{
chain.doFilter(request, response);
}
}
}

2.web.xmlの設定
<filter>
<filter-name>authority</filter-name>
<filter-class>jbelial.Filter.Authority</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
<init-param>
<param-name>loginPage</param-name>
<param-value>/login.jsp</param-value>
</init-param>
<init-param>
<param-name>noLogin</param-name>
<param-value>/noLogin.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>authority</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Java

Posted by arkgame