ssm项目整合shiro
时间: 2023-11-30 09:04:09 浏览: 98
SSM-Shiro.zip_shiro ssm 整合_ssm web shiro%2_ssm+shiro_ssm590.com_
SSM项目整合Shiro的步骤如下:
1. 引入Shiro的依赖,可以在pom.xml文件中添加以下代码:
```xml
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.0</version>
</dependency>
```
2. 在Spring配置文件中配置Shiro的相关信息,例如Shiro的安全管理器、Shiro的过滤器链等。可以在applicationContext.xml文件中添加以下代码:
```xml
<!-- 配置Shiro的安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<!-- 配置Shiro的自定义Realm -->
<bean id="myRealm" class="com.example.shirodemo.realm.MyRealm">
<property name="credentialsMatcher" ref="hashedCredentialsMatcher"/>
</bean>
<!-- 配置Shiro的密码匹配器 -->
<bean id="hashedCredentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<property name="hashIterations" value="2"/>
</bean>
<!-- 配置Shiro的过滤器链 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="successUrl" value="/index"/>
<property name="unauthorizedUrl" value="/unauthorized"/>
<property name="filterChainDefinitions">
<value>
/login = anon
/logout = logout
/** = authc
</value>
</property>
</bean>
```
3. 创建自定义Realm,继承org.apache.shiro.realm.Realm接口,并实现其中的方法。可以创建一个MyRealm类,代码如下:
```java
public class MyRealm implements Realm {
@Autowired
private UserService userService;
@Override
public String getName() {
return "myRealm";
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}
```
4. 在Controller中使用Shiro进行权限控制。可以在UserController中添加以下代码:
```java
@Controller
public class UserController {
@RequestMapping("/user/list")
@RequiresPermissions("user:list")
public String list() {
return "user/list";
}
@RequestMapping("/user/add")
@RequiresPermissions("user:add")
public String add() {
return "user/add";
}
@RequestMapping("/user/edit")
@RequiresPermissions("user:edit")
public String edit() {
return "user/edit";
}
@RequestMapping("/user/delete")
@RequiresPermissions("user:delete")
public String delete() {
return "user/delete";
}
}
```
以上是SSM项目整合Shiro的基本步骤,可以根据具体需求进行修改和扩展。
阅读全文