Servlet - Filterクラス作成
Filterクラスはjavax.servlet.Filterインタフェースを実装する。
1. void init(FilterConfit config) ⇒ 初期化メソッド
2. void destory() ⇒ 破棄メソッド
3. void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
⇒ filter処理実装
FirstFilter.java |
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(urlPatterns="/*")
public class FirstFilter implements Filter {
private FilterConfig config;
@Override
public void destroy() {
// Filter破棄方法
this.config = null;
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// Serlvet前処理
System.out.println("Filter処理開始します。");
// HttpServletRequestにキャスト
HttpServletRequest request = (HttpServletRequest)arg0;
request.setCharacterEncoding("UTF-8");
// HttpServletを呼び出す
arg2.doFilter(arg0, arg1);
// Serlvet後処理
System.out.println("Filter処理終了します。");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// filter init parameter
this.config = arg0;
}
}
|
afterFilterServlet.java |
import java.io.IOException;
import java.io.PrintStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/afterFilterServlet")
public class afterFilterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// set responce contecTtype
response.setContentType("text/html;charset=UTF-8");
// output stream
PrintStream out = new PrintStream(response.getOutputStream());
out.println("<html>");
out.println("<title>");
out.println("it is first servlet.");
out.println("</title>");
out.println("リクエスト文字コードは" + request.getCharacterEncoding());
out.println("<br/>");
out.println("</html>");
}
}
|
http://localhost:8080/webDemo/afterFilterServlet |