java servlet api 2.3 引进了过滤器,它支持拦截和转换 http 请求或响应。
以下示例使用 validator.f ilter 来用“servlet 过滤器”清理响应:
Java代码
// example to f ilter all sensitive characters in the http response using a java filter. // this example is for illustration purposes since it will f ilter all content in the response, including html tags! public class sensitivecharsfilter implements filter { ... public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception { printwriter out = response.getwriter(); responsewrapper wrapper = new responsewrapper((httpservletresponse)response); chain.dofilter(request, wrapper); chararraywriter caw = new chararraywriter(); caw.write(validator.f ilter(wrapper.tostring())); response.setcontenttype("text/html"); response.setcontentlength(caw.tostring().length()); out.write(caw.tostring()); out.close(); } ... public class charresponsewrapper extends httpservletresponsewrapper { private chararraywriter output; public string tostring() { return output.tostring(); } public charresponsewrapper(httpservletresponse response){ super(response); output = new chararraywriter(); } public printwriter getwriter(){ return new printwriter(output); } } }
[8-2] 保护cookie
在cookie中存储敏感数据时,确保使用cookie.setsecure(布尔标志)在 http 响应中设置cookie 的安全标志,以指导浏览器使用安全协议(如 https 或 ssl)发送cookie。
保护“用户”cookie 的示例:
Java代码
// example to secure a cookie, i.e. instruct the browser to / / send the cookie using a secure protocol cookie cookie = new cookie("user", "sensitive"); cookie.setsecure(true); response.addcookie(cookie);
全文结束,有问题的可以留言大家探讨。
作者“技术总结”