:Spring中视图有多种,现在因为WAP网站的原因,需要自定义JstlView可以使得渲染JSP时时候能给html中每个连接加上参数:
1:使用HttpServletResponseWrapper类包装HttpServletReponse
/**
* 重写包装类
* @author lijunqing
*/
public class WapResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream buffer;
private PrintWriter writer;
private ServletOutputStream out;
public WapResponseWrapper(HttpServletResponse response) throws UnsupportedEncodingException {
super(response);
buffer=new ByteArrayOutputStream();
out=new WapOutPutStream(buffer);
writer=new PrintWriter(new OutputStreamWriter(buffer, "UTF-8"));
}
// 重载父类获取outputstream的方法
public ServletOutputStream getOutputStream() throws IOException {
return out;
}
// 重载父类获取writer的方法
public PrintWriter getWriter() throws UnsupportedEncodingException {
return writer;
}
public void flushBuffer() throws IOException {
if(out != null) {
out.flush();
}
if(writer != null) {
writer.flush();
}
}
public String getContent() throws IOException {
flushBuffer(); //强行flush 不然有可能为空
return buffer.toString("UTF-8");
}
/**
* 自定义WapOutPutStream 把Reponse的流写到WapOutPutStream中
* @author lijunqing
*/
private class WapOutPutStream extends ServletOutputStream {
ByteArrayOutputStream byteArrayOut;
public WapOutPutStream(ByteArrayOutputStream out) {
byteArrayOut=out;
}
@Override
public void write(int b) throws IOException {
byteArrayOut.write(b);
}
}
}
2:定义WapView继承JstlView
/**
* wap视图显示
* @author lijunqing
*/
public class WapView extends JstlView {
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
WapResponseWrapper wrapper=new WapResponseWrapper(response);
super.render(model, request, wrapper); // 使得我们可以获得页面内容
String result=wrapper.getContent();
// 用正则给每个url加公共参数等 处理逻辑
PrintWriter w=response.getWriter(); // 这个地方不能用Wrapper的,不然输出页面没内容;
w.write(result);
w.flush();
}
}