Spring MVC集成Spring Data Reids和Spring Session实现Session共享

说明:Spring MVC中集成Spring Data Redis和Spring Session时版本是一个坑点,比如最新版本的Spring Data Redis已经不包含Jedis了,需要自行引入。且最新版本的2.0.1会与Spring MVC 4.1.4有冲突,估计写法错了。所以要明确引入的Spring MVC版本和Spring Data Redis和Spring Session版本。

小提示:如果想要官方明确的版本可以参考Spring Boot的版本,比如我使用了1.4.7的Spring Boot时,它们用的就是MVC4.3.9,Redis1.7.11,Jedis2.8.2。

实际集成步骤:

POM:

<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>com.jsoft.testspring</groupId>
    <artifactId>testmvchelloworld</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>testmvchelloworld Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Servlet Library -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring Core -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>

        <!-- Spring Web -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>

        <!-- Spring Web MVC -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>

        <!-- Redis -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.2</version>
        </dependency>

        <!-- Session -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.2.2.RELEASE</version>
        </dependency>        

    </dependencies>
    <build>
        <finalName>testmvchelloworld</finalName>
        <plugins>
            <!-- Config: Maven Tomcat Plugin -->
            <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
            <!-- http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!-- Config: contextPath and Port (Default:8080) -->
                <!--
                <configuration>
                    <path>/</path>
                    <port>8899</port>
                </configuration>
                 -->
            </plugin>
            <!-- Config: Maven Jetty Plugin -->
            <!-- http://mvnrepository.com/artifact/org.mortbay.jetty/jetty-maven-plugin -->
            <!-- http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.3.v20170317</version>
                <!-- Config: contextPath and Port (Default:8080) -->
                <!--
                <configuration>
                    <httpConnector>
                        <port>8899</port>
                    </httpConnector>
                    <webAppConfig>
                        <contextPath>/</contextPath>
                    </webAppConfig>
                </configuration>
                 -->
            </plugin>
        </plugins>
    </build>
</project>

web.xml

<web-app id="WebApp_ID" version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                                 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

   <display-name>Spring MVC Application</display-name>

    <!-- Session -->
    <filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

   <servlet>
       <servlet-name>spring-mvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!-- 默认:[servlet-name]-servlet.xml -->
       <!-- 通过初始化参数,指定xml文件的位置 -->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>/WEB-INF/applicationContext.xml</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
   </servlet>   

   <servlet-mapping>
       <servlet-name>spring-mvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

   <!-- 添加其它xml配置 -->
   <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/other-context.xml</param-value>
   </context-param>
   <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

</web-app>

说明:Session的拦截必须放在第一位。

other-content.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                             http://www.springframework.org/schema/beans/spring-beans.xsd
                             http://www.springframework.org/schema/context
                             http://www.springframework.org/schema/context/spring-context.xsd
                             http://www.springframework.org/schema/mvc
                             http://www.springframework.org/schema/mvc/spring-mvc.xsd">

   <context:component-scan base-package="com.jsoft.testspring"/>

   <context:annotation-config/>

    <!-- Redis -->
   <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
       <property name="hostName" value="127.0.0.1" />
       <property name="port" value="6379" />
   </bean>
   <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
       <property name="connectionFactory" ref="jedisConnectionFactory" />
   </bean>   

   <!-- Session -->
   <bean id="redisHttpSessionConfiguration"  class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" >
      <property name="maxInactiveIntervalInSeconds" value="120" />
   </bean>

</beans>

这个文件配置Redis和Session。如果你运行出错了,参考:http://www.cnblogs.com/EasonJim/p/7815712.html

测试代码:

package com.jsoft.testspring.testmvchelloworld;

import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(method=RequestMethod.GET)
    public String printHello(ModelMap model, HttpSession session){
        // Redis
        System.out.println(stringRedisTemplate.opsForValue().get("test"));
        // Session
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }
        session.setAttribute("uid", uid);
        System.out.println(session.getId());
        model.addAttribute("message","Hello Spring MVC Framework!");
        return "hello";
    }

    @RequestMapping("/set")
    @ResponseBody
    public String set() {
        stringRedisTemplate.opsForValue().set("test", new Date().toString());
        return "hello";
    }
}

示例工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test23/testmvchelloworld

参考:

http://dorole.com/1422/

http://www.cnblogs.com/qlong8807/p/5557271.html

http://blog.csdn.net/java123student/article/details/54863676

