【问题标题】:Spring mvc unable to fetch attribute set in sessionSpring mvc无法获取会话中设置的属性
【发布时间】:2014-07-04 09:22:47
【问题描述】:

我正在使用 Spring MVC 和 JQUERY 来实现将数据从表单提交到服务器的两步流程:

  1. JQUERY ajax POST 请求会在点击文件浏览时将文件数据从表单提交到服务器。这会将文件存储在文件服务器上,并在存储文件信息的数据库中创建一个条目,模式设置为草稿。

  2. 当用户点击表单提交按钮时,其他表单数据,如“文件标题”等,将被提交到服务器。进入数据库的条目现在应该将模式设置为“完成”。

在第 1 步中,我将文件数据(例如数据库中列的 Id、文件名)设置为会话属性。

/**
 * Upload single file using Spring Controller
 */
@RequestMapping(value = "/uploadFileDraft", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void uploadFileDraft(@RequestParam("file") MultipartFile file,Model map,  HttpSession httpSession) {

    PostDto draftPost = new PostDto();
    draftPost.setPostedDate(new Date());
    draftPost.setStrRawFileName(file.getOriginalFilename());

    //Logic to save this object into database.
    postService.uploadPostDraft(draftPost);

    //now set the data into session object
    httpSession.setAttribute("filePostDraftDto", draftPost);
}

现在在第 2 步中,我尝试从会话中检索此 Dto 对象并调用另一个服务。但他的对象不存在于会话中。

@RequestMapping(value = "/uploadFilePublish", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void uploadVideoPublish(@RequestParam("strVideoTitle") String strVideoTitle, Model map, HttpSession httpSession) {
    PostDto postDtoDraft = null;
        if(null!= httpSession.getAttribute("filePostDraftDto"))
        {
            postDtoDraft = (PostDto)httpSession.getAttribute("filePostDraftDto");
        }


        if(null!=postDtoDraft )
        {
            System.out.println("file name from session is: "+postDtoDraft.getStrFileName());
        }
        else
        {
            System.out.println("error: postDtoDraft is null");
        }
    }

}

每次都会打印以下内容:error: postDtoDraft is null

我的 web.xml 是:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
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>WebConnect</display-name>

<!-- Spring Security Configuration File -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlet and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>


<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <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>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
<!-- session time out set as 30 minites -->
<session-config>
    <session-timeout>30</session-timeout>
</session-config>

applicationConfig.xml 是:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<context:annotation-config />
<context:component-scan base-package="com.mycomp.myproj" />
<context:spring-configured />

<neo4j:config graphDatabaseService="graphDatabaseService" />
<neo4j:repositories base-package="com.mycomp.myproj.repository" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- setting maximum upload size -->
    <property name="maxUploadSize" value="10000000000" />

</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:default-servlet-handler />
<mvc:annotation-driven />

<tx:annotation-driven mode="aspectj"
    transaction-manager="transactionManager" />

spring-security.xml 是:

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

<http pattern="/resources/**" security="none" />

<http authentication-manager-ref="userAuthManager">
    <intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/register" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login login-page='/' authentication-failure-url="/" />
    <logout invalidate-session="true" logout-success-url="/" logout-url="/j_spring_security_logout" />
    <session-management invalid-session-url="/">
        <concurrency-control max-sessions="1"
            expired-url="/" />
    </session-management>
</http>

<beans:bean id="userAuthManager" class="com.inw.pyt.security.UserAuthManager">
</beans:bean>

<beans:bean id="passwordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

【问题讨论】:

  • 你能看到 JSESSIONID 设置了吗?如果您在点击uploadVideoPublish 方法后打印会话中的所有属性,您看到您的属性和值了吗?为什么对postService.uploadPostDraft(); 的调用不带参数?似乎应该把你的draftPost 保存起来。
  • 正确, postService.uploadPostDraft() 应该接受参数。我只是在发布我的问题时错过了它。相应地编辑了问题。当我打印所有属性时,它不会显示我的属性甚至 JSESSIONID。
  • JSESSIONID 将是一个 cookie 或可能是一个 GET 参数。如果您在设置会话变量后立即打印它,您会在那里看到它吗?

标签: spring spring-mvc spring-security httpsession


【解决方案1】:

解决此问题的方法是 PostDto 类不可序列化。一旦我更改 PostDto 以实现 Serializable,它就开始工作了。似乎 Spring 有一个限制,它不允许对象存储在会话中,除非它们是可序列化的。

当我尝试使用 Spring 自己的 @SessionAttributes 而不是 HttpSession 来设置和获取会话时,我发现了这个问题。然后在将属性设置为 Spring 模型时,我在控制台中收到以下错误:

StandardWrapperValve[mvc-dispatcher]: Servlet.service() for servlet mvc-dispatcher threw exception
java.lang.IllegalArgumentException: setAttribute: Non-serializable attribute with name filePostDraftDto
    at org.apache.catalina.session.ManagerBase.checkSessionAttribute(ManagerBase.java:835)
    at org.apache.catalina.session.StandardSession.setAttribute(StandardSession.java:1840)
    at org.apache.catalina.session.StandardSessionFacade.setAttribute(StandardSessionFacade.java:178)
    at org.springframework.web.context.request.ServletRequestAttributes.setAttribute(ServletRequestAttributes.java:131)
    at org.springframework.web.bind.support.DefaultSessionAttributeStore.storeAttribute(DefaultSessionAttributeStore.java:55)
    at org.springframework.web.method.annotation.SessionAttributesHandler.storeAttributes(SessionAttributesHandler.java:124)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 2017-12-18
    • 2012-06-18
    • 2023-03-09
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多