接纳idea2017搭建SSM框架及测量检验,redis作为缓存使用

By admin in 4858.com on 2019年9月29日

1.搭建情形windows10+eclipse4.8+jdk1.8+maven

搭建个SSM框架居然开支了自家好短期!特此记录!

环境

  
 摘要:本文选用了Spring+SpringMVC+Mybatis+Shiro+Msql来写了一个登入验证的实例,上边来拜见进度吧!整个工程依照Mavevn来创设,运维条件为JDK1.6+WIN7+tomcat7.

2.框架springMVC+spring+Hibernate

亟待预备的条件:

1,windows7

此间根本说了Shiro的搭建进度,Spring+SpringMVC+Mybatis的搭建过能够看这里Spring+Mybatis+SpringMVC+Maven+MySql搭建实例

3.搭建步骤

idea 2017.1

2,mysql

完全工程无偿下载:

1)首先创制maven项目

jdk1.8

3,eclipse

最后效果如下:

file–new–other—maven-project

Maven 3.3.9

4,redis

4858.com 1

2)配置pom文件

请提早将idea与Maven、jdk配置好,此番项目用的都以比较新的

5,tomcat7

工程一体化的目录如下:

spring-corespring-contextspring-webspring-webmvcspring-orm
hibernate-corehibernate-entitymanager mysql-connector-java

步骤:

只顾:运维redis的章程,已经把redis做成windows服务,以windows服务的艺术运转

java代码如下:

<?xml version=”1.0″ encoding=”UTF-8″?>

一、首先应用idea新建叁个Maven webapp项目

把redis做成windows服务的命令行

4858.com 2

<project xmlns=””
xmlns:xsi=””
xsi:schemaLocation=”
;
<modelVersion>4.0.0</modelVersion>

4858.com 3

redis-server --service-install redis.windows.conf

可自行百度其他命令行

项目整合经过测试,可以正常启动,redis缓存和mysql操作均没有问题

布局文件如下:

<groupId>cn.temptation</groupId>
<artifactId>ssh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

4858.com 4

================================分割线========================================

4858.com 5

<name>ssh Maven Webapp</name>
<!– FIXME change it to the project’s website –>
<url>;

4858.com 6

情景:使用spring,springmvc,mybatis整合redis

页面财富如下:

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.2.6.RELEASE</spring.version>
</properties>

4858.com 7

目录结构如下:

4858.com 8

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

点击Finish,第一回搭建可能会非常慢,乃至或然须要VPN本领搭建成功

4858.com 9

 

<!– springframework 4 dependencies begin –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!– springframework 4 dependencies end –>

二、搭建目录结构

报错是因为eclipse抽风,不用管。

好了,上面来归纳说下进程吧!

<!– hibernate 配置 begin –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.9.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.9.Final</version>
</dependency>
<!– hibernate 配置 end –>

自家这里列出的是搭建完了随后全体的目录和文书,诸位先把目录文件建起来,然后小编在付给文件内容

================================分割线========================================

预备干活:

<!– mysql数据库的驱动包 start –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

4858.com 10

pom文件

先建表:

<!– 引入jstl包 –>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>

这里的目录建好之后还亟需设置一下,让idea识别目录功用,选取File-Project
Structure

