分类:
2008-07-23 12:51:05
例子在JSF框架里面过滤success.jsp,防止非法用户绕过登录页面直接输入/ faces/success.jsp进入到成功页面。
编写Filter实现类:
public class AuthorityFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String isLogin = (String) req.getSession().getAttribute("isLogin");
if(isLogin == null || !isLogin.equals("yes")){
res.sendRedirect(req.getContextPath()+"/faces/error.jsp");
}
try {
chain.doFilter(request, response);
}
catch(Throwable t) {
}
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
}
}
代码分析:从session里面取得isLogin,判断是否登录,否的话重定向到错误页面,成功的话chain.doFilter(request,response);允许通过。
<filter>
<filter-name>encodingfilter-name>
<filter-class>
filter.FilterEncoding
filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>gbkparam-value>
init-param>
filter>
Set Character Encoding /*
package filter;
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;
public class FilterEncoding implements Filter
{
protected String encoding; // 接收字符编码
protected boolean ignore; // 是否忽略大小写
protected FilterConfig filterConfig; // 初始化配置
public void init(FilterConfig filterConfig) throws ServletException
{
// 从web.xml文件中读取encoding的值
encoding = filterConfig.getInitParameter("encoding");
// 从web.xml文件中读取ignore的值
String value = filterConfig.getInitParameter("ignore");
// 以下三种情况均为忽略大小写
if(value == null)
{
ignore = true;
}
else if(value.equalsIgnoreCase("yes"))
{
ignore = true;
}
else if(value.equalsIgnoreCase("true"))
{
ignore = true;
}
}
// doFilter方法
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
if(ignore || request.getCharacterEncoding() == null)
{
// 如果为空先从web.xml中得到
String encoding = selectEncoding(request);
if(encoding != null)
{
// 设置字符集编码
request.setCharacterEncoding(encoding);
}
}
// 继续执行
chain.doFilter(request, response);
}
// 得到字符编码
private String selectEncoding(ServletRequest request)
{
return encoding;
}
public void destroy()
{
}
}
<%@ page contentType="text/html;charset=gbk"%>