Filter解决乱码问题
引用接口
public class filter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; Charset =utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}
这里接口不用完全实现,只需要实现一个doFilter。因为在接口里有defalut修饰
public interface Filter {
default void init(javax.servlet.FilterConfig filterConfig) throws javax.servlet.ServletException {
/* compiled code */ }
void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException;
default void destroy() {
/* compiled code */ }
}
在xml里面配置
<filter>
<filter-name>character</filter-name>
<filter-class>com.yim.Servlet.filter</filter-class>
</filter>
<filter-mapping>
<filter-name>character</filter-name>
<url-pattern>/test2</url-pattern>
</filter-mapping>
这里就完成了控制台和输出到页面都没有乱码问题,也不用每个类都去修改一次乱码问题
注:writer乱码问题
FileReader读取中文字符乱码问题,注意UTF-8
InputStream inputStream= req.getInputStream();
Reader reader=new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader=new BufferedReader(reader);
屏蔽敏感词
@WebFilter("/test")
public class WordFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
servletRequest.setCharacterEncoding("UTF-8");
//将"敏感词"替换成"***"
String name = servletRequest.getParameter("name");
name = name.replaceAll("敏感词","***");
servletRequest.setAttribute("name",name);
filterChain.doFilter(servletRequest,servletResponse);
}
}
控制页面的访问权限。
假如用户无登陆状态直接打开下载链接,是不会跳转到下载页面而是跳转到登陆页面。
主要利用session和webfilter过滤器
@WebFilter("/download.jsp")
public class DownloadFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
if(name == null){
//不是登录状态
response.sendRedirect("/login.jsp");
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
}