springMVC和Shiro框架整合使用简单示例

一、目录结构

首先是目录结构如图:



二、pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo</groupId>
  <artifactId>ShiroDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ShiroDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>  
         <groupId>commons-collections</groupId>  
         <artifactId>commons-collections</artifactId>  
         <version>3.2.1</version>  
     </dependency>  
     <dependency>  
         <groupId>net.sf.ehcache</groupId>  
         <artifactId>ehcache-core</artifactId>  
         <version>2.6.9</version>  
     </dependency>  
  
     <dependency>  
         <groupId>org.apache.shiro</groupId>  
         <artifactId>shiro-spring</artifactId>  
         <version>1.2.3</version>  
         
     </dependency>  
  
     <dependency>  
         <groupId>org.apache.shiro</groupId>  
         <artifactId>shiro-ehcache</artifactId>  
         <version>1.2.3</version>  
     </dependency>  
  
     <dependency>  
         <groupId>org.apache.shiro</groupId>  
         <artifactId>shiro-quartz</artifactId>  
         <version>1.2.3</version>  
     </dependency>  
     <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.2.7.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.6.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.5</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.0.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
		<dependency>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
		<dependency>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-surefire-plugin</artifactId>
			<version>2.12.4</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.0.3.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
		<dependency>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.1</version>
		</dependency>
     
  </dependencies>
  <build>
    <finalName>ShiroDemo</finalName>
  </build>
</project>


三、applicationCotext.xml文件


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
						http://www.springframework.org/schema/mvc
						http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	<!-- 它背后注册了很多用于解析注解的处理器,其中就包括<context:annotation-config/>配置的注解所使用的处理器 -->
	<!-- 所以配置了<context:component-scan base-package="">之后,便无需再配置<context:annotation-config> -->
	<context:component-scan base-package="com.gentlehu.shiro"/>
	
	<!-- 启用SpringMVC的注解功能,它会自动注册HandlerMapping、HandlerAdapter、ExceptionResolver的相关实例 -->
	<mvc:annotation-driven/>

	<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的MyRealm.java -->
	<bean id="myRealm" class="com.gentlehu.shiro.MyRealm"/>

	<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
	<!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
	<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="myRealm"/>
	</bean>

	<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
	<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager"/>
		
		<!-- anon:它对应的过滤器里面是空的,什么都没做-->
		<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
		<property name="filterChainDefinitions">
			<value>
				/default/login=anon <!-- 任何人都可以访问,匿名 -->
				/main**=authc 	<!-- 需要登录 -->
				/user/info**=authc <!-- 需要登录 -->
				/admin/listUser**=authc,perms[admin:manage]<!-- 已经登录并且还要有admin:manage权限才可以访问 -->
			</value>
		</property>
	</bean>

	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

	<!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
	<!-- 配置以下两个bean即可实现此功能 -->
	<!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->
	<!-- 由于本例中并未使用Shiro注解,故注释掉这两个bean -->
	<!-- 
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager"/>
	</bean>
	 -->
	 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	 	<property name="prefix" value="/"></property>
	 	<property name="suffix" value=".jsp"></property>
	 </bean>
</beans>

四、MyRealm.java

package com.gentlehu.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;



public class MyRealm extends AuthorizingRealm {

	/**
	 * 授权
	 */
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String currentUsername = (String)super.getAvailablePrincipal(principals); 
		
//      List<String> roleList = new ArrayList<String>();  
//      List<String> permissionList = new ArrayList<String>();  
//      //从数据库中获取当前登录用户的详细信息  
//      User user = userService.getByUsername(currentUsername);  
//      if(null != user){  
//          //实体类User中包含有用户角色的实体类信息  
//          if(null!=user.getRoles() && user.getRoles().size()>0){  
//              //获取当前登录用户的角色  
//              for(Role role : user.getRoles()){  
//                  roleList.add(role.getName());  
//                  //实体类Role中包含有角色权限的实体类信息  
//                  if(null!=role.getPermissions() && role.getPermissions().size()>0){  
//                      //获取权限  
//                      for(Permission pmss : role.getPermissions()){  
//                          if(!StringUtils.isEmpty(pmss.getPermission())){  
//                              permissionList.add(pmss.getPermission());  
//                          }  
//                      }  
//                  }  
//              }  
//          }  
//      }else{  
//          throw new AuthorizationException();  
//      }  
//      //为当前用户设置角色和权限  
//      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
//      simpleAuthorInfo.addRoles(roleList);  
//      simpleAuthorInfo.addStringPermissions(permissionList); 
		
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		
		if(null!=currentUsername && currentUsername.equals("admin")){  
			//添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色    
			simpleAuthorInfo.addRole("admin");  
			//添加权限  
			simpleAuthorInfo.addStringPermission("admin:manage");  
			System.out.println("已为用户[admin]赋予了[admin]角色和[admin:manage]权限");  
			return simpleAuthorInfo;  
		} 
		return simpleAuthorInfo;  
	
		//若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址  
		//详见applicationContext.xml中的<bean id="shiroFilter">的配置  
//		return null;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		
		 //获取基于用户名和密码的令牌  
        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
        System.out.println("MyRealm.doGetAuthenticationInfo.token="+token); 
        
//      User user = userService.getByUsername(token.getUsername());  
//      if(null != user){  
//          AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname());  
//          this.setSession("currentUser", user);  
//          return authcInfo;  
//      }else{  
//          return null;  
//      }  
        //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息  
        //说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)  
        //这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证  
        if("admin".equals(token.getUsername())){  
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("admin", "admin", this.getName());  
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", "admin");
            return authcInfo;  
        }else if("user".equals(token.getUsername())){  
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("user", "user", this.getName());  
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", "user");
            return authcInfo;  
        }  
        //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常  
		return null;
	}

}

