美文网首页工作生活
ssm+shiro创建项目+配置文件+小案例

ssm+shiro创建项目+配置文件+小案例

作者: 一条小团团OvO | 来源:发表于2019-07-02 20:27 被阅读0次

1.导入jar包

<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>jxlv</groupId>
<artifactId>udpf</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jiangXi LianWei Unified development platform Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
  <java-version>1.8</java-version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring-version>4.2.5.RELEASE</spring-version>
  <org.springframework-version>3.2.8.RELEASE</org.springframework-version>
  <org.aspectj-version>1.6.10</org.aspectj-version>
  <org.slf4j-version>1.6.6</org.slf4j-version>
  <!-- mybatis版本号 -->
  <mybatis.version>3.2.6</mybatis.version>
  <!-- Apache shiro -->
  <shiro.version>1.2.5</shiro.version>
</properties>
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring-version}</version>
  </dependency>


  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring-version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${spring-version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework-version}</version>
  </dependency>
  <!-- mybatis核心包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>
  <!-- mybatis/spring包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
  </dependency>
  <!-- 导入java ee jar 包 -->
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
  </dependency>
  <!-- 导入Mysql数据库链接jar包 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
  </dependency>
  <!-- 导入Oracle数据库链接jar包 -->
  <!--<dependency>-->
  <!--<groupId>com.oracle</groupId>-->
  <!--<artifactId>ojdbc6</artifactId>-->
  <!--<version>10.2.0.1.0</version>-->
  <!--</dependency>-->
  <!-- https://mvnrepository.com/artifact/cglib/cglib -->
  <dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.5</version>
  </dependency>

  <!-- 阿里巴巴数据链接池-->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.18</version>
  </dependency>
  <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
  <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2.2</version>
  </dependency>

  <!-- Logging -->
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${org.slf4j-version}</version>
  </dependency>

  <dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
  </dependency>

  <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
  </dependency>

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
  </dependency>


  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${org.slf4j-version}</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${org.slf4j-version}</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>
  <!-- @Inject -->
  <dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
  </dependency>
  <!-- Servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

  <!-- json包-->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.31</version>
  </dependency>

  <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.10</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.1</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
  <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.26-incubating</version>
  </dependency>
  <!--Excel的POI操作-->
  <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
  </dependency>
  <!--文件上传组件-->
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>

  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>

  <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
  </dependency>

  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.4</version>
  </dependency>
  <!--shiro包导入-->
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.0</version>
  </dependency>

  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.4.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-lang -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-lang</artifactId>
    <version>1.4.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-cache -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-cache</artifactId>
    <version>1.4.0</version>
  </dependency>

  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>1.4.0</version>
  </dependency>

  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.0</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-crypto-hash -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-crypto-hash</artifactId>
    <version>1.4.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-crypto-cipher -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-crypto-cipher</artifactId>
    <version>1.4.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-config-core -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-config-core</artifactId>
    <version>1.4.0</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-config-ogdl -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-config-ogdl</artifactId>
    <version>1.4.0</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-event -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-event</artifactId>
    <version>1.4.0</version>
  </dependency>

  <!-- redis begin -->
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
  </dependency>
  <!--阿里云短息服务-->
  <dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version>
  </dependency>
  <!-- redis end -->
</dependencies>

<build>

  <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>${java-version}</source>
          <target>${java-version}</target>
          <encoding>UTF-8</encoding>
          <compilerArguments>
            <verbose/>
            <bootclasspath>${java.home}\jre\lib\rt.jar;${java.home}\jre\lib\jce.jar</bootclasspath>
          </compilerArguments>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>

  <finalName>UnifiedDevelopmenPlatform</finalName>
  <resources>
    <resource>
      <directory>${basedir}/src/main/java</directory>
      <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
    </resource>
    <resource>
      <directory>${basedir}/src/main/resources</directory>
    </resource>
  </resources>
</build>
</project>

2.配置在web.xml里配置filter

  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <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>

