1.定义拦截器
package com.lx.interceptor;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.lx.utils.RequestUtil;
public class LoginInterceptor implements HandlerInterceptor {
private List<String> excludeUrls;
public List<String> getExcludeUrls() {
return excludeUrls;
}
public void setExcludeUrls(List<String> excludeUrls) {
this.excludeUrls = excludeUrls;
}
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
// 设置字符编码
request.setCharacterEncoding("UTF-8");
// 判断是否登录(只拦截前台登录)
HttpSession session = request.getSession();
String requestUrl = RequestUtil.getRequestPath(request);
for (String excludeUrl : excludeUrls) {
if (requestUrl.indexOf(excludeUrl) != -1) {
return true;
}
}
String s=(String) session.getAttribute("123");
System.out.println(s);
if("123".equals(s)) {
System.out.println("session tong______");
return true;}
response.sendRedirect(request.getContextPath() + "/login.jsp");
return false;
}
}
2、在spring-mvc.xml中配置
<mvc:interceptors>
<bean class="com.lx.interceptor.LoginInterceptor">
<property name="excludeUrls">
<list>
<value>/login</value>
</list>
</property>
</bean>
</mvc:interceptors>
3、RequestUtil中的内容
package com.lx.utils;
import javax.servlet.http.HttpServletRequest;
public class RequestUtil {
public static String getRequestPath(HttpServletRequest request) {
String requestPath = request.getRequestURI();
requestPath = requestPath.substring(request.getContextPath().length());// 鍘绘帀椤圭洰璺緞
return requestPath;
}
private static final String[] PROXY_REMOTE_IP_ADDRESS = { "X-Forwarded-For", "X-Real-IP" };
public static String getRemoteIp( HttpServletRequest request ) {
for ( int i = 0 ; i < PROXY_REMOTE_IP_ADDRESS.length ; i++ ) {
String ip = request.getHeader( PROXY_REMOTE_IP_ADDRESS[i] );
if ( ip != null && ip.trim().length() > 0 ) {
return getRemoteIpFromForward( ip.trim() );
}
}
return request.getRemoteHost();
}
private static String getRemoteIpFromForward( String xforwardIp ) {
int commaOffset = xforwardIp.indexOf( ',' );
if ( commaOffset < 0 ) {
return xforwardIp;
}
return xforwardIp.substring( 0 , commaOffset );
}
}