http://blog.csdn.net/patrickyoung6625/article/details/45694157

时间: 2024-10-06 15:17:12

Spring MVC集成Spring Data Reids和Spring Session实现Session共享的相关文章

Spring MVC集成slf4j-logback

1.  Spring MVC集成slf4j-log4j 关于slf4j和log4j的相关介绍和用法,网上有很多文章可供参考,但是关于logback的,尤其是Spring MVC集成logback的,就相对少一些了,而且其中一些也有着这样那样的问题.进入正题之前先简单介绍下Spring MVC集成slf4j-log4j的过程,如下: 1)      在pom.xml文件中添加slf4j-log4j的依赖,完成后的classpath中将新增三个jar包,分别是:slf4j-api.jar.log4j

第二十六天 蛰伏的Hibernate遇到春日的暖阳 —Spring MVC 集成Hibernate使用(一)

6月7日,晴."纷纷红紫已成尘,布谷声中夏令新.夹路桑麻行不尽,始知身是太平人."        Hibernate和Spring的香艳相逢,不仅是Bean和Bean之间电光火石般的碰撞,也是XML和XML之间的萍水聚首.两种奇妙的架构,携手闯荡江湖,不仅塑造了依赖注入淋漓酣畅的快感,也让J2EE蹿红大半个地球. 第二十六天 蛰伏的Hibernate遇到春日的暖阳 -Spring MVC 集成Hibernate使用(一)

Spring MVC 学习总结(六)——Spring+Spring MVC+MyBatis框架集成

目录 一.新建一个基于Maven的Web项目    二.创建数据库与表    三.添加依赖包    四.新建POJO实体层    五.新建MyBatis SQL映射层    六.JUnit测试数据访问    七.完成Spring整合MyBatis配置    八.配置web.xml加载Spring容器与MVC    九.创建服务层     十.完成商品管理功能    10.1.商品列表与分页    11.2.删除与多删除功能    11.3.新增商品功能    11.4.编辑商品功能    11.

string与spring mvc集成多种技术构建复杂工程(转载)

使用spring集成其他技术,最基本的配置都是模板化的,比如配置视图模板引擎.数据库连接池.orm框架.缓存服务.邮件服务.rpc调用等,以spring的xml配置为例,我将这些配置过程整理出来,并不时更新,以备参考! spring 在普通的java工程中引入spring,只需要配置以下依赖 1 2 3 4 5 <dependency>     <groupId>org.springframework</groupId>     <artifactId>sp

spring mvc 集成mongoDB项目 例子

免费下载项目:点击打开链接 这个pom内容有点多,有的可以不用 <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

Spring MVC 学习笔记-----data binding

Servlet中的输入参数为都是string类型,而spring mvc通过data bind机制将这些string 类型的输入参数转换为相应的command object(根据view和controller之间传输数据的具体逻辑,也可称为model attributes, domain model objects).在这个转换过程中,spring实际是先利用java.beans.PropertyEditor中的 setAdText方法来把string格式的输入转换为bean属性, 亦可通过继承

Spring MVC集成Tiles使用方法

首先,我们定义一个总体的tiles视图 /tiles/mainTemplate.jsp首先使用:<tiles:getAsString name="title"/>打印tiles配置文件中定义的字符串属性title然后是分别加载header,content,footer三个jsp页面,共同组成mainTemplate.jsp <%@taglib uri="http://jakarta.apache.org/struts/tags-tiles" pre

Java Spring MVC项目搭建(一)——Spring MVC框架集成

1.Java JDK及Tomcat安装 我这里安装的是JDK 1.8 及 Tomcat 8,安装步骤详见:http://www.cnblogs.com/eczhou/p/6285248.html 2.下载Eclipse并安装 我这里安装的是Java EE neon 64位版本. 3.建立Spring MVC项目 3.1.打开安装好的eclipse ,选择File->new->other.在弹出的框内选择Web->Dynamic Web Project , 选择Next. 3.2.给项目起

Spring、Spring MVC、Mybatis、Dubbo、Spring security整合日记(一)

使用Idea 15作为开发工具 一.四个模块 api    作为接口,jar包,提供依赖 core  基础模块,提供实体类,工具类,jar包,提供依赖 consumer dubbo中的消费者,控制层,war包,依赖api.core provider dubbo中的提供者,业务层,war包,依赖api.core 二.Maven依赖 ①.dubbo(parent) pom.xml <groupId>com.zhf</groupId> <artifactId>dubbo<