五、DefaultController.java

package com.gentlehu.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/default")
public class DefaultController  {
	
	@RequestMapping("/login")
	public String login(String username,String password,Model model){
		 UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		 token.setRememberMe(true);
		 System.out.println("DefaultController.login#token="+token);
		 
		 Subject currentUser = SecurityUtils.getSubject();
		 
		 try {  
	            //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查  
	            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应  
	            //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法  
	            System.out.println("user[" + username + "]do login checking");  
	            currentUser.login(token);  
	            System.out.println("user[" + username + "]authentication success");  
	           
	        }catch(UnknownAccountException uae){  
	            System.out.println("user[" + username + "]UnknownAccountException");  
	            model.addAttribute("error_msg", "UnknownAccountException");
	        }catch(IncorrectCredentialsException ice){  
	        	System.out.println("user[" + username + "]IncorrectCredentialsException");
	            model.addAttribute("error_msg", "IncorrectCredentialsException");  
	        }catch(LockedAccountException lae){  
	        	System.out.println("user[" + username + "]LockedAccountException"); 
	            model.addAttribute("error_msg", "LockedAccountException");  
	        }catch(ExcessiveAttemptsException eae){  
	        	System.out.println("user[" + username + "]ExcessiveAttemptsException");  
	            model.addAttribute("error_msg", "ExcessiveAttemptsException");  
	        }catch(AuthenticationException ae){  
	            //注意:这个必须放在后面,因为这个异常可以处理所有认证失败的情况
	            model.addAttribute("error_msg", "authentication faild");  
	        }  
	        //验证是否登录成功  
	        if(currentUser.isAuthenticated()){  
	            System.out.println("user[" + username + "]authentication success"); 
	            return "main";
	        }  
	        token.clear(); 
	        return "login";
		 
	}
	@RequestMapping("/logout")
	public String logout(){
		SecurityUtils.getSubject().logout();
		return "redirect:login";
	}
}


六、UserController.java

package com.gentlehu.shiro.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/user")
public class UserController {
	
	
	@RequestMapping("/info")
	public String info(HttpServletRequest request,Model model){
		String currentUser = (String) request.getSession().getAttribute("currentUser");
		System.out.println("currentUser"+currentUser);
		model.addAttribute("currentUser", currentUser);
		return "user/info.jsp";
	}
}

七、login.jsp


<%@ page language="java" pageEncoding="UTF-8"%>

<html>
<body>
<div style="color:red; font-size:22px;">${error_msg}</div>

<form action="login" method="GET">
	姓名:<input type="text" name="username"/><br/>
	密码:<input type="text" name="password"/><br/>
	<input type="submit" value="确认"/>
</form>
</body>
</html>


八、main.jsp


<%@ page language="java" pageEncoding="UTF-8"%>

<html>
<body>

普通用户可访问<a href="/ShiroDemo/user/info.jsp" target="_blank">用户信息页面</a>
<br/>
<br/>
管理员可访问<a href="/ShiroDemo/admin/listUser.jsp" target="_blank">用户列表页面</a>
<br/>
<br/>
<a href="/ShiroDemo/default/logout" target="_blank">Logout</a>
</body>
</html>


九、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- Web容器加载顺序ServletContext-context-param-listener-filter-servlet -->

	<!-- 指定Spring的配置文件 -->
	<!-- 否则Spring会默认从WEB-INF下寻找配置文件,contextConfigLocation属性是Spring内部固定的 -->
	<!-- 通过ContextLoaderListener的父类ContextLoader的第120行发现CONFIG_LOCATION_PARAM固定为contextConfigLocation -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- 防止发生java.beans.Introspector内存泄露,应将它配置在ContextLoaderListener的前面 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	
	<!-- 实例化Spring容器 -->
	<!-- 应用启动时,该监听器被执行,它会读取Spring相关配置文件 -->

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>


	<filter>
		<filter-name>SpringEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>SpringEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->
	<!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->
	<!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->
	<!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- SpringMVC核心分发器 -->
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- Session超时20分钟(零或负数表示会话永不超时) -->
	<!-- 
	<session-config>
		<session-timeout>20</session-timeout>
	</session-config>
	 -->

	<error-page>
		<!-- 401表示权限被拒绝 -->
		<error-code>401</error-code>
		<location>/401.jsp</location>
	</error-page>
	<error-page>
		<error-code>405</error-code>
		<location>/405.html</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/404.jsp</location>
	</error-page>
</web-app>




其他页面没什么内容。就是显示我是哪个界面。
整体过程就是准备好这些文件之后,maven install . Run  As MyEclipse Server Application.
然后访问 http://localhost:8080/ShiroDemo/login.jsp
没有登录的用户只能访问login.jsp.访问其他页面会报401错误。
1.使用user身份登录
使用usename=user&password=user登录之后,会自动跳转mian.jsp页面。
然后只能点击用户信息页面链接和logou。点击其他一样会报401错误。

2.使用admin身份登录
使用username=admin&password=admin登录之后,也会自动跳转main.jsp页面。
这时候所有链接都可以访问。

其他要注意的都在代码的注释里了。这里不在敖述。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值