企业中老项目还在使用ssm框架。简单讲ssm整合shiro的思路写一下
(1)创建一个maven的web工程
(2)ssm整合到web工程
--pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wmd</groupId>
<artifactId>qy151-ssm-shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
<dependencies>
<!--spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.0</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--mybatis和spring整合的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--druid连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!--jackson java对象转换为json对象 @ResponseBody-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<!--servlet-api依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--servlet-jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<!--mybatis自动生成器依赖-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
<!--log4j依赖-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--分页拦截器依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
<!--文件上传依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--阿里云oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!--cglib-->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
</dependencies>
</project>
--spring配置文件
<?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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--包扫描-->
<context:component-scan base-package="com.wmd.controller"/>
<!--开启aop注解-->
<aop:aspectj-autoproxy/>
<!--开启注解-->
<mvc:annotation-driven/>
<!--静态资源的放行-->
<mvc:default-servlet-handler/>
<!--数据源配置-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<!--驱动名称-->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/my0424?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="12222222"/>
<!--初始化连接池的个数-->
<property name="initialSize" value="5"/>
<!--至少的个数-->
<property name="minIdle" value="5"/>
<!--最多的个数-->
<property name="maxActive" value="10"/>
<!--最长等待时间单位毫秒-->
<property name="maxWait" value="3000"/>
</bean>
<!--sqlSessionFactory 整合mybatis-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<!--设置mybatis映射文件的路径-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
</bean>
<!--为dao接口生成代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--为com.ykq.dao包下的接口生成代理实现类-->
<property name="basePackage" value="com.wmd.dao"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--整合shiro的配置内容-->
<!--①SecurityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="realm"/>
</bean>
<!--创建自定义realm类对象-->
<bean id="realm" class="com.wmd.realm.MyRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!--创建密码匹配器-->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="1024"/>
</bean>
<!--shiro过滤工厂: 设置过滤的规则-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--如果没有登录,跳转的路径-->
<property name="loginUrl" value="/login.jsp"/>
<!--没有权限,跳转的路径-->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filterChainDefinitions">
<value>
/login=anon
/**=authc
</value>
</property>
</bean>
</beans>
web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--当tomcat启动时创建DipatcherServlet 默认当访问controller路径时创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--加载spring配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<!-- shiro过滤器的代理-->
<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>
</web-app>
在controller层试下
@PostMapping("/login")
public String login(String username,String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
try {
subject.login(token);
return "redirect:/success.jsp";
}catch (Exception e){
return "redirect:/login.jsp";
}
}
login.jsp登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form method="post" action="/login">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
entity层
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer userid;
private String username;
private String userpwd;
private String sex;
private String address;
private String salt;
}
server层
public class UserService {
public User findByusername(String username) {
return null;
}
public List<String> findPowerByUsername(String username) {
List<String> list = new ArrayList<>();
if("admin".equals(username)){
list.add("user:insert");
list.add("user:update");
list.add("user:delete");
list.add("user:select");
}else if("zhangsan".equals(username)){
list.add("user:insert");
}
return list;
}
}
2.1 进入主页后,不同的用户可以看到不同的内容。
可以在jsp中获取当前登录者的账号
上面只是在网页中根据不同用户显示不同的菜单,这种方式只能防君子不能防小人。
有两种解决办法
(1)拦截器---获取请求路径 然后根据你的路径判断当前用户是否具有该权限。
(2)spring整合shiro时提供了一个注解:可以加载相应方法上。
1.开启shiro注解
<!-- 启动Shrio的注解 -->
<bean id="lifecycleBeanPostProcessor"
class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<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>
2.使用shiro注解
@RequiresPermissions(value = {"/user/query","/user/aaa"},logical= Logical.OR)
我们学习过全局异常处理:
3. ssm整合shiro完成前后端分离
所谓前后端完全分离:后端响应的都是json数据,而不再是网页。
1. 登录成功或者失败应该返回json数据
2. 当未登录时返回的也是json数据
3. 访问未授权的资源,也要分会json。
3.1 登录成功或者失败应该返回json数据
修改登录接口
@RestController
public class Hellocontroller {
@RequestMapping(value = "/login")
public CommonResult hello(String username, String userpwd){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token =new UsernamePasswordToken(username,userpwd);
try {
subject.login(token);
return new CommonResult(2000,"登录成功",null);
} catch (AuthenticationException e) {
e.printStackTrace();
return new CommonResult(5000,"登录失败",null);
}
}
}
3.2 当未登录时返回的也是json数据
创建一个过滤器,继承登录校验的某个接口。
public class LoginFilter extends FormAuthenticationFilter {
//当没有登录时会经过该方法。如果想让他返回json数据那么必须重写方法
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
CommonResult commonResult = new CommonResult(4001, "未登录", null);
ObjectMapper objectMapper=new ObjectMapper();
String json = objectMapper.writeValueAsString(commonResult);
writer.print(json); //响应给客户json数据
writer.flush();
writer.close();
return false;
}
}
注册我们的过滤器
3.3 如果没有权限应该返回json数据