Java Tutorial/Servlet/Filter

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Filter Response

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
    
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    chain.doFilter(request, response);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
    out.println("The filter got this message: " + filterConfig.getInitParameter("message"));
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





Filter that uses a response wrapper to convert all output to uppercase

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class UpperCaseFilter implements Filter {
  protected FilterConfig config;
  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }
  public void destroy() {
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    ServletResponse newResponse = response;
    if (request instanceof HttpServletRequest) {
      newResponse = new CharResponseWrapper((HttpServletResponse) response);
    }
    chain.doFilter(request, newResponse);
    if (newResponse instanceof CharResponseWrapper) {
      String text = newResponse.toString();
      if (text != null) {
        text = text.toUpperCase();
        response.getWriter().write(text);
      }
    }
  }
}
class CharResponseWrapper extends HttpServletResponseWrapper {
  protected CharArrayWriter charWriter;
  protected PrintWriter writer;
  protected boolean getOutputStreamCalled;
  protected boolean getWriterCalled;
  public CharResponseWrapper(HttpServletResponse response) {
    super(response);
    charWriter = new CharArrayWriter();
  }
  public ServletOutputStream getOutputStream() throws IOException {
    if (getWriterCalled) {
      throw new IllegalStateException("getWriter already called");
    }
    getOutputStreamCalled = true;
    return super.getOutputStream();
  }
  public PrintWriter getWriter() throws IOException {
    if (writer != null) {
      return writer;
    }
    if (getOutputStreamCalled) {
      throw new IllegalStateException("getOutputStream already called");
    }
    getWriterCalled = true;
    writer = new PrintWriter(charWriter);
    return writer;
  }
  public String toString() {
    String s = null;
    if (writer != null) {
      s = charWriter.toString();
    }
    return s;
  }
}
Simple response wrapper that utilizes a local CharArrayWriter for output

<filter>
  <filter-name>Upper Case Filter</filter-name>
  <filter-class>com.omh.filters.UpperCaseFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>Upper Case Filter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
*/





Servlet Filter Init Parameter

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
    
    
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    System.out.println("The message is: " + filterConfig.getInitParameter("message"));
    chain.doFilter(request, response);
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





Simple filter for measuring servlet response times

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.http.HttpServletRequest;
public class ResponseTimerFilter implements Filter {
  protected FilterConfig config;
  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }
  public void destroy() {
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    long startTime = System.currentTimeMillis();
    chain.doFilter(request, response);
    long elapsed = System.currentTimeMillis() - startTime;
    String name = "servlet";
    if (request instanceof HttpServletRequest) {
      name = ((HttpServletRequest) request).getRequestURI();
    }
    config.getServletContext().log(name + " took " + elapsed + " ms");
  }
}
<filter>
  <filter-name>Timing Filter</filter-name>
  <filter-class>com.omh.filters.ResponseTimerFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>Timing Filter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
*/





Use Filter to Check Date

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
 
    GregorianCalendar calendar = new GregorianCalendar();
    Date date1 = new Date();
    calendar.setTime(date1);
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    if(hour < 9 || hour > 17) {   
        chain.doFilter(request, response);
    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("Get Back to Work!");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>Get Back to Work!</H1>");
        out.println("Sorry, that resource is not available now.");
        out.println("</BODY>");
        out.println("</HTML>");
    }    
  }
  public void destroy() 
  { 
  }
  public void init(FilterConfig filterConfig) 
  {
  }
}





Use Filter to check Request Parameter

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    String password = ((HttpServletRequest) request).getParameter("password");
     
    if(password.equals("opensesame")) {   
        chain.doFilter(request, response);
    } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("Incorrect Password");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>Incorrect Password</H1>");
        out.println("Sorry, that password was incorrect.");
        out.println("</BODY>");
        out.println("</HTML>");
    }    
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





Use Filter to log Configuration

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
  private FilterConfig filterConfig = null;
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    long start = System.currentTimeMillis();
    String address =  request.getRemoteAddr();
    String file = ((HttpServletRequest) request).getRequestURI();
        
    chain.doFilter(request, response);
    filterConfig.getServletContext().log(
        "User access! " +      
        " User IP: " + address +      
        " Resource: " + file + 
        " Milliseconds used: " + (System.currentTimeMillis() - start) 
    );
  }
  public void destroy() { }
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
}





Your First Filter

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet implements Filter 
{
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException 
  {
    System.out.println("In filter");
    chain.doFilter(request, response);
    System.out.println("Leaving filter");
  }
  public void destroy() 
  { 
  }
  public void init(FilterConfig filterConfig) 
  {
  }
}