<project xmlns=””
xmlns:xsi=””
xsi:schemaLocation=”
;
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>web.ssm</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>web.ssm Maven Webapp</name>
<url>;
<properties>
<servlet.version>3.0.1</servlet.version>
<spring.version>4.2.5.RELEASE</spring.version>
<mybatis.version>3.4.1</mybatis.version>
<mybatis.spring.version>1.3.0</mybatis.spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<ssm-maven-compiler-plugin.version>3.1</ssm-maven-compiler-plugin.version>
<ssm-maven-javadoc-plugin.version>2.7</ssm-maven-javadoc-plugin.version>
<ssm-maven-shade-plugin.version>2.3</ssm-maven-shade-plugin.version>
<ssm-maven-war-plugin.version>2.6</ssm-maven-war-plugin.version>
<ssm-encoding.version>UTF-8</ssm-encoding.version>
<ssm-jdk.version>1.8</ssm-jdk.version>
</properties>
<dependencies>
<!– servletAPI begin–>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
</dependency>
<!– servletAPI end–>
<!– for Spring begin –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-context</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-tx</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-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!– for Spring end –>
<!–springAOP begin –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<!–springAOP end –>
<!– for mybatis begin –>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!– for mybatis end –>
<!– begin with below line configured for log4j –>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<!– end with above line configured for log4j –>
<!–junit begin –>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<!– <scope>test</scope> –>
</dependency>
接纳idea2017搭建SSM框架及测量检验,redis作为缓存使用。<!–junit end –>
<!–druid begin –>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.24</version>
</dependency>
<!–druid end –>
<!–MySql begin–>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!–MySql end–>
<!–redis begin –>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<!–redis end –>
<!– JSON转变工具 begin–>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.4</version>
</dependency>
<!– JSON调换工具 end–>
</dependencies>
<build>
<finalName>web.ssm</finalName>
<plugins>
<!– 全局项目创设进程 –>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${ssm-jdk.version}</source>
<target>${ssm-jdk.version}</target>
<encoding>${ssm-encoding.version}</encoding>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${ssm-maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${ssm-maven-shade-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${ssm-maven-war-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

 

<!– 引入servlet –>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

4858.com 11

============================分割线======================================

[sql] view
plain copy

<!– 引进数据库连接池 –>
<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>
</dependencies>

设置达成后ok

jdbc.properties文件

 

<build>
<finalName>ssh</finalName>
<pluginManagement><!– lock down plugins versions to avoid
using Maven defaults (may be moved to parent pom) –>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!– see

–>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

三、配置文件内容

#Enbrands DB
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=admin
jdbc.password=admin

  1. drop table if exists user;  
  2.  CREATE TABLE `user` (  
  3.   `id` int(11) primary key auto_increment,  
  4.   `name` varchar(20)  NOT NULL,  
  5.   `age` int(11) DEFAULT NULL,  
  6.   `birthday` date DEFAULT NULL,  
  7.   `password` varchar(20)  NOT NULL  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  9.   
  10.  insert into user values(1,’lin’,12,’2013-12-01′,’123456′);  
  11.  insert into user values(2,’apple’,34,’1999-12-01′,’123456′);  
  12.  insert into user values(3,’evankaka’,23,’2017-12-01′,’123456′);  

3)创制对应的财富包 src/main/java src/main/resources

pom.xml

#druid datasource
druid.initialSize=10
druid.minIdle=10
druid.maxActive=50
druid.maxWait=60000
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=SELECT ‘x’
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
druid.poolPreparedStatements=true
druid.maxPoolPreparedStatementPerConnectionSize=20
#druid.filters=wall,stat
druid.filters=stat

建好后,新建多少个Maven的webApp的工程,记得把结构划设想置成上边的那么!

4)加多配备文件

<project xmlns=””
        xmlns:xsi=””
        xsi:schemaLocation=”
;

==========================分割线========================================

 

spring-mvc.xml

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.chatRobot</groupId>
    <artifactId>ChatRobot</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>ChatRobot Maven Webapp</name>
    <url>;

redis-config.properties文件

上面来看看一些代码和配备

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
xmlns:xsi=””
xmlns:p=””
xmlns:context=””
xmlns:mvc=””
xsi:schemaLocation=”

;

    <properties>
        <!– 设置项目编码编码 –>
       
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!– spring版本号 –>
        <spring.version>4.3.5.RELEASE</spring.version>
        <!– mybatis版本号 –>
        <mybatis.version>3.4.1</mybatis.version>
    </properties>

# Redis settings
# server IP
redis.host=127.0.0.1
# server port
redis.port=6379
# server pass
redis.pass=admin
# use dbIndex
redis.database=0
#
\u63A7\u5236\u4E00\u4E2Apool\u6700\u591A\u6709\u591A\u5C11\u4E2A\u72B6\u6001\u4E3Aidle(\u7A7A\u95F2\u7684)\u7684jedis\u5B9E\u4F8B
redis.maxIdle=300
#
\u8868\u793A\u5F53borrow(\u5F15\u5165)\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u6700\u5927\u7684\u7B49\u5F85\u65F6\u95F4\uFF0C\u5982\u679C\u8D85\u8FC7\u7B49\u5F85\u65F6\u95F4(\u6BEB\u79D2)\uFF0C\u5219\u76F4\u63A5\u629B\u51FAJedisConnectionException\uFF1B
redis.maxWait=3000
#
\u5728borrow\u4E00\u4E2Ajedis\u5B9E\u4F8B\u65F6\uFF0C\u662F\u5426\u63D0\u524D\u8FDB\u884Cvalidate\u64CD\u4F5C\uFF1B\u5982\u679C\u4E3Atrue\uFF0C\u5219\u5F97\u5230\u7684jedis\u5B9E\u4F8B\u5747\u662F\u53EF\u7528\u7684
redis.testOnBorrow=false

1、POM文件

<!– 对web包中的全部类举行围观,以成就Bean创制和机关依赖注入的成效–>
<context:component-scan base-package=”cn.temptation” />

    <dependencies>

乱码部分是注释,不用管

留意不要少导包了,要是项目出现红叉,常常都是JDK版本的设置难点,本人百度时而就能够化解

<!– 激活基于申明的陈设 @RequestMapping, @ExceptionHandler,数据绑定
,@NumberFormat ,
@DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等
–>
<mvc:annotation-driven />

        <!– java ee –>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>

==========================分割线======================================

 

<!– 视图层配置 –>
<bean >
<!–配置JSTL表达式–>
<property name=”viewClass”
value=”org.springframework.web.servlet.view.JstlView”/>
<!– 前缀 –>
<property name=”prefix” value=”/WEB-INF/view/”/>
<!– 后缀 –>
<property name=”suffix” value=”.jsp”/>
</bean>

        <!– 单元测量检验 –>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

applicationContext.xml文件

[html] view
plain copy

<!– 配置静态能源 –>
<mvc:resources location=”/res/” mapping=”/res/**”/>
</beans>

        <!– 达成slf4j接口并组成 –>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.2</version>
        </dependency>

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
xmlns:xsi=””
xmlns:p=””
xmlns:context=””
xmlns:mvc=””
xsi:schemaLocation=”

;

 

spring.xml

        <!– 映入JSON –>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.7</version>
        </dependency>

<!–扫描包 –>
<context:component-scan base-package=”web.ssm.service” />
<context:component-scan base-package=”web.ssm.service.impl” />
<context:component-scan base-package=”web.ssm.dao” />

  1. <project xmlns=”” xmlns:xsi=””  
  2.     xsi:schemaLocation=” ;  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.lin</groupId>  
  5.     <artifactId>ShiroLearn1</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>ShiroLearn1 Maven Webapp</name>  
  9.     <url>;  
  10.     <properties>  
  11.         <!– spring版本号 –>  
  12.         <spring.version>3.2.8.RELEASE</spring.version>  
  13.         <!– log4j日志文件管理包版本 –>  
  14.         <slf4j.version>1.6.6</slf4j.version>  
  15.         <log4j.version>1.2.12</log4j.version>  
  16.         <!– junit版本号 –>  
  17.         <junit.version>4.10</junit.version>  
  18.         <!– mybatis版本号 –>  
  19.         <mybatis.version>3.2.1</mybatis.version>  
  20.     </properties>  
  21.     <dependencies>  
  22.         <!– 添加Spring依赖 –>  
  23.         <dependency>  
  24.             <groupId>org.springframework</groupId>  
  25.             <artifactId>spring-core</artifactId>  
  26.             <version>${spring.version}</version>  
  27.         </dependency>  
  28.         <dependency>  
  29.             <groupId>org.springframework</groupId>  
  30.             <artifactId>spring-webmvc</artifactId>  
  31.             <version>${spring.version}</version>  
  32.         </dependency>  
  33.         <dependency>  
  34.             <groupId>org.springframework</groupId>  
  35.             <artifactId>spring-context</artifactId>  
  36.             <version>${spring.version}</version>  
  37.         </dependency>  
  38.         <dependency>  
  39.             <groupId>org.springframework</groupId>  
  40.             <artifactId>spring-context-support</artifactId>  
  41.             <version>${spring.version}</version>  
  42.         </dependency>  
  43.         <dependency>  
  44.             <groupId>org.springframework</groupId>  
  45.             <artifactId>spring-aop</artifactId>  
  46.             <version>${spring.version}</version>  
  47.         </dependency>  
  48.         <dependency>  
  49.             <groupId>org.springframework</groupId>  
  50.             <artifactId>spring-aspects</artifactId>  
  51.             <version>${spring.version}</version>  
  52.         </dependency>  
  53.         <dependency>  
  54.             <groupId>org.springframework</groupId>  
  55.             <artifactId>spring-tx</artifactId>  
  56.             <version>${spring.version}</version>  
  57.         </dependency>  
  58.         <dependency>  
  59.             <groupId>org.springframework</groupId>  
  60.             <artifactId>spring-jdbc</artifactId>  
  61.             <version>${spring.version}</version>  
  62.         </dependency>  
  63.         <dependency>  
  64.             <groupId>org.springframework</groupId>  
  65.             <artifactId>spring-web</artifactId>  
  66.             <version>${spring.version}</version>  
  67.         </dependency>  
  68.   
  69.         <!–单元测量检验重视 –>  
  70.         <dependency>  
  71.             <groupId>junit</groupId>  
  72.             <artifactId>junit</artifactId>  
  73.             <version>${junit.version}</version>  
  74.             <scope>test</scope>  
  75.         </dependency>  
  76.   
  77.         <!– 日志文件管理包 –>  
  78.         <!– log start –>  
  79.         <dependency>  
  80.             <groupId>log4j</groupId>  
  81.             <artifactId>log4j</artifactId>  
  82.             <version>${log4j.version}</version>  
  83.         </dependency>  
  84.         <dependency>  
  85.             <groupId>org.slf4j</groupId>  
  86.             <artifactId>slf4j-api</artifactId>  
  87.             <version>${slf4j.version}</version>  
  88.         </dependency>  
  89.         <dependency>  
  90.             <groupId>org.slf4j</groupId>  
  91.             <artifactId>slf4j-log4j12</artifactId>  
  92.             <version>${slf4j.version}</version>  
  93.         </dependency>  
  94.         <!– log end –>  
  95.   
  96.         <!–spring单元测量试验依赖 –>  
  97.         <dependency>  
  98.             <groupId>org.springframework</groupId>  
  99.             <artifactId>spring-test</artifactId>  
  100.             <version>${spring.version}</version>  
  101.             <scope>test</scope>  
  102.         </dependency>  
  103.   
  104.         <!–mybatis依赖 –>  
  105.         <dependency>  
  106.             <groupId>org.mybatis</groupId>  
  107.             <artifactId>mybatis</artifactId>  
  108.             <version>${mybatis.version}</version>  
  109.         </dependency>  
  110.   
  111.         <!– mybatis/spring包 –>  
  112.         <dependency>  
  113.             <groupId>org.mybatis</groupId>  
  114.             <artifactId>mybatis-spring</artifactId>  
  115.             <version>1.2.0</version>  
  116.         </dependency>  
  117.   
  118.         <!– mysql驱动包 –>  
  119.         <dependency>  
  120.             <groupId>mysql</groupId>  
  121.             <artifactId>mysql-connector-java</artifactId>  
  122.             <version>5.1.29</version>  
  123.         </dependency>  
  124.   
  125.              <!– servlet驱动包 –>  
  126.         <dependency>  
  127.             <groupId>javax.servlet</groupId>  
  128.             <artifactId>servlet-api</artifactId>  
  129.             <version>3.0-alpha-1</version>  
  130.         </dependency>  
  131.   
  132.         <!– Spring 整合Shiro供给的注重 –>  
  133.         <dependency>  
  134.             <groupId>org.apache.shiro</groupId>  
  135.             <artifactId>shiro-core</artifactId>  
  136.             <version>1.2.1</version>  
  137.         </dependency>  
  138.         <dependency>  
  139.             <groupId>org.apache.shiro</groupId>  
  140.             <artifactId>shiro-web</artifactId>  
  141.             <version>1.2.1</version>  
  142.         </dependency>  
  143.         <dependency>  
  144.             <groupId>org.apache.shiro</groupId>  
  145.             <artifactId>shiro-ehcache</artifactId>  
  146.             <version>1.2.1</version>  
  147.         </dependency>  
  148.         <dependency>  
  149.             <groupId>org.apache.shiro</groupId>  
  150.             <artifactId>shiro-spring</artifactId>  
  151.             <version>1.2.1</version>  
  152.         </dependency>  
  153.         <!– Spring 整合Shiro须要的重视 –>  
  154.   
  155.     </dependencies>  
  156.     <build>  
  157.         <finalName>ShiroLearn1</finalName>  
  158.         <plugins>  
  159.             <!– 指定web项目 版本 –>  
  160.             <plugin>  
  161.                 <artifactId>maven-war-plugin</artifactId>  
  162.                 <configuration>  
  163.                     <version>2.4</version>  
  164.                 </configuration>  
  165.             </plugin>  
  166.             <!– 钦定编写翻译使用 –>  
  167.             <plugin>  
  168.                 <groupId>org.apache.maven.plugins</groupId>  
  169.                 <artifactId>maven-compiler-plugin</artifactId>  
  170.                 <version>2.3.2</version>  
  171.                 <configuration>  
  172.                     <source>1.6</source>  
  173.                     <target>1.6</target>  
  174.                 </configuration>  
  175.             </plugin>  
  176.         </plugins>  
  177.     </build>  
  178. </project>  

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans default-autowire=”byName”
xmlns=””
xmlns:xsi=””
xmlns:p=””
xmlns:context=””
xmlns:tx=””
xsi:schemaLocation=”

;

        <!– 数据库 –>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
            <scope>runtime</scope>
        </dependency>

<!– 引进同文件夹下的redis属性配置文件 –>
<import resource=”classpath:spring/spring-mybatis.xml”/>

 

<!– 对web包中的全数类进行围观,以成就Bean创立和机关信赖注入的职能
–>
<context:component-scan base-package=”cn.temptation” />

        <!– 数据库连接池 –>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

<import resource=”classpath:spring/spring-redis.xml”/>

2、自定义Shiro拦截器

<!– 数据源,BasicDataSource,commons-dbcp –>
<bean >
<property name=”driverClassName” value=”com.mysql.jdbc.Driver”
/>
<property name=”url”
value=”jdbc:mysql://localhost:3306/ket-test?useUnicode=true&characterEncoding=UTF-8″
/>
<property name=”username” value=”root” />
</bean>

        <!– MyBatis –>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

</beans>

 
 这里那些拦截器达成了客户名和密码的验证,验证成功后又给用赋剧中人物和权杖(注意,这里赋角色和权力笔者一向写进去了,没有动用数据库,日常都以要因而service层找到客户名后,再去数据库查该客商对应的剧中人物以及权限,然后再步入到shiro中去)

<!– Hibernate SesssionFactory –>
<bean >
<property name=”dataSource” ref=”dataSource” />
<property name=”hibernateProperties”>
<props>
<prop
key=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
<prop key=”hibernate.format_sql”>true</prop>
<prop key=”hibernate.hbm2ddl.auto”>update</prop>
</props>
</property>
<property name=”mappingLocations”
value=”classpath:/cn/temptation/entity/*.hbm.xml” />
</bean>

        <!– mybatis/spring整合包 –>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

===============================分割线=================================================

4858.com 12

<!– PlatTranscationManager –>
<bean >
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>

        <!– Spring –>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</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-context</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-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

spring-mvc.xml文件

代码如下:

<tx:annotation-driven transaction-manager=”transactionManager”
/>
</beans>

    </dependencies>

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
xmlns:xsi=””
xmlns:context=””
xmlns:mvc=””
xmlns:util=””
xsi:schemaLocation=”

;
<!– 扫描调整器包 –>
<mvc:default-servlet-handler />
<!– <mvc:annotation-driven></mvc:annotation-driven>
–>
<context:component-scan base-package=”web.ssm.controller” />

 

4)修改web.xml

    <build>
        <finalName>ChatRobot</finalName>
        <plugins>
            <plugin>
               
<groupId>org.apache.maven.plugins</groupId>
               
<artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!– 设置JDK版本 –>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

<mvc:annotation-driven>
<mvc:message-converters>
<ref bean=”stringHttpMessageConverter” />
<ref bean=”mappingJacksonHttpMessageConverter” /> <!–
JSON转换器 –>
</mvc:message-converters>
</mvc:annotation-driven>

[java] view
plain copy

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=””
xmlns=””
xmlns:web=””
xsi:schemaLocation=”

version=”3.0″>

</project>

<bean id=”mappingJacksonHttpMessageConverter”
class=”org.springframework.http.converter.json.MappingJackson2HttpMessageConverter”>
<property name=”supportedMediaTypes”>
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>

 

<display-name>Archetype Created Web
Application</display-name>

只顾右下角更新pom

<!– – StringHttpMessageConverter bean –>
<bean id = “stringHttpMessageConverter” class =
“org.springframework.http.converter.StringHttpMessageConverter”>
<property name=”supportedMediaTypes”>
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!– 注解POJO的映射 –>
<bean
class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>
<property name=”messageConverters”>
<list>
<ref bean=”mappingJacksonHttpMessageConverter” /> <!–
JSON转换器 –>
<ref bean=”stringHttpMessageConverter” />
</list>
</property>
</bean>

  1. package com.lin.realm;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6. import org.apache.shiro.authc.AuthenticationException;  
  7. import org.apache.shiro.authc.AuthenticationInfo;  
  8. import org.apache.shiro.authc.AuthenticationToken;  
  9. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  10. import org.apache.shiro.authc.UsernamePasswordToken;  
  11. import org.apache.shiro.authz.AuthorizationInfo;  
  12. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  13. import org.apache.shiro.cache.Cache;  
  14. import org.apache.shiro.realm.AuthorizingRealm;  
  15. import org.apache.shiro.subject.PrincipalCollection;  
  16. import org.apache.shiro.subject.SimplePrincipalCollection;  
  17. import org.slf4j.Logger;  
  18. import org.slf4j.LoggerFactory;  
  19. import org.springframework.beans.factory.annotation.Autowired;  
  20.   
  21. import com.lin.domain.User;  
  22. import com.lin.service.UserService;  
  23. import com.lin.utils.CipherUtil;  
  24.   
  25. public class ShiroDbRealm extends AuthorizingRealm {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     private static final String ALGORITHM = “MD5”;  
  28.       
  29.     @Autowired  
  30.     private UserService userService;  
  31.   
  32.     public ShiroDbRealm() {  
  33.         super();  
  34.     }  
  35.       
  36.     /** 
  37.      * 验证登录 
  38.      */  
  39.     @Override  
  40.     protected AuthenticationInfo doGetAuthenticationInfo(  
  41.             AuthenticationToken authcToken) throws AuthenticationException {  
  42.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
  43.         System.out.println(token.getUsername());  
  44.         User user = userService.findUserByLoginName(token.getUsername());  
  45.         System.out.println(user);  
  46.         CipherUtil cipher = new CipherUtil();//MD5加密  
  47.         if (user != null) {  
  48.             return new SimpleAuthenticationInfo(user.getName(), cipher.generatePassword(user.getPassword()), getName());  
  49.         }else{  
  50.             throw new AuthenticationException();  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.      * 登陆成功未来,进行剧中人物和权杖验证 
  56.      */  
  57.     @Override  
  58.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  59.         /*此地应该依附userName使用role和permission 的serive层来做决断,并将对应 的权柄加进去,下边简化了这一步*/  
  60.         Set<String> roleNames = new HashSet<String>();  
  61.         Set<String> permissions = new HashSet<String>();  
  62.         roleNames.add(“admin”);//加多剧中人物。对应到index.jsp  
  63.         roleNames.add(“administrator”);  
  64.         permissions.add(“create”);//增添权力,对应到index.jsp  
  65.         permissions.add(“login.do?main”);  
  66.         permissions.add(“login.do?logout”);  
  67.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
  68.         info.setStringPermissions(permissions);  
  69.         return info;  
  70.     }  
  71.   
  72.   
  73.     /** 
  74.      * 清除全数客户授权音讯缓存. 
  75.      */  
  76.     public void clearCachedAuthorizationInfo(String principal) {  
  77.         SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());  
  78.         clearCachedAuthorizationInfo(principals);  
  79.     }  
  80.   
  81.   
  82.     /** 
  83.      * 清除全数客户授权新闻缓存. 
  84.      */  
  85.     public void clearAllCachedAuthorizationInfo() {  
  86.         Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();  
  87.         if (cache != null) {  
  88.             for (Object key : cache.keys()) {  
  89.                 cache.remove(key);  
  90.             }  
  91.         }  
  92.     }  
  93.   
  94. //  @PostConstruct  
  95. //  public void initCredentialsMatcher() {//MD5鍔犲瘑  
  96. //      HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);  
  97. //      setCredentialsMatcher(matcher);  
  98. //  }  
  99. }  

<!– 配置spring容器 –>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>

 

<!– 视图配置–>
<bean
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix” value=”/WEB-INF/views/” />
<property name=”suffix” value=”.jsp” />
</bean>

3、shiro的布署文件 :spring-shiro.xml

<!– 配置监听器 –>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

logback.xml

</beans>

剧情如下:

<!– 央浼都提交DispatcherServlet管理 –>
<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:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

 

==================================分割线===========================================

 

<!– 扩张中文乱码过滤器 –>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration debug=”true”>
    <appender name=”STDOUT”
class=”ch.qos.logback.core.ConsoleAppender”>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level
%logger{36} – %msg%n</pattern>
        </encoder>
    </appender>
    <root level=”debug”>
        <appender-ref ref=”STDOUT”/>
    </root>
</configuration>

spring-mybatis文件

[html] view
plain copy

<!– 清除jsp空格 –>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>

 

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
xmlns:xsi=””
xmlns:tx=””
xmlns:context=””
xmlns:mvc=””
xmlns:aop=””
xsi:schemaLocation=”

“>

 

<!–<welcome-file-list>
<welcome-file>/view/login.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>–>

这里能够调节输出格式和剧情,有意思味的能够协调安装

<context:property-placeholder
location=”classpath:database/jdbc.properties”
ignore-unresolvable=”true”/>

  1. <?xml version=”1.0″ encoding=”UTF-8″?>  
  2. <beans xmlns=””  
  3.     xmlns:xsi=””  
  4.     xsi:schemaLocation=”   
  5.                         ”  
  6.     default-lazy-init=”true”>  
  7.   
  8.     <description>Shiro Configuration</description>  
  9.   
  10.     <!– Shiro’s main business-tier object for web-enabled applications –>  
  11.     <bean id=”securityManager” class=”org.apache.shiro.web.mgt.DefaultWebSecurityManager”>  
  12.         <property name=”realm” ref=”shiroDbRealm” />  
  13.         <property name=”cacheManager” ref=”cacheManager” />  
  14.     </bean>  
  15.   
  16.     <!– 項目自定义的Realm –>  
  17.     <bean id=”shiroDbRealm” class=”com.lin.realm.ShiroDbRealm”>  
  18.         <property name=”cacheManager” ref=”cacheManager” />  
  19.     </bean>  
  20.   
  21.     <!– Shiro Filter –>  
  22.     <bean id=”shiroFilter” class=”org.apache.shiro.spring.web.ShiroFilterFactoryBean”>  
  23.         <property name=”securityManager” ref=”securityManager” />  
  24.         <property name=”loginUrl” value=”/login.do” />  
  25.         <property name=”successUrl” value=”/view/index.html” />  
  26.         <property name=”unauthorizedUrl” value=”/error/noperms.jsp” />  
  27.         <property name=”filterChainDefinitions”>  
  28.             <value>  
  29.                 /index.html = authc  
  30.                 /checkLogin.do = anon  
  31.                 /login.do = anon  
  32.                 /logout.html = anon  
  33.                 /** = authc  
  34.             </value>  
  35.         </property>  
  36.     </bean>  
  37.   
  38.     <!– 顾客授权音讯Cache –>  
  39.     <bean id=”cacheManager” class=”org.apache.shiro.cache.MemoryConstrainedCacheManager” />  
  40.   
  41.     <!– 保险落实了Shiro内部lifecycle函数的bean实践 –>  
  42.     <bean id=”lifecycleBeanPostProcessor” class=”org.apache.shiro.spring.LifecycleBeanPostProcessor” />  
  43.   
  44.     <!– AOP式方法级权限检查 –>  
  45.     <bean class=”org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator”  
  46.         depends-on=”lifecycleBeanPostProcessor”>  
  47.         <property name=”proxyTargetClass” value=”true” />  
  48.     </bean>  
  49.   
  50.     <bean class=”org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor”>  
  51.         <property name=”securityManager” ref=”securityManager” />  
  52.     </bean>  
  53. </beans>  

</web-app>

 

<bean id=”dataSource” class=”com.alibaba.druid.pool.DruidDataSource”
init-method=”init” destroy-method=”close”>
<!– 基特性能 url、user、password –>
<property name=”url” value=”${jdbc.url}” />
<property name=”username” value=”${jdbc.username}” />
<property name=”password” value=”${jdbc.password}” />
<property name=”driverClassName” value=”${jdbc.driver}” />

 

5)编写测量检验的调节层和逻辑层代码

jdbc.properties

<!– 配置初阶化大小、最小、最大 –>
<property name=”initialSize” value=”1″ />
<property name=”minIdle” value=”1″ />
<property name=”maxActive” value=”20″ />

这里大致表达下:

LoginController

 

<!– 配置获取连接等待超时的日子 –>
<property name=”maxWait” value=”60000″ />

(1)

package cn.temptation.controller;

jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://xxxxxxxxx:3306/ChatRobot?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=xxxx
#密码
jdbc.password=xxxxx
#最达累斯萨拉姆接数
c3p0.maxPoolSize=30
#微小连接数
c3p0.minPoolSize=10
#关门连接后不自行commit
c3p0.autoCommitOnClose=false
#收获连接超时时间
c3p0.checkoutTimeout=10000
#当获得连接失利重试次数
c3p0.acquireRetryAttempts=2

<!– 配置间隔多长期才举行三遍检查评定,检测要求关闭的空闲连接,单位是皮秒–>
<property name=”timeBetweenEvictionRunsMillis” value=”60000″ />

**securityManager:这几个个性是必得的。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

 

<!– 配置多个总是在池中幽微生存的时光,单位是飞秒 –>
<property name=”minEvictableIdleTimeMillis” value=”300000″ />

loginUrl:未有登入的客商伏乞须要报到的页面时自动跳转到登陆页面,不是必需的属性,不输入地方的话会自行寻觅项目web项指标根目录下的”/login.jsp”页面。

import cn.temptation.entity.User;
import cn.temptation.service.LoginService;

 

<!– <property name=”validationQuery” value=”SELECT ‘x’ from test
” /> –>
<property name=”testWhileIdle” value=”false” />
<property name=”testOnBorrow” value=”false” />
<property name=”testOnReturn” value=”false” />

successUrl:登入成功暗中同意跳转页面,不配备则跳转至”/”。假设登入前点击的一个索要登入的页面,则在登入活动跳转到那三个供给登入的页面。不跳转到此。

/**
* @version
* @time 2018-2-28 下午5:57:07
* @describe:控制器
*/
@Controller
// 表明为调控器
@RequestMapping(value = “/login”)
// 截获带有/login的供给
public class LoginController {
@Autowired
LoginService loginService; // 注入service层

spring-mybatis.xml

<!– 张开PSCache,何况钦定各类连接上PSCache的尺寸 –>
<property name=”poolPreparedStatements” value=”true” />
<property name=”maxPoolPreparedStatementPerConnectionSize” value=”20″
/>

unauthorizedUrl:未有权限暗中同意跳转的页面。
**

@RequestMapping(method = RequestMethod.GET)
public String get() { // 用来回到三个页面
return “login”; // 再次来到指向login.jsp页面
}

 

<!– 配置监察和控制总括拦截的filters –>
<property name=”filters” value=”stat” />
</bean>

(2)

@RequestMapping(method = RequestMethod.POST)
public String post(User user) { // 用来管理客商的登录要求
if (loginService.login(user.getUserName(), user.getPassword {
return “login_4858.com,success”; // 登入成功,跳转到login_success.jsp页面
}
return “login”;

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
      xmlns:xsi=””
      xmlns:context=””
      xmlns:tx=””
      xsi:schemaLocation=”
     
     
     
     
      ;

<bean id=”sqlSessionFactory”
class=”org.mybatis.spring.SqlSessionFactoryBean”>
<property name=”dataSource” ref=”dataSource” />
<!– 自动扫描mapping.xml文件 –>
<property name=”mapperLocations”
value=”classpath:mapping/*.xml”></property>
</bean>

*anon:例子/admins/\*=anon 未有参数,表示能够佚名使用。

}
}

    <!– 扫描service包下全体应用申明的类别 –>
    <context:component-scan base-package=”com.chatRobot.service”/>

<!– DAO接口所在包名,Spring会自动物检疫索其下的类 –>
<bean class=”org.mybatis.spring.mapper.MapperScannerConfigurer”>
<property name=”basePackage” value=”web.ssm.dao” />
<property name=”sqlSessionFactoryBeanName”
value=”sqlSessionFactory”></property>
</bean>

authc:例如/admins/user/**=authc代表要求申明(登入)能力应用,没有参数

LoginService

    <!– 配置数据库相关参数properties的性子:${url} –>
    <context:property-placeholder
location=”classpath:jdbc.properties”/>

<!– (事务管理)transaction manager, use JtaTransactionManager for
global tx –>
<bean id=”transactionManager”
class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
<property name=”dataSource” ref=”dataSource” />
</bean>
<!– enables scanning for @Transactional annotations –>
<tx:annotation-driven transaction-manager=”transactionManager”
/>
<tx:advice id=”txAdvice”
transaction-manager=”transactionManager”>
<tx:attributes>
<tx:method name=”get*” propagation=”REQUIRED”
read-only=”true”/>
<tx:method name=”search*” propagation=”REQUIRED”
read-only=”true”/>
<tx:method name=”find*” propagation=”REQUIRED”
read-only=”true”/>
<tx:method name=”save*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”add*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”insert*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”update*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”create*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”delete*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”run*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”batch*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<tx:method name=”execute*” propagation=”REQUIRED”
rollback-for=”java.lang.Exception”/>
<!– <tx:method name=”*” propagation=”REQUIRED”/> –>
</tx:attributes>
</tx:advice>

roles:例子/admins/user/**=roles[admin],参数能够写多个,多少个时必得抬高引号,何况参数之间用逗号分割,当有多个参数时,譬喻admins/user/**=roles[“admin,guest”],每一种参数通过才算通过,相当于hasAllRoles()方法。

package cn.temptation.service;

    <!– 数据库连接池 –>
    <bean id=”dataSource”
class=”com.mchange.v2.c3p0.ComboPooledDataSource”>
        <property name=”driverClass” value=”${jdbc.driver}”/>
        <property name=”jdbcUrl” value=”${jdbc.url}”/>
        <property name=”user” value=”${jdbc.username}”/>
        <property name=”password” value=”${jdbc.password}”/>
        <property name=”maxPoolSize”
value=”${c3p0.maxPoolSize}”/>
        <property name=”minPoolSize”
value=”${c3p0.minPoolSize}”/>
        <property name=”autoCommitOnClose”
value=”${c3p0.autoCommitOnClose}”/>
        <property name=”checkoutTimeout”
value=”${c3p0.checkoutTimeout}”/>
        <property name=”acquireRetryAttempts”
value=”${c3p0.acquireRetryAttempts}”/>
    </bean>

<!– AOP 设置这几个类的咋样措施参加专门的学问 –>
<aop:config proxy-target-class=”true”>
<aop:pointcut id=”webssmService” expression=”execution(*
web.ssm.service..*.*(..))” />
<aop:advisor pointcut-ref=”webssmService” advice-ref=”txAdvice”
/>
</aop:config>
</beans>

perms:例子/admins/user/**=perms[user:add:*],参数能够写多少个,五个时必需抬高引号,况兼参数之间用逗号分割,举个例子/admins/user/**=perms[“user:add:*,user:modify:*”],当有多少个参数时必须每一种参数都经过才通过,想当于isPermitedAll()方法。

public interface LoginService {
public int login(String userName, String password);
}

    <!– 配置SqlSessionFactory对象 –>
    <bean id=”sqlSessionFactory”
class=”org.mybatis.spring.SqlSessionFactoryBean”>
        <!– 注入数据库连接池 –>
        <property name=”dataSource” ref=”dataSource”/>
        <!– 扫描model包 使用外号 –>
        <property name=”typeAliasesPackage”
value=”com.chatRobot.model”/>
        <!– 扫描sql配置文件:mapper要求的xml文件 –>
        <property name=”mapperLocations”
value=”classpath:mapper/*.xml”/>
    </bean>

===============================分割线=================================================

rest:例子/admins/user/**=rest[user],依据乞求的法子,相当于/admins/user/**=perms[user:method]
,其中method为post,get,delete等。

LoginServiceImpl

    <!– 配置扫描Dao接口包,动态完结Dao接口,注入到spring容器中
–>
    <bean
class=”org.mybatis.spring.mapper.MapperScannerConfigurer”>
        <!– 注入sqlSessionFactory –>
        <property name=”sqlSessionFactoryBeanName”
value=”sqlSessionFactory”/>
        <!– 给出必要扫描Dao接口包 –>
        <property name=”basePackage” value=”com.chatRobot.dao”/>
    </bean>

spring-redis.xml文件

port:例子/admins/user/**=port[8081],当呼吁的url的端口不是8081是跳转到schemal://serverName:8081?queryString,个中schmal是说道http或https等,serverName是您拜候的host,8081是url配置里port的端口,queryString

package cn.temptation.service;

    <!– 配置事务管理器 –>
    <bean id=”transactionManager”
class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
        <!– 注入数据库连接池 –>
        <property name=”dataSource” ref=”dataSource”/>
    </bean>

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
xmlns:xsi=””
xmlns:p=””
xmlns:context=””
xmlns:mvc=””
xmlns:cache=””
xsi:schemaLocation=”

;

是您拜谒的url里的?前边的参数。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

    <!– 配置基于注脚的注明式事务 –>
    <tx:annotation-driven
transaction-manager=”transactionManager”/>

<context:property-placeholder
location=”classpath:redis/redis-config.properties”
ignore-unresolvable=”true”/>

authcBasic:例如/admins/user/**=authcBasic未有参数表示httpBasic认证

import cn.temptation.dao.UserDao;

</beans>

<!–
启用缓存注明作用,这几个是必需的,不然注脚不会收效,别的,该评释应当要申明在spring主配置文件中才会生效
–>
<cache:annotation-driven cache-manager=”cacheManager” />

ssl:例子/admins/user/**=ssl未有参数,表示安全的url供给,合同为https

@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private UserDao userDao;

 

<!– redis 相关布置 –>
<bean id=”poolConfig”
class=”redis.clients.jedis.JedisPoolConfig”>
<property name=”maxIdle” value=”${redis.maxIdle}” />
<property name=”maxWaitMillis” value=”${redis.maxWait}” />
<property name=”testOnBorrow” value=”${redis.testOnBorrow}” />
</bean>

user:例如/admins/user/**=user未有参数表示必需存在客户,当登陆操作时不做检讨

@Override
public int login(String userName, String password) {
return userDao.find(userName, password) == null ? 0 : 1;
}

 

<bean id=”JedisConnectionFactory”
class=”org.springframework.data.redis.connection.jedis.JedisConnectionFactory”
p:host-name=”${redis.host}” p:port=”${redis.port}”
p:password=”${redis.pass}” p:pool-config-ref=”poolConfig”/>

注:anon,authcBasic,auchc,user是认证过滤器,

}

spring-mvc.xml

<bean id=”redisTemplate”
class=”org.springframework.data.redis.core.RedisTemplate”>
<property name=”connectionFactory” ref=”JedisConnectionFactory”
/>
</bean>

perms,roles,ssl,rest,port是授权过滤器**

UserDao

 

<!– spring本身的缓存管理器,这里定义了缓存地方名称 ,即阐明中的value
–>
<bean id=”cacheManager”
class=”org.springframework.cache.support.SimpleCacheManager”>
<property name=”caches”>
<set>
<!– 这里能够配备五个redis –>
<!– <bean class=”com.cn.util.RedisCache”>
<property name=”redisTemplate” ref=”redisTemplate” />
<property name=”name” value=”default”/>
</bean> –>
<bean class=”web.ssm.utils.RedisCache”>
<property name=”redisTemplate” ref=”redisTemplate” />
<property name=”name” value=”common”/>
<!– common名称要在类或格局的注释中使用 –>
</bean>
</set>
</property>
</bean>

4、web.xml配置解读shiro的配备文件(上边的)

package cn.temptation.dao;

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=””
      xmlns:xsi=””
      xmlns:context=””
      xmlns:mvc=””
      xsi:schemaLocation=”
     
     
     
     
      ;

</beans>

 

import cn.temptation.entity.User;

    <!– 扫描web相关的bean –>
    <context:component-scan
base-package=”com.chatRobot.controller”/>

=================================分割线========================================

[html] view
plain copy

public interface UserDao {
public User find(String userName, String password);
}

    <!– 开启SpringMVC注明形式 –>
    <mvc:annotation-driven/>

web.xml文件

 

UserDaoImpl

    <!– 静态财富暗中同意servlet配置 –>
    <mvc:default-servlet-handler/>

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=””
xmlns=””
xsi:schemaLocation=”

version=”3.0″>
<display-name>webssm</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webssm</param-value>
</context-param>
<!– log4j begin –>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!– log4j end –>
<!– 编码过滤器 –>
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!– spring config–>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  1. <?xml version=”1.0″ encoding=”UTF-8″?>  
  2. <web-app xmlns:xsi=””  
  3.     xmlns=”” xmlns:web=””  
  4.     xsi:schemaLocation=” ”  
  5.     id=”WebApp_ID” version=”2.5″>  
  6.     <display-name>Archetype Created Web Application</display-name>  
  7.     <!– 初阶招待分界面 –>  
  8.     <welcome-file-list>  
  9.         <welcome-file>/login.do</welcome-file>  
  10.     </welcome-file-list>  
  11.   
  12.     <!– 读取spring配置文件 –>  
  13.     <context-param>  
  14.         <param-name>contextConfigLocation</param-name>  
  15.         <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>  
  16.     </context-param>  
  17.     <!– 设计路径变量值 –>  
  18.     <context-param>  
  19.         <param-name>webAppRootKey</param-name>  
  20.         <param-value>springmvc.root</param-value>  
  21.     </context-param>  
  22.   
  23.   
  24.     <!– Spring字符集过滤器 –>  
  25.     <filter>  
  26.         <filter-name>SpringEncodingFilter</filter-name>  
  27.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  28.         <init-param>  
  29.             <param-name>encoding</param-name>  
  30.             <param-value>UTF-8</param-value>  
  31.         </init-param>  
  32.         <init-param>  
  33.             <param-name>forceEncoding</param-name>  
  34.             <param-value>true</param-value>  
  35.         </init-param>  
  36.     </filter>  
  37.     <filter-mapping>  
  38.         <filter-name>SpringEncodingFilter</filter-name>  
  39.         <url-pattern>/*</url-pattern>  
  40.     </filter-mapping>  
  41.       
  42.     <filter>  
  43.         <filter-name>shiroFilter</filter-name>  
  44.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  45.         <init-param>  
  46.             <param-name>targetFilterLifecycle</param-name>  
  47.             <param-value>true</param-value>  
  48.         </init-param>  
  49.     </filter>  
  50.     <filter-mapping>  
  51.         <filter-name>shiroFilter</filter-name>  
  52.         <url-pattern>/*</url-pattern>  
  53.     </filter-mapping>  
  54.   
  55.     <!– 日志记录 –>  
  56.     <context-param>  
  57.         <!– 日志配置文件路线 –>  
  58.         <param-name>log4jConfigLocation</param-name>  
  59.         <param-value>classpath:log4j.properties</param-value>  
  60.     </context-param>  
  61.     <context-param>  
  62.         <!– 日志页面包车型大巴基础代谢间隔 –>  
  63.         <param-name>log4jRefreshInterval</param-name>  
  64.         <param-value>6000</param-value>  
  65.     </context-param>  
  66.     <listener>  
  67.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  68.     </listener>  
  69.   
  70.     <listener>  
  71.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  72.     </listener>  
  73.       
  74.     <!– 幸免spring内部存款和储蓄器溢出监听器 –>  
  75.     <listener>  
  76.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  77.     </listener>  
  78.   
  79.     <!– springMVC大旨配置 –>  
  80.     <servlet>  
  81.         <servlet-name>dispatcherServlet</servlet-name>  
  82.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  83.         <init-param>  
  84.             <param-name>contextConfigLocation</param-name>  
  85.             <!–spingMVC的安插路线 –>  
  86.             <param-value>classpath:springmvc/spring-mvc.xml</param-value>  
  87.         </init-param>  
  88.         <load-on-startup>1</load-on-startup>  
  89.     </servlet>  
  90.     <!– 拦截设置 –>  
  91.     <servlet-mapping>  
  92.         <servlet-name>dispatcherServlet</servlet-name>  
  93.         <url-pattern>/</url-pattern>  
  94.     </servlet-mapping>  
  95.   
  96.     <!– 配置session超时时间,单位分钟 –>  
  97.     <session-config>  
  98.         <session-timeout>15</session-timeout>  
  99.     </session-config>  
  100.     <error-page>  
  101.         <error-code>404</error-code>  
  102.         <location>/WEB-INF/views/error/404.jsp</location>  
  103.     </error-page>  
  104.     <error-page>  
  105.         <error-code>401</error-code>  
  106.         <location>/WEB-INF/views/error/401.jsp</location>  
  107.     </error-page>  
  108. </web-app>  

package cn.temptation.dao;

    <!– 配置jsp 显示ViewResolver –>
    <bean
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
        <property name=”viewClass”
value=”org.springframework.web.servlet.view.JstlView”/>
        <property name=”prefix” value=”/WEB-INF/views/”/>
        <property name=”suffix” value=”.jsp”/>
    </bean>

<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:spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

 

import java.util.List;

</beans>

<!– Spring刷新Interceptor幸免内部存款和储蓄器泄漏 –>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>

此地不止配置了SpringMVC还要配置Shiro!

import javax.annotation.Resource;

 

<!– 设置session 超时时间为20秒钟 –>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>

5、登录页面login.jsp

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

 

==============================分割线==============================================

以下是私下认可登入的界面

import cn.temptation.entity.User;

web.xml

log4j配置

4858.com 13

@Repository
public class UserDaompl extends HibernateDaoSupport implements UserDao {

 

log4j.rootLogger=debug,debug,info,warn,error,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss }
[%t] [%c] [%p] – %m%n

 

// 用来注入sessionFactory
@Resource(name = “sessionFactory”)
public void setSessionFactoryOverride(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns=””
        xmlns:xsi=””
        xsi:schemaLocation=”

        version=”3.1″>

log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.debug.MaxFileSize=20MB
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss }
[%t] [%c] [%p] – %m%n
log4j.appender.debug.datePattern=’.’yyyy-MM-dd
log4j.appender.debug.Threshold = debug
log4j.appender.debug.append=true
#log4j.appender.debug.File=${webapp.root}/logs/debug.log
log4j.appender.debug.File=E:/webssmLogs/logs/debug.log

[html] view
plain copy

@Override
public User find(String userName, String password) {
List<?> users = getHibernateTemplate()
.find(“from User where userName=? and password=?”, userName,
password);
return users.size() > 0 ? users.get : null;//
通过Hibernate去数据库取
}

    <display-name>ChatRobot</display-name>
    <description>ChatRobot_Alpha_0.0.1</description>

log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.info.MaxFileSize=20MB
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss }
[%t] [%c] [%p] – %m%n
log4j.appender.info.datePattern=’.’yyyy-MM-dd
log4j.appender.info.Threshold = info
log4j.appender.info.append=true
#log4j.appender.info.File=${webapp.root}/logs/info.log
log4j.appender.info.File=E:/webssmLogs/logs/info.log

 

}

    <!– 编码过滤器 –>
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
#log4j.appender.warn.MaxFileSize=20MB
log4j.appender.warn.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss }
[%t] [%c] [%p] – %m%n
log4j.appender.warn.datePattern=’.’yyyy-MM-dd
log4j.appender.warn.Threshold = warn
log4j.appender.warn.append=true
#log4j.appender.warn.File=${webapp.root}/logs/warn.log
log4j.appender.warn.File=E:/webssmLogs/logs/warn.log

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8″  pageEncoding=”UTF-8″%>  
  2. <%  
  3.     String url = request.getRequestURL().toString();  
  4.     url = url.substring(0, url.indexOf(‘/’, url.indexOf(“//”) + 2));  
  5.     String context = request.getContextPath();  
  6.     url += context;  
  7.     application.setAttribute(“ctx”, url);  
  8. %>  
  9. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “;  
  10. <html>  
  11. <head>  
  12. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>  
  13. <title>Insert title here</title>  
  14. </head>  
  15. <body>  
  16.     <form action=”${ctx}/checkLogin.do” method=”post”>  
  17.         username: <input type=”text” name=”username”><br>  
  18.         password: <input type=”password” name=”password”><br>  
  19.         <input type=”submit” value=”登录”>  
  20.     </form>  
  21. </body>  
  22. </html>  

User

    <!– 配置DispatcherServlet –>
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
       
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!– 配置springMVC须要加载的安插文件–>
        <init-param>
            <param-name>contextConfigLocation</param-name>
           
<param-value>classpath:spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!– 相称全数诉求,此处也得以安插成 *.do 形式 –>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.error.MaxFileSize=20MB
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss }
[%t] [%c] [%p] – %m%n
log4j.appender.error.datePattern=’.’yyyy-MM-dd
log4j.appender.error.Threshold = error
log4j.appender.error.append=true
#log4j.appender.error.File=${webapp.root}/logs/error.log
log4j.appender.error.File=E:/webssmLogs/logs/error.log

 

package cn.temptation.entity;

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

在乎:配置中有log4j.appender.error=org.apache.log4j.DailyRollingFileAppender,

6、验证成功页面index.jsp

public class User {
private Integer id;
private String userName;
private String password;

</web-app>

也能够选拔代码中的log4j包下的类来促成,效果是一致的。

倘若客户名和密码精确后,跳转到的页面

public Integer getId() {
return id;
}

到此处大约遭受就搭建实现了,上面初叶测量检验

===============================分割线==================================================== 

 

public void setId(Integer id) {
this.id = id;
}

四、测试

java代码部分结构图

[html] view
plain copy

public String getUserName() {
return userName;
}

起头入一份数据库测验文件

4858.com 14

 

public void setUserName(String userName) {
this.userName = userName;
}

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘用户ID’,
  `email` varchar(255) NOT NULL COMMENT ‘顾客邮箱’,
  `password` varchar(255) NOT NULL COMMENT ‘客户密码’,
  `username` varchar(255) NOT NULL COMMENT ‘客商别名’,
  `role` varchar(255) NOT NULL COMMENT ‘客户身份’,
  `status` int(1) NOT NULL COMMENT ‘客户情状’,
  `regTime` datetime NOT NULL COMMENT ‘注册时间’,
  `regIp` varchar(255) NOT NULL COMMENT ‘注册IP’,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES (‘1’, ‘xxx’, ‘xxxxx’, ‘xxxxx’, ‘root’, ‘0’,
‘2017-03-28 09:40:31’, ‘127.0.0.1’);
SET FOREIGN_KEY_CHECKS=1;

================================分割图=====================================================

  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8″  
  2.     pageEncoding=”UTF-8″%>  
  3. <%@ taglib prefix=”shiro” uri=”;  
  4. <%  
  5.     String url = request.getRequestURL().toString();  
  6.     url = url.substring(0, url.indexOf(‘/’, url.indexOf(“//”) + 2));  
  7.     String context = request.getContextPath();  
  8.     url += context;  
  9.     application.setAttribute(“ctx”, url);  
  10. %>  
  11. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “;  
  12. <html>  
  13. <head>  
  14. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>  
  15. <title>Shiro登入实例</title>  
  16. </head>  
  17. <body>  
  18.     <h1>Shiro登录实例</h1><a href=”${ctx}/logout.html”>退出</a>  
  19.     <p>一、验证当前客户是还是不是为”访客”,即未表明(包涵未记住)的客商</p>  
  20.     <shiro:guest>    
  21.         Hi there!  Please <a href=”login.jsp”>Login</a> or <a href=”signup.jsp”>Signup</a> today!    
  22.     </shiro:guest>  
  23.     <p>二、认证通过或已记住的用户</p>  
  24.     <shiro:user>    
  25.         Welcome back John!  Not John? Click <a href=”login.jsp”>here<a> to login.   
  26.     </shiro:user>  
  27.     <p>三、已评释通过的客户。不带有已记住的客商,那是与user标签的分别所在。</p>  
  28.     <shiro:authenticated>    
  29.         <a href=”updateAccount.jsp”>Update your contact information</a>.    
  30.     </shiro:authenticated>  
  31.     <p>四、未认证通过客商,与authenticated标签相呼应。与guest标签的分化是,该标签包涵已记住客户。</p>  
  32.     <shiro:notAuthenticated>    
  33.         Please <a href=”login.jsp”>login</a> in order to update your credit card information.    
  34.     </shiro:notAuthenticated>    
  35.     <p>五、输出当前顾客音信,经常为记名帐号音信</p>  
  36.     Hello, <shiro:principal/>, how are you today?    
  37.     <p>六、验证当前顾客是或不是属于该角色</p>  
  38.     <shiro:hasRole name=”administrator”>    
  39.         <a href=”admin.jsp”>Administer the system</a>    
  40.     </shiro:hasRole>    
  41.     <p>七、与hasRole标签逻辑相反,当客商不属于该剧中人物时说明通过</p>  
  42.     <shiro:lacksRole name=”administrator”>    
  43.         Sorry, you are not allowed to administer the system.    
  44.     </shiro:lacksRole>    
  45.     <p>八、验证当前客商是还是不是属于以下猖獗二个剧中人物。</p>  
  46.     <shiro:hasAnyRoles name=”developer,manager,administrator”>  
  47.         You are either a developer,manager, or administrator.    
  48.     </shiro:hasAnyRoles>  
  49.    <p>九、验证当前顾客权限。</p>  
  50.     <shiro:hasPermission name=”create”>    
  51.       <p>当前客户全体扩大的权杖!!!!!!!!!!!!!</p>  
  52.     </shiro:hasPermission>    
  53.   
  54.     <shiro:hasPermission name=”delete”>    
  55.        <p>当前客商具有删除的权位!!!!!!!!!!!!!</p>  
  56.     </shiro:hasPermission>    
  57. </body>  
  58. </html>  

public String getPassword() {
return password;
}

接下去配置类

UserController类

别的页面就不说了,具体看工程吧!

public void setPassword(String password) {
this.password = password;
}

UserController

package web.ssm.controller;

 

@Override
public String toString() {
return “User [, userName=” + userName + “, password=”

package com.chatRobot.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

7、controller层来探望

  • password + “]”;
    }

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

此处/{id}/showUser首假使来评释是不是连接成功(现在不能够测验了),当然在工程里你也得以到src/test/java里的包com.lin.service下的UserServiceTest.java,这里我也写了一个单元测量试验的类。

}

import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import web.ssm.entity.User;
import web.ssm.service.UserService;

 

User.hbm.xml

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(“/user”)
public class UserController {
private static final String DEBUG_PREFIX = “[UserController]”;

[java] view
plain copy

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping
DTD 3.0//EN”
“” >
<hibernate-mapping package=”cn.temptation.entity”>
<class name=”User” table=”user”>
<id name=”id”>
<generator />
</id>
<property name=”userName” length=”12″ not-null=”true”
unique=”true”/>
<property name=”password” length=”12″ not-null=”true”/>
</class>
</hibernate-mapping>

@Controller
@RequestMapping(“/user”)
public class UserController {

private static final String INFO_PREFIX = “<UserController>”;

 

6)编写视图层的jsp代码

    @Resource
    private IUserService userService;

private static final String ERROR_PREFIX = “UserController->”;

  1. package com.lin.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.shiro.SecurityUtils;  
  7. import org.apache.shiro.authc.UsernamePasswordToken;  
  8. import org.apache.shiro.subject.Subject;  
  9. import org.slf4j.Logger;  
  10. import org.slf4j.LoggerFactory;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.ui.Model;  
  14. import org.springframework.web.bind.annotation.PathVariable;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17. import org.springframework.web.bind.annotation.ResponseBody;  
  18.   
  19. import com.lin.domain.User;  
  20. import com.lin.realm.ShiroDbRealm;  
  21. import com.lin.service.UserService;  
  22. import com.lin.utils.CipherUtil;  
  23.   
  24. @Controller  
  25. public class UserControler {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     @Autowired  
  28.     private UserService userService;  
  29.       
  30.     /** 
  31.      * 验证springmvc与batis连接成功 
  32.      * @param id 
  33.      * @param request 
  34.      * @return 
  35.      */  
  36.     @RequestMapping(“/{id}/showUser”)  
  37.     public String showUser(@PathVariable int id, HttpServletRequest request) {  
  38.         User user = userService.getUserById(id);  
  39.         System.out.println(user.getName());  
  40.         request.setAttribute(“user”, user);  
  41.         return “showUser”;  
  42.     }  
  43.       
  44.     /** 
  45.      * 开端登录界面 
  46.      * @param request 
  47.      * @return 
  48.      */  
  49.     @RequestMapping(“/login.do”)  
  50.     public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
  51.         logger.debug(“来自IP[” + request.getRemoteHost() + “]的访问”);  
  52.         return “login”;  
  53.     }  
  54.       
  55.     /** 
  56.      * 验证客户名和密码 
  57.      * @param request 
  58.      * @return 
  59.      */  
  60.     @RequestMapping(“/checkLogin.do”)  
  61.     public String login(HttpServletRequest request) {  
  62.         String result = “login.do”;  
  63.         // 获得顾客名  
  64.         String username = request.getParameter(“username”);  
  65.         //取得 密码,并用MD5加密  
  66.         String password = CipherUtil.generatePassword(request.getParameter(“password”));  
  67.         //String password = request.getParameter(“password”);  
  68.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  69.           
  70.         Subject currentUser = SecurityUtils.getSubject();  
  71.         try {  
  72.             System.out.println(“—————————-“);  
  73.             if (!currentUser.isAuthenticated()){//使用shiro来验证  
  74.                 token.setRememberMe(true);  
  75.                 currentUser.login(token);//验证剧中人物和权杖  
  76.             }  
  77.             System.out.println(“result: ” + result);  
  78.             result = “index”;//验证成功  
  79.         } catch (Exception e) {  
  80.             logger.error(e.getMessage());  
  81.             result = “login。do”;//验证退步  
  82.         }  
  83.         return result;  
  84.     }  
  85.     
  86.     /** 
  87.      * 退出 
  88.      * @return 
  89.      */  
  90.     @RequestMapping(value = “/logout”)    
  91.     @ResponseBody    
  92.     public String logout() {    
  93.     
  94.         Subject currentUser = SecurityUtils.getSubject();    
  95.         String result = “logout”;    
  96.         currentUser.logout();    
  97.         return result;    
  98.     }    
  99.        
  100. }  

在webapp下开创新的文书夹view将测量试验的登入和登入成功的jsp放到这些文件夹下

    @RequestMapping(“/showUser.do”)
    public void selectUser(HttpServletRequest request,
HttpServletResponse response) throws IOException {
        request.setCharacterEncoding(“UTF-8”);
        response.setCharacterEncoding(“UTF-8”);
        long userId = Long.parseLong(request.getParameter(“id”));
        User user = this.userService.selectUser(userId);
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(user));
        response.getWriter().close();
    }

//日志
private static Logger logger = Logger.getLogger(UserController.class);

再来看看效果呢!

login.jsp

}

@Autowired
private UserService userService;

4858.com 15

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping
DTD 3.0//EN”
“” >
<hibernate-mapping package=”cn.temptation.entity”>
<class name=”User” table=”user”>
<id name=”id”>
<generator />
</id>
<property name=”userName” length=”12″ not-null=”true”
unique=”true”/>
<property name=”password” length=”12″ not-null=”true”/>
</class>
</hibernate-mapping>

IUserDao

@RequestMapping(method={RequestMethod.GET}, value=”/selectUser”)
@ResponseBody
public User selectUser(HttpServletRequest request, HttpServletResponse
response){
String sid = request.getParameter(“id”);
int id = Integer.valueOf(sid);
User user = userService.selectByPrimaryKey(id);
return user;
}

一体化学工业程无需付费下载:

login-success.jsp

package com.chatRobot.dao;

@RequestMapping(method={RequestMethod.GET}, value=”/insertUser”)
@ResponseBody
public int insertUser(HttpServletRequest request, HttpServletResponse
response){
String name = request.getParameter(“name”);
User user = new User();
user.setName(name);
userService.insertSelective(user);
return 1;
}

 

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
charset=UTF-8″>
<title>登入成功</title>
</head>
<body>
登陆成功
</body>
</html>

import com.chatRobot.model.User;

@RequestMapping(method={RequestMethod.GET}, value=”/deleteUser”)
@ResponseBody
public int deleteUser(HttpServletRequest request, HttpServletResponse
response){
String sid = request.getParameter(“id”);
int id = Integer.valueOf(sid);
userService.deleteByPrimaryKey(id);
return 1;
}
}

