@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// 过滤用户请求,判断是否登录
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
httpServletRequest.setCharacterEncoding("utf-8");
httpServletResponse.setCharacterEncoding("utf-8");
String username = (String)httpServletRequest.getSession().getAttribute("username");
if (username == null) {
String path = httpServletRequest.getContextPath();
httpServletResponse.sendRedirect(path+"/index.jsp");
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
<!-- 配置 过滤器 -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!-- /*表示过滤所有页面 ,/main.jsp 表示只过滤main.jsp页面-->
<url-pattern> /main.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<!-- /*表示过滤所有页面 /addProduct.jsp 表示只过滤addProduct.jsp页面-->
<url-pattern>/addProduct.jsp</url-pattern>
</filter-mapping>