SpringMVC用户登录和拦截器简单应用增删改查

在学习SpringMVC和Spring整合的时候做了一个小练习,对员工进行报道(增)、修改、升迁、离职等操作,操作的时候用户必须实在登录状态下才能进行,这时候就用到了拦截器。

通过查阅资料,整理了一下,并简单进行了一下测试,当用户没有登录进行操作时,会自动跳转到login.jsp,也就是登录页面,部分程序如下:

自定义拦截器Login实现HandlerInterceptor接口,重写HandlerInterceptor接口的方法

package com.hygj.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;

public class Login implements HandlerInterceptor {
	
	private List<String> excludedUrls;

	public List<String> getExcludedUrls() {
		return excludedUrls;
	}

	public void setExcludedUrls(List<String> excludedUrls) {
		this.excludedUrls = excludedUrls;
	}

	public void afterCompletion(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse, Object obj, Exception exc)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
			Object obj, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj) throws Exception {
		//demo_13/emp/XXX 获取控制层方法
		String requestUri = request.getRequestURI();

		//遍历获取不做拦截的路径
        for (String url : excludedUrls) {
        	//如果是以/checkLogin结尾的请求不做拦截处理
            if (requestUri.endsWith(url)) {
                return true;
            }
        }
        HttpSession session = request.getSession();
        //判断用户是否登录
        if (session.getAttribute("userUid") == null) {
        	//如果没有登录,则跳转到login.jsp
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } 
      
        return true;
	}

}
SpringMVC容器配置

<!--配置拦截器, 如果多个拦截器,则顺序执行 -->
	<mvc:interceptors>  
    	<mvc:interceptor>
	    	<!-- 拦截器拦截的URL格式 ,如果不配置或/**,将拦截所有的Controller-->
	        <mvc:mapping path="/**" />
	        <!-- 处理拦截的具体实现类 -->
	        <bean class="com.hygj.interceptor.Login">
	        	<!-- excludedUrls是要放行的url集合 -->
		        <property name="excludedUrls">
			        <list>
			        	<value>/checkLogin</value>
			        </list>
		        </property>
	        </bean>
    	</mvc:interceptor>  
	</mvc:interceptors>  

测试用户名为:admin,密码为1

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>login</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<c:if test="${err == '1'}">
	<script type="text/javascript">
		alert("uid或pwd错误");
	</script>
</c:if>
  </head>
  
  <body>
  <form method="post" action="${pageContext.request.contextPath}/emp/checkLogin">
    uid:<input type="text" id="userUid" name="userUid" value="${userUid}"><br><br>
    pwd:<input type="text" id="userPwd" name="userPwd"><br><br>
    <input type="submit" value="Login">
  </form>
  </body>
</html>

控制层

checkLogin()判断用户名和密码,登录成功则跳转到showEmp.jsp

package com.hygj.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hygj.pojo.Employee;
import com.hygj.pojo.EmployeeHistroy;
import com.hygj.pojo.Pager;
import com.hygj.service.iface.IEmpService;

@Controller
@RequestMapping("/emp")
public class EmpController {

	@Resource(name="empService")
	private IEmpService empService;
	public void setEmpService(IEmpService empService) {
		this.empService = empService;
	}
	
	@RequestMapping("/checkLogin")
	public String checkLogin(HttpServletRequest request){
		String userUid = request.getParameter("userUid");
		String userPwd = request.getParameter("userPwd");
		if("admin".equals(userUid) && "1".equals(userPwd)){
			HttpSession session = request.getSession();
			session.setAttribute("userUid", userUid);
			return "redirect:showEmp";
		}else{
			request.setAttribute("err", 1);
			return "login";
		}
	}
	@RequestMapping("/show")
	public String showEmp(HttpServletRequest request){
		//省略
		return "showEmp";
	}
}

showEmp.jsp,因为省略了数据库操作,showEmp.jsp只显示succ表示登录成功

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>showEmp</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  succ
  </body>
</html>


全部源码下载:http://download.csdn.net/download/users0001/10123920


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值