7)项目安顿到tomcat中运营服务

public interface IUserDao {

=======================================分割线=====================================

    User selectUser(long id);

UserDao类

}

package web.ssm.dao;

User

import org.springframework.stereotype.Repository;

package com.chatRobot.model;

import web.ssm.entity.User;

import java.util.Date;

@Repository
public interface UserDao {
public User selectByPrimaryKey(Integer id);
public void insertSelective(User user);
public void deleteByPrimaryKey(Integer id);
}

public class User {

================================分割线======================================

    private long id;
    private String email;
    private String password;
    private String username;
    private String role;
    private int status;
    private Date regTime;
    private String regIp;

User类

    public long getId() {
        return id;
    }

package web.ssm.entity;

    public void setId(int id) {
        this.id = id;
    }

import java.io.Serializable;

    public String getEmail() {
        return email;
    }

public class User implements Serializable {

    public void setEmail(String email) {
        this.email = email;
    }

private static final long serialVersionUID = 5533446196251002012L;

    public String getPassword() {
        return password;
    }

private Integer id;
private String name;

    public void setPassword(String password) {
        this.password = password;
    }

public User() {}

    public String getUsername() {
        return username;
    }

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}

    public void setUsername(String username) {
        this.username = username;
    }

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return “User [id=” + id + “, name=” + name + “]”;
}
}

    public String getRole() {
        return role;
    }

