1.对编码进行过滤:
EncodeFilter.java
package com.bgiseq.util; 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 EncodeFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 将服务器的响应编码格式设置为UTF-8 response.setContentType("text/html;charset=utf-8"); // 浏览器请求服务器过滤乱码 request.setCharacterEncoding("utf-8"); chain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { } }
xml配置:
<!-- 过滤编码 --> <filter> <filter-name>EncodeFilter</filter-name> <filter-class>com.bgiseq.util.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
判断用户是否登录:
UserIslogin.java
package com.bgiseq.util; 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; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserIslogin implements Filter{ @Override public void destroy() {} @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // 获得在下面代码中要用的request,response,session对象 HttpServletRequest request=(HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; HttpSession session = request.getSession(); // 从session里登录信息 String username= (String) session.getAttribute("Username"); // 获得用户请求的URI String path = request.getRequestURI(); /*if(path.indexOf("css")!=-1||path.indexOf("images")!=-1||path.indexOf("jquery")!=-1||path.indexOf("script")!=-1||path.indexOf("all")!=-1||path.indexOf("loginUser")!=-1){ chain.doFilter(req, resp); } */ // 登陆页面无需过滤 if(path.indexOf("/login.jsp") > -1) { chain.doFilter(request, response); return; } // 判断如果没有取到员工信息,就跳转到登陆页面 if (username == null || "".equals(username)) { response.sendRedirect("/BGISEQ2/views/jsp/login/login.jsp"); }else{ // 已经登陆,继续此次请求 chain.doFilter(req, resp); } } @Override public void init(FilterConfig arg0) throws ServletException {} }
XML配置:
<!-- 判断用户是否登录 --> <filter> <filter-name>UserIslogin</filter-name> <filter-class>com.bgiseq.util.UserIslogin</filter-class> </filter> <filter-mapping> <filter-name>UserIslogin</filter-name> <url-pattern>/views/jsp/*</url-pattern> </filter-mapping>