spring session实现session统一管理(jdbc实现)
阅读原文时间:2023年07月09日阅读:2

最近在看一些关于spring session 的知识,特做一个笔记记录一下。

在项目中经常会遇到这么一种情况,同一个web项目有时需要部署多份,然后使用nginx实现负载均衡,那么遇到的问题就是,部署多份之后,如何实现一个session的共享功能。此时就可以使用spring session来实现。

参考网址:http://docs.spring.io/spring-session/docs/current/reference/html5/guides/httpsession-jdbc-xml.html

1.引入spring session 的jar包依赖。

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.huan.spring</groupId>
        <artifactId>spring-session-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>02_spring_session_jdbc</artifactId>
    <packaging>war</packaging>
    <name>02_spring_session_jdbc Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-jdbc</artifactId>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
        </dependency>
    </dependencies>
    <build>
        <finalName>02_spring_session_jdbc</finalName>
    </build>
</project>

spring 的版本:4.1.5.RELEASE spring session-jdbc的版本:1.2.0.RELEASE

二、配置spring session的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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-4.1.xsd">
    <context:annotation-config />
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 基本属性driverClassName、 url、user、password -->
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
        <property name="username" value="scott" />
        <property name="password" value="tiger" />
    </bean>
    <bean
        class="org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration" />
    <bean
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
</beans>

三、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring-session.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>
</web-app>

四、编写测试代码

1.登录界面(login.jsp)

<body>
    <form action="LoginServlet" method="post">
        <table>
            <tbody>
                <tr>
                    <td>用户名:</td>
                    <td><input name="loginName" required="required" /></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" name="password" required="required"></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="2"><input type="submit" value="登录"></td>
                </tr>
            </tfoot>
        </table>
    </form>
</body>

2.后台的逻辑处理

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = -8455306719565291102L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("UTF-8");
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        request.getSession().setAttribute("login", true);
        request.getSession().setAttribute(loginName, password);
        response.sendRedirect(request.getContextPath() + "/show.jsp");
    }
}

3.展示界面(show.jsp ---> 没有登录访问次界面,直接跳到登录界面)

输出session中的值: <% if (request.getSession().getAttribute("login") == null) { response.sendRedirect(request.getContextPath() + "/login.jsp"); } %> <% Enumeration enumeration = request.getSession().getAttributeNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); Object value = request.getSession().getAttribute(key); out.println(key + " --- " + value); } %>
----------------- jsessionId:<%=request.getSession().getId() %> ---------------------- <%=request.getRemoteAddr()%> <%=request.getRemotePort()%> <%=request.getRemoteHost()%> <%=request.getRemoteUser()%> <%=request.getHeader("X-Real-IP")%> <%=request.getHeader("Host")%> <%=request.getHeader("X-Forwarded-For")%> <%=request.getLocalPort()%>

4.nginx的简单配置 --- 启动ngnix

5.分别启动2个tomcat容器

6.修改其中一个tomcat容器中的show.jsp的值,随便加一个内容,以示区分。

7.页面上访问


 
 8.可以到oracle数据区中进行查询,用到的表

select * from SPRING_SESSION t;
select * from SPRING_SESSION_ATTRIBUTES t;

9.用到的sql语句所在的jar包目录