设置登录界面的访问地址不拦截,如果直接访问除登录界面的地址时,那么此时session就为空,则直接跳转回登录界面。
话不多说,直接上代码
web.xml文件配置拦截部分代码
<!-- 检查后端用户是否登录了管理系统的过滤器配置 开始 -->
<filter>
<filter-name>BackendSessionFilter</filter-name>
<filter-class>com.Lin.jianji.filter.LoginFilter</filter-class>
<init-param>
<description>将当前登录的用户的信息保存在 session 中时使用的key,如果没有配置此参数,则该过滤器不起作用</description>
<param-name>sessionKey</param-name>
<param-value>BACKEND_SESSION_USER_KEY</param-value>
</init-param>
<init-param>
<description>
如果用户未登录(即在 session 中 key 为 sessionKey 的属性不存在或为空),则将请求重定向到该 url。
该 url 不包含web应用的 ContextPath。
如果不配置此参数,则在用户未登录系统的情况下,直接重定向到web应用的根路径(/)
</description>
<param-name>forwardUrl</param-name>
<param-value>/resources/index.jsp</param-value>
</init-param>
<init-param>
<description>
不需要进行拦截的 url 的正则表达式,即:如果当前请求的 url 的 servletPath 能匹配该正则表达式,则直接放行(即使未登录系统)。
此参数的值一般为 loginServlet 和 registServlet 等。
另外,参数 redirectUrl 的值不用包含在该正则表达式中,因为 redirectUrl 对应的 url 会被自动放行。
还有一点需要说明的是,该参数的值不包含web应用的 ContextPath。
</description>
<param-name>excepUrlRegex</param-name>
<!-- 不拦截 -->
<param-value>/login.action</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>BackendSessionFilter</filter-name>
<url-pattern>/resources/welocme.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>BackendSessionFilter</filter-name>
<url-pattern>/welcome/*</url-pattern>
</filter-mapping>
<!-- 检查后端用户是否登录了管理系统的过滤器配置 结束 -->
主要的那些都用红色框框起来了
少圈了spring下的root-context.xml
里面也要有这段代码
<!-- 启动项目时Spring创建一个过滤器对象交由代理过滤器管理(DelegatingFilterProxy) -->
<beans:bean id="BackendSessionFilter" class="com.Lin.jianji.filter.LoginFilter">
</beans:bean>
接下来就是LoginFilter.java文件的编写
package com.Lin.jianji.filter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Pattern;
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 com.google.common.base.Strings;
public class LoginFilter implements Filter {
/** 要检查的 session 的名称 */
private String sessionKey;
/** 需要排除(不拦截)的URL的正则表达式 */
private Pattern excepUrlPattern;
/** 检查不通过时,转发的URL */
private String forwardUrl;
public void init(FilterConfig cfg) throws ServletException {
sessionKey = cfg.getInitParameter("sessionKey");
String excepUrlRegex = cfg.getInitParameter("excepUrlRegex");
if (!Strings.isNullOrEmpty(excepUrlRegex)) {
excepUrlPattern = Pattern.compile(excepUrlRegex);
}
forwardUrl = cfg.getInitParameter("forwardUrl");
if(Strings.isNullOrEmpty(forwardUrl)){
forwardUrl="/";
}
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
// 如果 sessionKey 为空,则直接放行
if (Strings.isNullOrEmpty(sessionKey)) {
chain.doFilter(req, res);
return;
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String servletPath = request.getServletPath();
if(!Strings.isNullOrEmpty(request.getPathInfo())){
servletPath = servletPath + request.getPathInfo();
}
// 如果请求的路径与forwardUrl相同,或请求的路径是排除的URL时,则直接放行
if (servletPath.equals(forwardUrl) || excepUrlPattern.matcher(servletPath).matches()) {
chain.doFilter(req, res);
return;
}
Object sessionObj = request.getSession().getAttribute(sessionKey);
// 如果Session为空,则跳转到指定页面
if (sessionObj == null) {
String contextPath = request.getContextPath();
String redirect = servletPath + "?" + Strings.nullToEmpty(request.getQueryString());
if (request.getHeader("x-requested-with") != null
&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
// 如果是ajax请求响应头会有,x-requested-with
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.addHeader("sessionStatus","false");
return;
}
response.sendRedirect(contextPath + forwardUrl + "?redirect="
+ URLEncoder.encode(redirect, "UTF-8"));
} else {
chain.doFilter(req, res);
}
}
public void destroy() {
}
}
我的登录界面index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 拼装当前网页的相对路径
request.getContextPath():解决相对路径的问题,可返回站点的根路径
request.getScheme():这是获取协议,如常用的http协议
request.getServerName():服务器的名字
request.getServerPort():这是服务器端口号
-->
<%
session.removeAttribute("BACKEND_SESSION_USER_KEY");
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
response.setHeader( "Pragma", "no-cache" );
response.addHeader( "Cache-Control", "must-revalidate" );
response.addHeader( "Cache-Control", "no-cache" );
response.addHeader( "Cache-Control", "no-store" );
response.setDateHeader("Expires", 0);
%>
<title>Insert title here</title>
<script type='text/javascript'>var basePath = '<%=basePath%>';</script>
<script type="text/javascript" src="../resources/index.js"></script>
<link rel="stylesheet" type="text/css"
href="../resources/easyUI/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../resources/easyUI/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../resources/easyUI/css/demo.css">
<script type="text/javascript" src="../resources/easyUI/jquery.min.js"></script>
<script type="text/javascript" src="../resources/easyUI/jquery.easyui.min.js"></script>
</head>
<body>
<!-- <div style="margin:20px 0;"></div> -->
<!-- <div class="easyui-panel" title="Login" style="width:100%;max-width:400px;padding:30px 60px;">
<form id="LoginForm" method="post">
<div style="margin-bottom:20px">
<input class="easyui-textbox" type = "text" id = "u_username" name="username" style="width:100%" data-options="label:'用户名:',required:true">
</div>
<div style="margin-bottom:20px">
<input class="easyui-textbox" type = "password" id = "u_password" name="password" style="width:100%" data-options="label:'密码:',required:true">
</div>
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">Submit</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">Clear</a>
</div>
</div> -->
<div style="margin:20px 0;"></div>
<div class="easyui-panel" style="width:400px;padding:50px 60px" title="Login">
<form id="LoginForm" method="post">
<div style="margin-bottom:20px">
<input class="easyui-textbox" prompt="Username" id = "u_username" name="username" iconWidth="28" style="width:100%;height:34px;padding:10px;">
</div>
<div style="margin-bottom:20px">
<input class="easyui-passwordbox" prompt="Password" id = "u_password" name="password" iconWidth="28" style="width:100%;height:34px;padding:10px">
</div>
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">Submit</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">Clear</a>
</div>
</div>
<div id="viewer"></div>
<script type="text/javascript">
$('#u_password').passwordbox({
inputEvents: $.extend({}, $.fn.passwordbox.defaults.inputEvents, {
keypress: function(e){
var char = String.fromCharCode(e.which);
$('#viewer').html(char).fadeIn(200, function(){
$(this).fadeOut();
});
}
})
})
</script>
<style>
#viewer{
position: relative;
padding: 0 60px;
top: -70px;
font-size: 54px;
line-height: 60px;
}
</style>
<!-- <script>
function submitForm(){
//$.trim():去掉字符串起始和结尾的空格
var username = $.trim($("#u_username").val());
var password = $("#u_password").val();
if(username == ""){
alert("用户名不能为空!");
loginForm.u_username.focus();
return false;
}else if(username != null && password == null){
//用户名不为空,密码为空时,直接用表单的id查找input标签的id,直接value赋值
LoginForm.u_username.value = username;
//重新聚焦到密码输入框
loginForm.u_password.focus();
return false;
}else{
$.ajax({
cache: true,
type: "POST",
url : basePath + 'UserMsg/login.action',
data:"username="+username+"&password="+password,
success : function(date){
if(data.success){
window.location.href= basePath + "resources/welcome.jsp";
}else{
alert(data.message);
}
},
erron : function(request){
alert("Connection error");
}
});
}
}
function clearForm(){
$('#LoginForm').form('clear');
}
</script> -->
</body>
</html>
welcome.jsp页面如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
response.setHeader( "Pragma", "no-cache" );
response.addHeader( "Cache-Control", "must-revalidate" );
response.addHeader( "Cache-Control", "no-cache" );
response.addHeader( "Cache-Control", "no-store" );
response.setDateHeader("Expires", 0);
%>
<html>
<head>
<!--js全局变量,权限管理start-->
<script type='text/javascript'>
var basePath = '<%=basePath%>';
(function(){
USER_SESSION = <%=session.getAttribute("BACKEND_SESSION_USER_KEY")%>;
BACKEND_SESSION_USER_AREA_KEY = <%=session.getAttribute("BACKEND_SESSION_USER_AREA_KEY")%>;
if(USER_SESSION == null){
window.location.href = "<%=basePath%>" +"resources/index.jsp";
}
})();
var isDeleteState = '0';
var login_Account = {
loginAccount : USER_SESSION.username
};
var isYes = 'No';
var MyDataStatic;
var textData;
</script>
<!--js全局变量,权限管理end-->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<label>某某到此一访问^V^ ^V^ ^V^</label>
</body>
</html>
我的UserMsgController类如下
package com.Lin.jianji.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.Lin.jianji.utils.*;
import com.Lin.jianji.entity.UserMsg;
import com.Lin.jianji.service.UserMsgService;
@Controller
@RequestMapping(value = "/UserMsg/*")
public class UserMsgController {
private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
@Autowired
private UserMsgService service;
@RequestMapping(value = "search.action")
public @ResponseBody Map<String, ? extends Object> search(
@RequestParam int page, @RequestParam int rows,
@RequestParam(required = false) String exampleJson) {
try {
UserMsg item = new UserMsg();
if (!Strings.isNullOrEmpty(exampleJson)) {
item = gson.fromJson(exampleJson, new TypeToken<UserMsg>() {
}.getType());
}
int total = service.count(item);
List<UserMsg> items = service.search((page-1)*rows, rows, item);
return EasyUIReturns.mapOK(items, total, "成功!");
} catch (Exception e) {
LogUtil.error("失败:", e);
return EasyUIReturns.mapError("失败" + e.getMessage());
}
}
@RequestMapping(value = "create.action")
public @ResponseBody Map<String, ? extends Object> create(@RequestBody UserMsg item) {
try {
service.save(item);
return EasyUIReturns.mapOK(item.getId(), "成功!");
} catch (Exception e) {
LogUtil.error("失败!", e);
return EasyUIReturns.mapError("失败:" + e.getMessage());
}
}
@RequestMapping(value = "update.action")
public @ResponseBody Map<String, ? extends Object> update(@RequestBody UserMsg item) {
try {
service.update(item);
return EasyUIReturns.mapOK("成功!");
} catch (Exception e) {
LogUtil.error("失败:", e);
return EasyUIReturns.mapError("失败:" + e.getMessage());
}
}
@RequestMapping(value = "delete.action")
public @ResponseBody Map<String, ? extends Object> delete(@RequestBody UserMsg item) {
try {
service.delete(item);
return EasyUIReturns.mapOK("成功!");
} catch (Exception e) {
LogUtil.error("失败!", e);
return EasyUIReturns.mapError("失败:" + e.getMessage());
}
}
//登录校验
@RequestMapping(value = "login.action")
public @ResponseBody Map<String, ? extends Object> login(HttpSession session, String username, String password) {
try {
//把用户名和密码
UserMsg userMsg = service.getUserByUserNameAndPassword(username, password);
session.setAttribute(Constants.BACKEND_SESSION_USER_KEY, gson.toJson(userMsg));
return EasyUIReturns.mapOK("登录成功!");
}catch(Exception e){
LogUtil.error("账号和密码不对!",e);
return EasyUIReturns.mapError("账号和密码不对!:" + e.getMessage());
}
}
//退出登录
@RequestMapping(value = "logout.action")
public @ResponseBody Map<String, ? extends Object> logout(HttpSession session) {
try {
session.removeAttribute(Constants.BACKEND_SESSION_USER_KEY);
session.invalidate();
return EasyUIReturns.mapOK("退出成功!");
}catch(Exception e){
LogUtil.error("失败!", e);
return EasyUIReturns.mapError("失败:" + e.getMessage());
}
}
}
UserMsgController里面的登录校验的BACKEND_SESSION_USER_KEY是我Constants.java常量类
package com.Lin.jianji.utils;
/**
* 此类是常量类
* @author Administrator
*
*/
public class Constants {
public static final String BACKEND_SESSION_USER_KEY = "BACKEND_SESSION_USER_KEY";
public static final Integer WATER_COMPANY_ID = 98;
public static final String SUPER_USER = "超级管理员";
public static final String DIRECT_AFTER_SALE_FORM = "DIRECT_ASF_NO";
public static final String ORDER_STATE_DATA_TYPE_CODE = "ORDER_STATE";
public static final String BACKEND_SESSION_USER_AREA_KEY = "BACKEND_SESSION_USER_AREA_KEY";
}
运行结果截图
欢迎交流,互相学习