星期三, 5月 30, 2012

[Java] Filter 變更 jsp輸出內容

今天為了讓jsp上面的js檔案能使用SVN的版號做版本控制,
又為了讓同事能不用變更之前放在jsp裡面的script path,
所以想到了可以透過filter來將jsp輸出前把script path加上SVN的版號,
這樣就可以模擬出使用者每次都能讀到最新變更的Javascript

以下是簡單置換內容的Filter Sample




import java.io.CharArrayWriter;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class ResponseWrapper extends HttpServletResponseWrapper {

 private PrintWriter cachedWriter;
 private CharArrayWriter bufferedWriter;

 public ResponseWrapper(HttpServletResponse response) {
  super(response);
  this.bufferedWriter = new CharArrayWriter();
  this.cachedWriter = new PrintWriter(this.bufferedWriter);
 }

 @Override
 public PrintWriter getWriter() {
  return this.cachedWriter;
 }

 public String getResponseHtml() {
  return this.bufferedWriter.toString();
 }
}


透過Filter結合HttpServletResponseWrapper
 @Override
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {

  ResponseWrapper respWrapper 
   = new ResponseWrapper((HttpServletResponse) response);
  
  HttpServletResponse hsrespWrapper = respWrapper;
  
  chain.doFilter(request, hsrespWrapper);

  // get html content(依你的需求取代這個content的內容即可)
  String currentJSPCotent = respWrapper.getResponseHtml()

  
  // final output content
  PrintWriter out = response.getWriter();
  out.write(currentJSPCotent);
  out.flush();
  out.close();
 }

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails