简体   繁体   中英

Spring mvc unable to fetch attribute set in session

I am using Spring MVC and JQUERY to implement a 2 step process to submit data from a form to the server:

  1. A JQUERY ajax POST request would submit the file data from form to the server on click of file browse. This would store the file on file server and create an entry into the database storing the file information, with the mode set as draft.

  2. When user clicks on form submit button, the other form data such as 'File Title' and so on, would be submitted to the server. The entry into database should now set the mode to 'Complete'.

At step 1 I am setting the file data such as Id of the column in database, name of file into a session attribute.

/**
 * 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);
}

Now in step 2 I trying to retrieve this Dto object from session and calling another service. But he object does not exist into the session.

@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");
        }
    }

}

The following gets printed everytime: error: postDtoDraft is null

My web.xml is:

<?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>

The applicationConfig.xml is:

<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" />

The spring-security.xml is:

<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" />

The solution to this issue was with the class PostDto not being serializable. Once I changed PostDto to implement Serializable it started working. Seems like there is a restriction with Spring, which does not let objects to be stored in session unless they are serializable.

I found the issue when I tried to use Spring's own @SessionAttributes to set and get from the session, instead of the HttpSession. Then while setting the attribute into the Spring model I got the following error in the console:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM