依赖:spring-context,spring-MVC,shiro-core,shiro-spring,shiro-web

实话实说:web.xml,spring,springmvc配置文件好难

大致效果

代码结构(使用web骨架构建)

pom.xml

<dependencies>

        <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>

实体类User

public class User {
private int id;
private String username;
private String password; public User() {
} public User(String username, String password) {
this.username = username;
this.password = password;
} public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

自定义Realm 域  类(加盐)

public class CustomRealm extends AuthorizingRealm {    
  @Override //授权
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
//通过用户名username,获取角色
Set<String> roles=getRolesByUsername(username);
//通过用户名username,获取角色de权限
Set<String> permissions=getPermissionsByUsrname(username); //返回AuthorizationInfo对象,先创建
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//设置授权 ---角色
info.setRoles(roles);
//设置授权 ---权限
info.setStringPermissions(permissions);
return info;
} private Set<String> getPermissionsByUsrname(String username) {
//也是从数据库去,这里写死
Set<String> permissions=new HashSet<>();
permissions.add("user:select");
permissions.add("user:update");
permissions.add("user:delete");
permissions.add("user:insert");
return permissions;
} private Set<String> getRolesByUsername(String username) {
//也是从数据库去,这里写死
Set<String> roles=new HashSet<>();
roles.add("admin");
roles.add("user");
return roles;
} @Override //认证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
System.out.println("用户名:"+username);
String pwd=getPwdByUsername(username);
System.out.println("密 码:"+pwd);
if (pwd==null){
return null;
}
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,pwd,"customRealmSecret");
     info.setCredentialsSalt(ByteSource.Util.bytes("salt"));
return info;
} private String getPwdByUsername(String username) {
Map<String,String> map=new HashMap<>();
//加密的密码admin再加盐 --->c657540d5b315892f950ff30e1394480
map.put("admin","c657540d5b315892f950ff30e1394480");
super.setName("customRealmSecret");
return map.get(username);
}
}

控制器controller

@Controller
public class UserController {
@ResponseBody
@RequestMapping(value = "/subLogin",method = RequestMethod.POST,produces="application/json;charset=utf-8")
public String subLogin(User user){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword()); try {
subject.login(token);
} catch (AuthenticationException e) {
return e.getMessage();
}
return "登录成功";
}
}

login.htnl

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>shiro登录页面</title>
</head>
<body>
<form action="subLogin" method="post">
<input type="text" name="username"/><br/>
<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>

重头戏:配置文件