这里的<filter-name>shiroFilter</filter-name>中的shiroFilter必须跟shiro配置文件中的真实的filter bean id一致
3.创建shiro配置文件spring_shiro.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"
         xmlns:aop="http://www.springframework.org/schema/aop"
         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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--<bean-->
            <!--class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"-->
            <!--depends-on="lifecycleBeanPostProcessor" />-->
     <!--&lt;!&ndash;配置自定义的realm&ndash;&gt;-->
       <bean id="UserRealm" class="shiro.UserRealm"></bean>
     <!--配置安全管理器Securitymanager-->
     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
         <property name="realm" ref="UserRealm"/>
     </bean>
    <!--自定义shiroFilter-->
     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
         <property name="securityManager" ref="securityManager"/>
         <property name="loginUrl" value="/login"/>
         <property name="unauthorizedUrl" value="/nopermission.jsp"/>
         <property name="filterChainDefinitions">
             <value>
                 /**=authc
             </value>
         </property>
     </bean>
    <!--开启aop对类代理-->
    <aop:config expose-proxy="true"></aop:config>
    <!--开启shiro注解支持-->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    <!--定义需要特殊处理的异常,用类名或完全路径名作为key,异常页名作为value-->
    <!--shiro权限异常处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/nopermission.jsp</prop>
            </props>
        </property>
    </bean>
</beans>

3.创建认证,授权令牌

package shiro;
import csd.entity.User;
import csd.service.UserService;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {
    public UserRealm() {
        System.out.println("实例化了令牌");
    }

    public String getName() {
        return "UserRealm";
    }
    @Resource(name = "Iuser")
    private UserService userService;
    //授权操作
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权进行中");
        User user = (User)principalCollection.getPrimaryPrincipal();
        List<String> permissions = new ArrayList<String>();
        if ("10086".equals(user.getUsername())) {
            permissions.add("employee:edit");
        } else if ("admin".equals(user.getUsername())) {
            permissions.add("*:*");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        return info;
    }

    //认证操作
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证进行中");
        String username=(String) authenticationToken.getPrincipal();
        //System.out.println("令牌的username为"+username);
        User user = userService.login(username);
        if (user == null){
            return null;
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return info;
    }
}

4.需要准备的资源


页面.PNG 资源.PNG

5.controller层的编写

package csd.controller;


import csd.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
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;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @RequestMapping(value = "/login",method= RequestMethod.GET)
    public String login(Model model, HttpServletRequest req, User user)throws Exception{
        System.out.println("进入了login方法");
        System.out.println("用户名加密码"+user.getUsername()+","+user.getPassword());
        //如果认证失败就从reques中获取异常信息,shiroLoginFailure是shiro异常类的权限命名
//        String exceptionClassName=(String)req.getAttribute("shiroLoginFailure");
//        if(exceptionClassName!=null){
//            if(UnknownAccountException.class.getName().equals(exceptionClassName)){
//                model.addAttribute("errorMsg","账号不存在");
//                System.out.println("账号不存在");
//            }else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
//                model.addAttribute("errorMsg","账号或密码错误");
//                System.out.println("账号或密码错误");
//            }else {
//                model.addAttribute("errorMsg","其他异常信息");
//            }
//        }
        if(user.getUsername()!=null&&user.getPassword()!=null) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            try {
                //登录,即身份校验,由通过Spring注入的UserRealm会自动校验输入的用户名和密码在数据库中是否有对应的值
                subject.login(token);
                return "main";
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("errorMsg", "账号或密码错误");
                return "forward:/login.jsp";
            }
        }else {
             return "forward:/login.jsp";
        }
    }
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest req)throws Exception{
        System.out.println("进入了login方法");
         return "forward:/login.jsp";
    }
}

package csd.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
    @RequestMapping("/main")
    public String main(){
        System.out.println("进入了main");
        return "main";
    }
}

package csd.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @RequestMapping("/emp")
    public String index(){
         return "employee";
    }
    @RequestMapping("/del")
    @RequiresPermissions("employee:del")
    public String del(){
        System.out.println("执行了员工的删除操作");
        return "employee";
    }
    @RequestMapping("/add")
    @RequiresPermissions("employee:add")
    public String add(){
        System.out.println("执行了员工的添加操作");
        return "employee";
    }
    @RequestMapping("/edit")
    @RequiresPermissions("employee:edit")
    public String edit(){
        System.out.println("执行了员工的编辑操作");
        return "employee";
    }
    @RequestMapping("/select")
    @RequiresPermissions("employee:select")
    public String select(){
        System.out.println("执行了员工的查询操作");
        return "employee";
    }
}

6.页面的准备
(1)login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 联想
  Date: 2019/6/30
  Time: 12:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<span>ee${errorMsg}</span>
<form action="/login" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

(2).nopermission.jsp

<%--
  Created by IntelliJ IDEA.
  User: 联想
  Date: 2019/6/30
  Time: 12:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
没有权限
</body>
</html>

(3)main.jsp

<%--
  Created by IntelliJ IDEA.
  User: 联想
  Date: 2019/6/30
  Time: 12:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>欢迎xx访问</h1><br>
<p>注销</p><p>重新加载权限</p><br>
<a href="/employee/emp">员工列表</a><br>
<a href="department.jsp">部门列表</a>
</body>
</html>

(4).employee.jsp

<%--
  Created by IntelliJ IDEA.
  User: 联想
  Date: 2019/7/1
  Time: 18:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<p><a href="/employee/add">添加</a></p>
<p><a href="/employee/del">删除</a></p>
<p><a href="/employee/edit">修改</a></p>
<p><a href="/employee/select">查询</a></p>
</body>
</html>

相关文章

网友评论

    本文标题:ssm+shiro创建项目+配置文件+小案例

    本文链接:https://www.haomeiwen.com/subject/bopvcctx.html