当前位置:首页 » HTML/CSS

过滤器中向所有JSP页面插入html代码

2009-10-20 15:23 本站整理 浏览(12)

为公司内部开发了1个简单的MVC框架,框架中需要向所有JSP页面的<head>中插入2条引用JS的代码,实现如下:

主要是继承HttpServletResponseWrapper写1个类(PageResponseWrapper),代码:

1 public class PageResponseWrapper extends HttpServletResponseWrapper {

2 private Buffer buffer;

3 private HttpServletResponse originalResponse;

4

5 public PageResponseWrapper(final HttpServletResponse response){

6 super(response);

7 this.originalResponse = response;

8 buffer = new Buffer();

9 }

10

11 @Override

12 public PrintWriter getWriter() throws IOException {

13 return buffer.getWriter();

14 }

15

16 public CharArrayWriter getContent(){

17 return buffer.getBufferedWriter();

18 }

19

20 public void close() throws IOException {

21 buffer.getWriter().close();

22 }

23

24 public void finalize() throws Throwable {

25 super.finalize();

26 buffer.getWriter().close();

27 }

28

29 /**

30 * 获取原始的response

31 * @return the originalResponse

32 */

33 public HttpServletResponse getOriginalResponse() {

34 return originalResponse;

35 }

36 }

Buffer类:

1 public class Buffer {

2

3 private CharArrayWriter bufferedWriter;

4 private PrintWriter exposedWriter;

5

6 public char[] getContents() throws IOException {

7 //bufferedWriter 表示请求的页面的html

8 if (getBufferedWriter() != null) {

9 return getBufferedWriter().toCharArray();

10 }

11 return null;

12 }

public PrintWriter getWriter() {

16 if (getBufferedWriter() == null) {

17 bufferedWriter = new CharArrayWriter();

18 exposedWriter = new PrintWriter(getBufferedWriter());

19 }

20 return exposedWriter;

21 }

22 /**

23 * @return the bufferedWriter

24 */

25 public CharArrayWriter getBufferedWriter() {

26 return bufferedWriter;

27 }

28 }

过滤器的代码:

1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

2 HttpServletRequest hRequest = (HttpServletRequest)request;

3 HttpServletResponse hResponse = (HttpServletResponse)response;

4 PageResponseWrapper prw = new PageResponseWrapper(hResponse);

5

6 chain.doFilter(request, prw);

7 // 得到视图html代码

8 String tmpHtml = prw.getContent();

9 // 最终输出的html代码

10 String retHtml = "";

11 // 查找<head>

12 int index = tmpHtml.toLowerCase().indexOf("<head>");

13 if(index != -1){

14 index +=6;

15 retHtml = tmp.substring(0, index) + "<script src='http://./..js'></script>" + tmp.substring(index);

16 }else{

17 retHtml = tmpHtml;

18 }

19 // 输出(注意,这里只能使用hResponse,不能使用prwgetWriter())

20 PrintWriter writer = hResponse.getWriter();

21 writer.write(retHtml);

22 writer.close();

23 writer.close();

24 writer.flush();

25 }