=================================分割线=============================================

    public void setRole(String role) {
        this.role = role;
    }

log4j类

    public int getStatus() {
        return status;
    }

package web.ssm.log4j;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Priority;
/**
* 自定义文件输出destination
*/
public class BackUpAppender extends DailyRollingFileAppender {
@Override
public boolean isAsSevereAsThreshold(Priority priority) {
//只推断是还是不是等于,而不推断优先级
return this.getThreshold().equals(priority);
}
}

    public void setStatus(int status) {
        this.status = status;
    }

================================分割线===============================================

    public Date getRegTime() {
        return regTime;
    }

UserService类

    public void setRegTime(Date regTime) {
        this.regTime = regTime;
    }

package web.ssm.service;

    public String getRegIp() {
        return regIp;
    }

import web.ssm.entity.User;

    public void setRegIp(String regIp) {
        this.regIp = regIp;
    }

public interface UserService {
/**
* @方法描述: 依据id查询对象
* @作者: 1603254
* @日期: 2016-12-2-上午11:09:58
* @param id
* @return
* @重回类型: User
*/
public User selectByPrimaryKey(Integer id);

}

/**
* @方法描述: 插入对象
* @作者: 1603254
* @日期: 2016-12-2-上午11:10:01
* @param user
* @再次回到类型: void
*/
public void insertSelective(User user);