web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener> <filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter> <filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="login.html"/>
<property name="unauthorizedUrl" value="403.html"/>
<!--过滤器页面-->
<property name="filterChainDefinitions">
<value>
/subLogin=anon <!--提交登录的url也不需要认证-->
/login.html=anon <!--不需要认证,也可以访问-->
/*=authc <!--需要认证,才可以访问-->
</value>
</property>
</bean> <!--创建securityManager对象-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="realm"/>
</bean> <bean class="com.imooc.shiro.realm.CustomRealm" id="realm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
id="credentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<property name="hashIterations" value="1"/>
</bean>
</beans>

springmvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.imooc.controller"/>
<mvc:annotation-driven/>
<!--排除静态文件-->
<mvc:resources mapping="/*" location="/"/> </beans>

个人总结下啦:

  难在配置,特别有个坑在spring的bean里面,要的是web的

  <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  而我配少了个web
  <bean id="securityManager" class="org.apache.shiro.mgt.DefaultWebSecurityManager">
哎,这就搞了我一晚头大,买了个表,顶
还有就是,理解好,shiro的
shiroFilter,
DefaultWebSecurityManager,
CustomRealm(自定义的域),
HashedCredentialsMatcher(加密),
也就七七八八了

shiro学习(四、shiro集成spring+springmvc)的更多相关文章

  1. Apache Shiro学习-2-Apache Shiro Web Support

     Apache Shiro Web Support  1. 配置 将 Shiro 整合到 Web 应用中的最简单方式是在 web.xml 的 Servlet ContextListener 和 Fil ...

  2. Drools 7.4.1.Final参考手册(十四)集成Spring

    集成Spring Drools 6.0重要变更 Drools Spring集成经历了与Drools 6.0的变化完全一致的改造. 以下是一些主要的变化: T*推荐的Drools Spring的前缀已经 ...

  3. javaweb各种框架组合案例(四):maven+spring+springMVC+spring data jpa(hibernate)【失败案例】

    一.失败案例 1. 控制台报错信息 严重: Exception sending context initialized event to listener instance of class org. ...

  4. shiro与Web项目整合-Spring+SpringMVC+Mybatis+Shiro(八)

    Jar包

  5. shiro基础学习(四)—shiro与项目整合

    一.认证 1.配置web.xml   2.配置applicationContext.xml      在applicationContext.xml中配置一个bean,ID和上面的过滤器的名称一致. ...

  6. Shiro学习

    Shiro学习资源 Shiro官网,http://shiro.apache.org/index.html 学习网站链接,http://blog.java1234.com/blog/articles/4 ...

  7. Quartz学习——SSMM(Spring+SpringMVC+Mybatis+Mysql)和Quartz集成详解(四)

    当任何时候觉你得难受了,其实你的大脑是在进化,当任何时候你觉得轻松,其实都在使用以前的坏习惯. 通过前面的学习,你可能大致了解了Quartz,本篇博文为你打开学习SSMM+Quartz的旅程!欢迎上车 ...

  8. (转) Quartz学习——SSMM(Spring+SpringMVC+Mybatis+Mysql)和Quartz集成详解(四)

    http://blog.csdn.net/u010648555/article/details/60767633 当任何时候觉你得难受了,其实你的大脑是在进化,当任何时候你觉得轻松,其实都在使用以前的 ...

  9. Shiro学习(12)与Spring集成

    Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成. 在示 ...

随机推荐

  1. Flutter移动电商实战 --(8)dio基础_伪造请求头获取数据

    在很多时候,后端为了安全都会有一些请求头的限制,只有请求头对了,才能正确返回数据.这虽然限制了一些人恶意请求数据,但是对于我们聪明的程序员来说,就是形同虚设.这篇文章就以极客时间 为例,讲一下通过伪造 ...

  2. ansible的剧本

    ansible的playbook的介绍-yaml ansible的playbook是使用yaml语言写的 YAML标记语言介绍YAML是一个可读性高的用来表达资料序列的格式.YAML参考了其他多种语言 ...

  3. Android通讯-webSocket

    概述 上一篇简单的认识了Socket以及他的使用,在学习过程中看到了WebSocket的身影,于是乎百度了一把,这货也可以做全双工的网络通讯,而且是html5提出来的新东西!程序员嘛!就是要对新的东西 ...

  4. 浅谈WebView在新窗口浏览网页(setSupportMultipleWindows()与onCreateWindow()关系)

    一,写在前面 我们平常使用电脑浏览器浏览网页可能会有三种方式: 1.新窗口 2.当前窗口种的新选项卡 3.当前选项卡或者窗口 我们知道在电脑系统中同一时间可以开启多个相同的进程,就像你可以同时登陆2个 ...

  5. SQL-W3School-基础:SQL 简介

    ylbtech-SQL-W3School-基础:SQL 简介 1.返回顶部 1. SQL 是用于访问和处理数据库的标准的计算机语言. 什么是 SQL? SQL 指结构化查询语言 SQL 使我们有能力访 ...

  6. TP5连接数据库和phpstrom连接数据库(宝塔面板数据库连接)

    1.编译器:phpstrom 框架:TP5 服务器面板:宝塔面板 2.我遇到的核心问题:数据库.用户名.密码均正确但是无法连接, 使用宝塔面板的都知道phpmyadmin的端口号是888,注意注意这个 ...

  7. an extra named object property

    Grunt supports the ability to split each task configuration into several separate configurations all ...

  8. mysql 截取字符函数substring(param1,param2,param3) 的用法

    substring(paramter1,paramter2,paramter3) 截取字段长度 paramter1  被截取的字段paramter2 从第几位开始截取,负数表示从末尾开始数,的位数开始 ...

  9. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) (转)

    http://www.cnblogs.com/liqingwen/p/6640861.html 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) 本系列的 GitHub地址:ht ...

  10. CetOS 服务不支持 chkconfig 的解决方法

    今天在添加Elasticsearch系统自动启动服务的时候,提示 “服务 elasticsearch 不支持 chkconfig ”,如下图: 后来查找了下原因,是脚本编写的不符合规范,缺少关键的前三 ...