IUserService

/**
* @方法描述: 依照id删除对象
* @作者: 1603254
* @日期: 2016-12-2-上午11:10:04
* @param id
* @重临类型: void
*/
public void deleteByPrimaryKey(Integer id);
}

package com.chatRobot.service;

=================================分割线============================================

import com.chatRobot.model.User;

UserServiceImple类

public interface IUserService {

package web.ssm.service.impl;

    public User selectUser(long userId);

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

}

import web.ssm.dao.UserDao;
import web.ssm.entity.User;
import web.ssm.service.UserService;

UserServiceImpl

@Service
public class UserServiceImpl implements UserService{

package com.chatRobot.service.impl;

@Autowired
private UserDao userDao;

import com.chatRobot.dao.IUserDao;
import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import org.springframework.stereotype.Service;

@Cacheable(value=”common”,key=”‘id_’+#id”)
public User selectByPrimaryKey(Integer id) {
System.out.println(“======================”);
System.out.println(“======================”);
System.out.println(“======================”);
return userDao.selectByPrimaryKey(id);
}

import javax.annotation.Resource;

@CachePut(value=”common”,key=”#user.getName()”)
public void insertSelective(User user) {
userDao.insertSelective(user);
System.out.println(“########################”);
System.out.println(“########################”);
System.out.println(“########################”);
}

@Service(“userService”)
public class UserServiceImpl implements IUserService {

@CacheEvict(value=”common”,key=”‘id_’+#id”)
public void deleteByPrimaryKey(Integer id) {
userDao.deleteByPrimaryKey(id);
System.out.println(“******************************”);
System.out.println(“******************************”);
System.out.println(“******************************”);
}
}

    @Resource
    private IUserDao userDao;

在意:各类注脚的作用请自行百度

    public User selectUser(long userId) {
        return this.userDao.selectUser(userId);
    }

=================================分割线=============================================

}

RedisCache类

UserDao.xml

package web.ssm.utils;

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN”
“;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

<!– 设置为IUserDao接口方法提供sql语句配置 –>
<mapper namespace=”com.chatRobot.dao.IUserDao”>

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

    <select id=”selectUser” resultType=”User”
parameterType=”long”>
        SELECT * FROM user WHERE id = #{id}
    </select>

public class RedisCache implements Cache{

</mapper>

private RedisTemplate<String, Object> redisTemplate;
private String name;
public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}

然后新建个测验类,来测量检验mybatis

public void setRedisTemplate(RedisTemplate<String, Object>
redisTemplate) {
this.redisTemplate = redisTemplate;
}

IUserDaoTest

public void setName(String name) {
this.name = name;
}

package com.chatRobot.dao;

@Override
public String getName() {
// TODO Auto-generated method stub
return this.name;
}

import com.chatRobot.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@Override
public Object getNativeCache() {
// TODO Auto-generated method stub
return this.redisTemplate;
}

// 加载spring配置文件
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({“classpath:spring-mybatis.xml”})
public class IUserDaoTest {

@Override
public ValueWrapper get(Object key) {
// TODO Auto-generated method stub
System.out.println(“get key”);
final String keyf = key.toString();
Object object = null;
object = redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] key = keyf.getBytes();
byte[] value = connection.get(key);
if (value == null) {
return null;
}
return toObject(value);
}
});
return (object != null ? new SimpleValueWrapper(object) : null);
}

    @Autowired
    private IUserDao dao;

@Override
public void put(Object key, Object value) {
// TODO Auto-generated method stub
System.out.println(“put key”);
final String keyf = key.toString();
final Object valuef = value;
final long liveTime = 86400;
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyb = keyf.getBytes();
byte[] valueb = toByteArray(valuef);
connection.set(keyb, valueb);
if (liveTime > 0) {
connection.expire(keyb, liveTime);
}
return 1L;
}
});
}

    @Test
    public void testSelectUser() throws Exception {
        long id = 1;
        User user = dao.selectUser(id);
        System.out.println(user.getUsername());
    }

private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
}catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}

}

private Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}

运营后结果应当是会在决定台出口id为1的客户名,没得逞的话就找BUG去吧…

@Override
public void evict(Object key) {
// TODO Auto-generated method stub
System.out.println(“del key”);
final String keyf = key.toString();
redisTemplate.execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.del(keyf.getBytes());
}
});
}

雄起雌伏新建个页面来测量试验springmvc和mybatis

@Override
public void clear() {
// TODO Auto-generated method stub
System.out.println(“clear key”);
redisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return “ok”;
}
});
}

index.html

@Override
public <T> T get(Object key, Class<T> type) {
// TODO Auto-generated method stub
return null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset=”UTF-8″>
    <title>test</title>
</head>
<script>
    function selectUser() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById(“test”).innerHTML =
xmlhttp.responseText;
            }
        }
        xmlhttp.open(“POST”, “user/showUser.do”, true);
        xmlhttp.setRequestHeader(“Content-type”,
“application/x-www-form-urlencoded”);
        xmlhttp.send(“id=1”);
    }
</script>
<body>
<p id=”test”>Hello World!</p>
<button type=”button” onclick=”selectUser()”>onclick
test</button>
</body>
</html>

@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
// TODO Auto-generated method stub
return null;
}

新建达成后布署项目周转条件,点击Run-Edit Configurations…

}

点击加号新建运营境况,选用汤姆cat Server-Local

=======================================分割线==================================================

4858.com 16

 

入选新建好的服务器,右侧选择Deployment,点击加号-Atifact…

4858.com 17

采纳第二项

4858.com 18

然后在左边Application context配置你的类小名

4858.com 19

末尾运营品种,在开荒的页面中式茶食击按键测量试验,成功的话会在页面上海展览中心示id为1的客户音讯

正文永恒更新链接地址:http://www.linuxidc.com/Linux/2017-05/143307.htm

4858.com 20

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有