Spring Web MVC Cannot upload file to server - java

I am trying to upload an image via Spring MVC.
Controller.java
#SuppressWarnings("resource")
#RequestMapping(value = "/editprofilehandler", method=RequestMethod.POST)
public ModelAndView editProfileHandlerController(#ModelAttribute("userForm") Users users
, ModelMap model, HttpSession session)
{
if(session.getAttribute("session_user") != null){
try
{
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile file = users.getImage();
String fileName = file.getOriginalFilename();
inputStream = file.getInputStream();
File newFile = new File("C:/Documents and Settings/smart/workspace/Pir/WebContent/resources/images/profile/" + fileName);
if(!newFile.exists())
{
model.addAttribute("exc", "File Does not exist");
}
model.addAttribute("exc", newFile.getName());
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while((read = inputStream.read(bytes)) != -1)
outputStream.write(bytes, 0, read);
}
catch(Exception e){
//model.addAttribute("exc", e.getMessage() + "df");
}
List<Object[]> userDetails = this.userFunctionsService.getUserDetails(((UserLoginDetails)session.getAttribute("session_user")).getEmailID());
model.addAttribute("userDetails", userDetails);
return new ModelAndView("editProfile", model);
}
else
return new ModelAndView("redirect:/");
}
welcome-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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.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.1.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc">
<context:annotation-config />
<context:component-scan base-package="com.pir" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTransactionManager" />
<bean id="myTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/pir"
p:username="root"
p:password="user" />
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
editProfile.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
${exc }
<table>
<c:forEach items="${userDetails}" var="element">
<tr>
<td valign="top">
<a href="${pageContext.request.contextPath }/changeimage">
<img src="${pageContext.request.contextPath }/resources/images/profile/${element[5] }" height="145" width="200" />
</a>
</td>
<td>
<form:form action="${pageContext.request.contextPath}/editprofilehandler" method="POST" modelAttribute="userForm" enctype="multipart/form-data">
<table>
<tr>
<td>
First Name :
</td>
<td>
<form:input path="firstName" value="${element[2] }" /> <form:errors path="firstName" class="error" />
</td>
</tr>
<tr>
<td>
Last Name :
</td>
<td>
<form:input path="lastName" value="${element[3] }" /> <form:errors path="lastName" class="error" />
</td>
</tr>
<tr>
<td>
EmailID Name :
</td>
<td>
<form:input path="emailID" value="${element[1] }" /> <form:errors path="emailID" class="error" />
</td>
</tr>
<tr>
<td>
Mobile No :
</td>
<td>
<form:input path="mobileNo" value="${element[4] }" /> <form:errors path="mobileNo" class="error" />
</td>
</tr>
<tr>
<td>
Date of birth :
</td>
<td>
<form:input path="dateOfBirth" value="${element[6]}" /> <form:errors path="dateOfBirth" class="error" />
</td>
</tr>
<tr>
<td>
Gender :
</td>
<td>
<form:input path="gender" value="${element[7]}" /> <form:errors path="gender" class="error" />
</td>
</tr>
<tr>
<td>
Profile image :
</td>
<td>
<input type="file" name="uploadImage" />
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="Update" />
</td>
</tr>
</table>
</form:form>
</td>
</tr>
</c:forEach>
</table>
Error:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Why this error is coming while uploading the image?
I am getting this error when I add
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576" />
</bean>
to the servlet.xml file. I am using Spring 4.

You need to have separate parameter in editProfileHandlerController method like #RequestParam("file") MultipartFile file.
Issue is Spring internally adds parameter resolver based on parameter type.
In your case your wrapping MultipartFile field in your custom type Users that's why it is not working.
Modify your method like below will work:
#RequestMapping(value = "/editprofilehandler", method=RequestMethod.POST)
public ModelAndView editProfileHandlerController(#ModelAttribute("userForm") Users users
,#RequestParam("uploadImage") MultipartFile file, ModelMap model, HttpSession session)

change your multipart class name.like
org.springframework.web.multipart.commons.CommonsMultipartResolver.CommonsMultipartResolver

Related

Internationalize in spring mvc/java. Translating only first line of messages.property

I got next problem with my application. I want to internationalize my pages. On first page I have problem, because app translate only first variable. Firstly i added messages_en.properties in src/main/resources.
addGame.form.gameId.label = Game ID
addGame.form.gameName.label = Game name
addGame.form.gamePlatform.label = Game platform
addGame.form.gamePrice.label = Game price
addGame.form.gameDescription.label = Game description
addGame.form.gameCategory.label = Game category
addGame.form.gamesInStock.label = Games in stock
addGame.form.condition.label = Game condition
addGame.form.gameImage.label = Game image
Next step was add choice of language in addGame.jsp. It's work good.
<div class="pull-right" style="padding-right:50px">
angielski
</div>
Next step in DispatcherServlet-context.xml added one bean.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
And in same file
<mvc:interceptors>
<bean class= "org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language"/>
</bean>
</mvc:interceptors>
And last what i do was added language to GameController like this.
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setDisallowedFields("unitsInOrder", "discontinued");
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "language");
}
Screen from page
On screenshot you can see my page after click English language. its changing only first variable. Could you tell me why?
Mine code. You can see messages_en.properties up. This is DispatcherServlet-context.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: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">
<mvc:annotation-driven enable-matrix-variables="true"
validator="validator" />
<context:annotation-config />
<mvc:resources mapping="/resource/**" location="/resources/" />
<context:component-scan base-package="com.kk.gamestore" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json;charset=UTF-8" />
<entry key="xml" value="application/xml;charset=UTF-8" />
<entry key="html" value="text/html;charset=UTF-8" />
</map>
</property>
<property name="defaultViews">
<list>
<ref bean="jsonView" />
<ref bean="xmlView" />
</list>
</property>
</bean>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prettyPrint" value="true" />
</bean>
<bean id="xmlView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.kk.gamestore.domain.Game</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl" />
</bean>
<mvc:interceptors>
<bean class="com.kk.gamestore.interceptor.PerformanceMonitorInterceptor" />
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property value="language" name="paramName"/>
</bean>
<bean class="com.kk.gamestore.interceptor.AuditingInterceptor" />
<bean class="com.kk.gamestore.interceptor.PromoCodeInterceptor">
<property name="promoCode" value="PROMOGRY" />
<property name="errorRedirect" value="invalidPromoCode" />
<property name="offerRedirect" value="games" />
</bean>
</mvc:interceptors>
</beans>
There is GameController. I added position language in method - setAllowedFields
package com.kk.gamestore.controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.kk.gamestore.domain.Game;
import com.kk.gamestore.exception.GameNotFoundException;
import com.kk.gamestore.service.GameService;
#RequestMapping("/games")
#Controller
public class GameController {
#Autowired
private GameService gameService;
#RequestMapping
public String Welcome(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/all")
public String allGames(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/{platform}")
public String getGamesByPlatform(Model model, #PathVariable("platform") String gamePlatform) {
model.addAttribute("games", gameService.getGamesByPlatform(gamePlatform));
return "games";
}
#RequestMapping("/filter/{ByCriteria}")
public String getGamesByFilter(#MatrixVariable(pathVar="ByCriteria")
Map<String,List<String>> filterParams, Model model){
model.addAttribute("games", gameService.getGamesByFilter(filterParams));
return "games";
}
#RequestMapping("/game")
public String getGamesById(#RequestParam("id") String gameId, Model model){
Game game = gameService.getGameById(gameId);
model.addAttribute("game", game);
return "game";
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddNewGameForm(Model model) {
Game newGame = new Game();
model.addAttribute("newGame", newGame);
return "addGame";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String processAddNewGameForm(#ModelAttribute("newGame") #Valid Game gameToBeAdded, BindingResult result, HttpServletRequest request) {
if(result.hasErrors()) {
return "addGame";
}
String[] suppressedFields = result.getSuppressedFields();
if (suppressedFields.length > 0) {
throw new RuntimeException("Próba wiązania niedozwolonych pól: " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
MultipartFile gameImage = gameToBeAdded.getGameImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if (gameImage!=null && !gameImage.isEmpty()) {
try {
gameImage.transferTo(new File(rootDirectory+"resources\\images\\"+gameToBeAdded.getGameId() + ".png"));
} catch (Exception e) {
throw new RuntimeException("Blad podczas zapisu okladki gry.", e);
}
}
gameService.addGame(gameToBeAdded);
return "redirect:/games";
}
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "condition" , "language");
}
#ExceptionHandler(GameNotFoundException.class)
public ModelAndView handleError(HttpServletRequest req, GameNotFoundException exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("invalidGameId", exception.getGameId());
mav.addObject("exception", exception);
mav.addObject("url", req.getRequestURL()+"?"+req.getQueryString());
mav.setViewName("gameNotFound");
return mav;
}
#RequestMapping("/invalidPromoCode")
public String invalidPromoCode() {
return "invalidPromoCode";
}
}
And AddGame.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>Gry</title>
</head>
<body>
<section>
<div class="jumbotron">
<div class="container">
<h1>Gry</h1>
<p>Dodaj gry</p>
</div>
wyloguj
<div class="pull-right" style="padding-right:50px">
<a href="?language=pl" >polski</a>|<a href="?language=en" >angielski</a>
</div>
</div>
</section>
<section class="container">
<form:form modelAttribute="newGame" class="form-horizontal" enctype="multipart/form-data">
<form:errors path="*" cssClass="alert alert-danger" element="div"/>
<fieldset>
<legend>Dodaj nową grę</legend>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameId">
<spring:message code="addGame.form.gameId.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameId" path="gameId" type="text" class="form:input-large" />
<form:errors path="gameId" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameName">Nazwa</label>
<div class="col-lg-10">
<form:input id="gameName" path="gameName" type="text" class="form:input-large" />
<form:errors path="gameName" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamePrice">Cena</label>
<div class="col-lg-10">
<form:input id="gamePrice" path="gamePrice" type="text" class="form:input-large" />
<form:errors path="gamePrice" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gamePlatform">Platforma Gry</label>
<div class="col-lg-10">
<form:radiobutton path="gamePlatform" value="PS4" />
Playstation 4
<form:radiobutton path="gamePlatform" value="XBOX ONE" />
Xbox One
<form:radiobutton path="gamePlatform" value="PS3" />
Playstation 3
<form:radiobutton path="gamePlatform" value="XBOX 360" />
Xbox 360
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameCategory">Kategoria</label>
<div class="col-lg-10">
<form:input id="gameCategory" path="gameCategory" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamesInStock">Liczba gier w magazynie</label>
<div class="col-lg-10">
<form:input id="gamesInStock" path="gamesInStock" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameDescription">Opis</label>
<div class="col-lg-10">
<form:textarea id="gameDescription" path="gameDescription" rows="2"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="condition">Stan</label>
<div class="col-lg-10">
<form:radiobutton path="condition" value="New" />
Nowy
<form:radiobutton path="condition" value="Old" />
Używany
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameImage">
<spring:message code="addProdcut.form.gameImage.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameImage" path="gameImage" type="file" class="form:input-large" />
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" id="btnAdd" class="btn btn-primary" value="Dodaj" />
</div>
</div>
</fieldset>
</form:form>
</section>
</body>
</html>
I haven't idea what i doing wrong. Button of changing language working well, but it's translate only first variable no more. On screen you can see en version (not default) and it changed only first variable and next variable name its from default lang. I haven't problems in console when running application just one warning like this.
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:gamestoreCOPIED' did not find a matching property.
#EDIT:
Hi, after few days coding and repairing errors im back there. I got new informations.
PROBLEM : Application working good.
Locale change button working good. After click on this button application generate link (if english button click: http://localhost:8080/gamestore/games/add?language=en or if polish: add?language=pl)
and language are changing.
When i want change it on english language it translate me only first word of messages_en.properties. When i make english language default - its same situation - only first word its changing.
In console 0 errors only one warning but its nothing in this topic.
Problem is when i try change language on english or use on default english its change only first line of messages_en.properties.
If i change ResourceBundleMessageSource for ReloadableResourceBundleMessageSource(with changing classpath and make it good)
nothing changed.
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
I need this line.
<mvc:annotation-driven enable-matrix-variables="true"
So i can't make mine app with HandlerMapping. But if i do it its not working.
I read a lot of informations and trying find answer in network but nothing work. Anyone got similiar problems in past?

session.update not updating in db

I have a jsp page i which i am sending a model attribute from controller and after that making some changes in the properties of model attribute. it is reflecting the model attribute but not updating in database. My code is -
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.vc.teacher" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Configuration defining views files -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.vc.teacher.entities.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/teacher"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
AccountContoller class
package com.vc.teacher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
#Controller
public class AccountController {
#Autowired
UserDao userDao;
#RequestMapping("/login")
public String loginUser(#RequestParam("email") String email,
#RequestParam("password") String password, Model model) {
User user = userDao.checkCreditionals(
email, password);
if (user != null) {
model.addAttribute("user", user);
System.out.println("id=============================="+user.getId());
return "jsp/profile";
} else {
model.addAttribute("error", "Wrong creditionals");
return "jsp/signin";
}
}
#RequestMapping("/signUp")
public String initilize(Model model) {
model.addAttribute(new User());
return "jsp/signup";
}
#RequestMapping(method = RequestMethod.POST, value = "/register")
public String signUpUser(User user, RedirectAttributes attributes) {
boolean result = false;
user.setStatus("Deactive");
result = userDao.registerUser(user);
if (result == true) {
attributes.addFlashAttribute("message", "You are ready to go now !");
return "redirect:/signUp";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
}
#RequestMapping(method = RequestMethod.POST, value = "/update")
public String updateUser(User user, RedirectAttributes attributes) {
boolean result = false;
System.out.println("====================================================="+user.getFirstName());
System.out.println("============================================="+user.getEmail());
System.out.println("============================================"+user.getId());
user.setStatus("Active");
result = userDao.updateUser(user);
if (result == true) {
attributes.addFlashAttribute("message", "Profile Updated !");
return "jsp/profile";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "jsp/profile";
}
}
}
profile.jsp
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="firstName" type="text" class="form-control" id="firstName" placeholder="Your first name" value="${user.firstName}" />
<label for="firstName">First name</label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="lastName" class="form-control" id="lastName" placeholder="Your last name" value="${user.lastName}" />
<label for="lastName">Last name</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="email" type="email" class="form-control" id="inputEmail3" placeholder="Email" value="${user.email}" />
<label for="inputEmail3">Email address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Phone</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="phone" type="number" class="form-control" id="inputEmail3" placeholder="Phone" value="${user.phone}" />
<label for="phone">Phone</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Address</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-link"></i></span>
<sf:input path="address" type="text" class="form-control used" id="website" placeholder="Address" value="${user.address}" />
<label for="address">Address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-md-2 control-label">Change Password</label>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="password" type="password" class="form-control" id="inputPassword3" placeholder="Password" value="${user.password}" />
<label for="password">Password</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</sf:form>
UserDao class
package com.vc.teacher.db.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.vc.teacher.entities.User;
#Component
public class UserDao {
#Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
public User checkCreditionals(String email, String password){
User user = null;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where email = '"+email+"' and password = '"+password+"'");
List list = query.list();
if(list.size()>0)
user = (User)list.get(0);
return user;
}
#Transactional
public boolean registerUser(User user){
boolean result = false;
Session session = sessionFactory.getCurrentSession();
try{
user.setUserTypeId(2);
session.save(user);
result = true;
} catch (Exception e){
result = false;
e.printStackTrace();
}
return result;
}
#Transactional
public boolean updateUser(User user){
boolean result = false;
Session session = sessionFactory.getCurrentSession();
try{
user.setUserTypeId(2);
session.update(user);
result = true;
} catch (Exception e){
result = false;
e.printStackTrace();
}
return result;
}
}
Here I am login using login method in AccountController class and adding a model attribute user and making changes in this object in the profile jsp page and after submitting the form its showing changes in the jsp page but not updating the changes in the database. Sometimes this exception also come -
org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:205)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:730)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:592)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.vc.teacher.db.dao.UserDao$$EnhancerBySpringCGLIB$$467fa027.updateUser(<generated>)
at com.vc.teacher.controller.AccountController.updateUser(AccountController.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeFor
What is the problem ?
You should first load the user then update user properties.
Your code will like this:
#Transactional
public boolean updateUser(User user){
boolean result = false;
Session session = sessionFactory.getCurrentSession();
try{
User useToUpdate = session.get(user.getId());
useToUpdate.setUsername(user.getUsername());
...
result = true;
} catch (Exception e){
result = false;
e.printStackTrace();
}
return result;
}
Hibernate will persist the changes when commiting the transaction, so you don't need to call session.update(user);
I checked my code and i find that my user object was taking id as 0 thats why exception came on updating. I set id on jsp page in the form and that issued my problem.

Spring model object becomes null on jsp

I have a spring project and my problem is that my model objects becomes null on jsp when I debug it in the controller it shows data but on jsp nothing is displayed and there are no errors in the log.
I have added spring tiles config recently and tiles are working fine but these objects stopped getting displayed earlier it was working fine.
I have searched a lot on this and checked same links like Spring Model Object is not rendering on stackoverflow but nothing worked.
Here is my controller:
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelAndView model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model = new ModelAndView("systemUsers");
model.addObject("systemUsers", systemUsers);
return "viewClient";
}
spring-config.xml
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order">
<value>0</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
tiles.xml
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/pages/Theme/Template/mainTemplate.jsp">
<put-attribute name="title" value=""></put-attribute>
<put-attribute name="header" value="/WEB-INF/pages/Theme/Template/header.jsp"></put-attribute>
<put-attribute name="menu" value="/WEB-INF/pages/Theme/Template/menu.jsp"></put-attribute>
<put-attribute name="body" value=""></put-attribute>
<!-- <put-attribute name="footer" value="/WEB-INF/pages/Theme/Template/footer.jsp"></put-attribute> -->
</definition>
<definition name="base.definition.login" template="/WEB-INF/pages/Theme/Template/loginTemplate.jsp">
<put-attribute name="title" value=""></put-attribute>
<put-attribute name="body" value=""></put-attribute>
</definition>
<definition extends="base.definition" name="viewClient">
<put-attribute name="title" value="View Client"></put-attribute>
<put-attribute name="body" value="/WEB-INF/pages/Theme/Admin/viewClient.jsp"></put-attribute>
</definition>
<tiles-definitions>
viewClient.jsp:
<table class="table table-striped table-advance table-hover">
<h4>
<!-- <i class="fa fa-angle-right"></i> --> Client Details
</h4>
<thead>
<tr>
<th><i class="fa fa-bullhorn"></i> index --${systemUsers.size()}--size </th>
<th><i class="fa fa-bullhorn"></i> Username</th>
<th><i class="fa fa-bullhorn"></i> Password</th>
<th><i class="fa fa-bullhorn"></i> User role</th>
<th><i class="fa fa-bullhorn"></i> Mobile No</th>
<th><i class="fa fa-bullhorn"></i> Email ID</th>
<th><i class="fa fa-bullhorn"></i> SMSC</th>
<th><i class="fa fa-bullhorn"></i> Virtual Sim ID</th>
<th></th>
</tr>
</thead>
<tbody>
<c:set var="count" value="0" scope="page" />
<c:forEach var="user" items="${systemUsers}">
<tr>
<td>${count + 1}</td>
<td>${ user.getUsername()}</td>
<td>${ user.getPassword()}</td>
<td>${user.getUserrole()}</td>
<td>${user.getMobileNumber()}</td>
<td>${user.getPrimaryEmailAddress()}</td>
<td>${user.getSmsc()}</td>
<td>${user.getVirtualSimID()}</td>
<td>
<button class="btn btn-success btn-xs">
<i class="fa fa-check"></i>
</button>
<button class="btn btn-primary btn-xs">
<i class="fa fa-pencil"></i>
</button>
<button class="btn btn-danger btn-xs">
<i class="fa fa-trash-o "></i>
</button>
</td>
</tr>
<c:set var="count" value="${count + 1}" scope="page" />
</c:forEach>
</tbody>
</table>
In the jsp the systemUsers are not getting iterated nor displayed not its size is getting displayed..
Make it correct and change return type to ModelAndView
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public ModelAndView viewClient() {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
ModelAndView model = new ModelAndView("viewClient");
model.addObject("systemUsers", systemUsers);
return model ;
}
OR use
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelMap model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addAttribute("systemUsers", systemUsers);
return "viewClient";
}
Look at ModelAndView that accepts view name.
You can also try this interface Model for this issue:
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(Model model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addAttribute("systemUsers", systemUsers);
return "viewClient";
}
Make sure that in your pom.xml the following dependency exist:
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
Do not reinitialize ModelAndView Object
#RequestMapping(value = "/viewClient", method = RequestMethod.GET)
public String viewClient(ModelAndView model) {
ArrayList<SystemUser> systemUsers = clientController.getAllUsers();
model.addObject("systemUsers", systemUsers);
return "viewClient";
}

Neither BindingResult nor plain target object ... Exception

Yes, I read it is pretty common problem, but reading those post did not really help me.
The short story is that I wanna submit a form on showAllComments.jsp
<form:form method="post" action="postNewComment.html">
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>
Here is the controller:
#Controller
#SessionAttributes
public class CommentController {
#Autowired
private CommentService commentService;
#RequestMapping(value = "/postNewComment", method = RequestMethod.POST)
public ModelAndView showAllUsers(#ModelAttribute("command") Comment comment, BindingResult result) {
System.out.println(comment.getComment());
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", commentService.getComments());
return new ModelAndView("showAllComments", model);
}
}
and here is the result:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
But probably you need to see the whole story, from the beginning:
The user starts the application on index.jsp by clicking
Log in
That link takes him to LoginController
#RequestMapping("/toLoginPage")
public ModelAndView goToLoginPage() {
return new ModelAndView("login", "command", new User());
}
Then he is taken to login.jsp where he provides his username and password.
<form:form method="post" action="log_in.html">
<input type="text" name="uName" />
<input type="password" name="pW" />
<input type="submit" value="Log IN">
</form:form>
he submits the form and he is taken back to LoginController
#RequestMapping(value = "/log_in", method = RequestMethod.POST)
public ModelAndView tryToLogin(#RequestParam("uName") String uName, #RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) {
ModelAndView ret = new ModelAndView("login", "command", new User());
User user = userService.existingUser(uName, pW);
loggedInUser = new User();
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", allComments);
model.put("LOGGED_IN_USER", loggedInUser);
ret = ModelAndView("showAllComments", model);
}
return ret;
}
After successful login he is on the showAllComments page where he sees all the comments and he should be able to add his own comment but submitting the above mentioned form throws the above mentioned exception. I feel something is missing but I can't figure out what it is. Just for the record I show the 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<display-name>Spring3MVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
and the spring-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="net" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>net.model.User</value>
<value>net.model.Comment</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
</beans>
You need to add a your form bean class ie Comment, as an attribute to your model when you show the showAllComments.jsp in the logincontroller.
#RequestMapping(value = "/log_in", method = RequestMethod.POST)
public ModelAndView tryToLogin(#RequestParam("uName") String uName, #RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) {
ModelAndView ret = new ModelAndView("login", "command", new User());
User user = userService.existingUser(uName, pW);
loggedInUser = new User();
model.addAttribute("command", new Comment());
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", allComments);
model.put("LOGGED_IN_USER", loggedInUser);
ret = ModelAndView("showAllComments", model);
}
return ret;
}
This should work fine.
UPDATE
And it is not a good practise to use 'command' as the command object name. For the class comment you can use a 'comment' or something like that.
If your doing that, Update your form with the following code.
<form:form method="post" action="postNewComment.html" commandName="comment">
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>
Do the same change at all other places, viz
model.addAttribute("comment", new Comment());
and
#ModelAttribute("comment")
UPDATE 2
#RequestMapping(value="userRegistration", method = RequestMethod.GET)
public ModelAndView showUserRegistrationForm(Model model){
model.addAttribute("user", new AccountDetailsForm());
return new ModelAndView("userRegistration");
}

Spring MVC - passing variables from one page to anther

I need help. I am working on a project where I have multiple pages and multiple forms; each page has one form. I just need to be able to pass values from one jsp to another. What should I do?
I am new to Spring MVC. I am using spring 2.5.6.
Here's my design:
formPage1.jsp --> Controller1 --> formPage2a.jsp --> Controller2 needs val frm pg1 & pg2a.
formPage1.jsp --> Controller1 --> formPage2b.jsp --> Controller3 needs val frm pg1 & pg2b.
formPage1.jsp --> Controller1 --> formPage2c.jsp --> Controller4 needs val frm pg1 & pg2c.
As you can see above, formPage1.jsp can load either formPage2a, formPage2b or formPage2c. Based on the input provided in formPage1.jsp, it goes to the controller (which is an extension of SimpleFormController) and controller get the values entered by user = command object.
I want to be able to use these command object values in either formPage2a, formPage2b or formPage2c when they are submitted to another controller.
here's the current code:
formPage1.jsp:
<form:form method="post" commandName="gainLossRequest">
<form:errors path="*" cssClass="error"/>
<table>
<tr>
<td>
<table>
<tr>
<td><h4>Choose Client</h4></td>
<td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
</tr>
</table>
</td>
<td>
<form:select path="client">
<form:option value="none" label="Select" />
<form:option value="abc" label="abc" />
<form:option value="def" label="def" />
<form:option value="xyz" label="xyz" />
</form:select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</td>
</tr>
</table>
</form:form>
Controller1.java
public class TestController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public TestController() {
logger.info("entering TestController.constructor..");
setCommandClass(UserPreference.class);
setCommandName("userPreference");
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws ServletException {
logger.info("entering TestController.onSubmit all..");
UserPreference userPreference = (UserPreference) command;
ModelAndView view = null;
if ("abc".equals(userPreference.getClient())) {
GainLossRequest gainLossRequest = new GainLossRequest(userPreference);
view = new ModelAndView("redirect:/test/gainLossRequest.htm",
"gainLossRequest", gainLossRequest);
} else if ("def".equals(userPreference.getClient())) {
IncomingPositionsRequest incomingPositionsRequest = new IncomingPositionsRequest();
view = new ModelAndView(
"redirect:/test/incomingPositionsRequest.htm",
"incomingPositionsRequest", incomingPositionsRequest);
} else if ("xyz".equals(userPreference
.getClient())) {
TaxStrategyRequest taxStrategyRequest = new TaxStrategyRequest();
view = new ModelAndView("redirect:/test/taxStrategyRequest.htm",
"taxStrategyRequest", taxStrategyRequest);
}
}
}
formPage2a.jsp
<form:form method="post" commandName="gainLossRequest">
<form:errors path="*" cssClass="error"/>
<table style="width: 60%">
<tr>
<td>Account Number (s):</td>
<td style="font-size: medium; font-family: Arial, bold; color: red">*</td>
</tr>
<tr>
<td>
User Chosen Client:
</td>
<td>
<c:out value="${gainLossRequest.client}"/>
</td>
</tr>
<tr colspan="2">
<td>
<input type="reset" value="Reset" />
<input type="submit" value="Submit" />
</td>
</tr>
dispatcher servlet config
<!-- setupNew.jsp is the first jsp -->
<bean name="/test/setupNew.htm" class="chimeraweb.web.TestController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="userPreference"/>
<property name="commandClass" value="chimeraweb.service.UserPreference"/>
<property name="validator">
<bean class="chimeraweb.service.UserPreferenceValidator"/>
</property>
<property name="formView" value="/test/setupNew"/>
</bean>
<!-- gainLossRequest.jsp is the 2nd jsp where I want to display the values captured in the first jsp page -->
<bean name="/test/gainLossRequest.htm" class="chimeraweb.web.SimpleGainLossController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="gainLossRequest"/>
<property name="commandClass" value="chimeraweb.service.GainLossRequest"/>
<property name="validator">
<bean class="chimeraweb.service.GainLossValidator"/>
</property>
<property name="formView" value="/test/gainLossRequest"/>
</bean>
Please help!!
You could also use session attributes, either manually, such as:
public ModelAndView handleRequest(HttpServletRequest request){
request.getSession().getAttribute("nameOfAttribute");
}
Apologies for writing this as an annotated controller, I do not recall if xml config controllers offer this feature...
There is no Spring code involved for that. The other option is to use the #SessionAttribute annotation on your controller:
#Controller
#SessionAttributes("nameOfAttribute")
public class MyController{
//your session attribute can be accessed in controller methods using #ModelAttribute
public ModelAndView handleRequest(#ModelAttribute("nameOfAttribute")){
session.getAttribute("nameOfAttribute");
}
Note
You will need to clear the session attribute when you are done with it:
request.getSession().setAttribute("nameOfAttribute", null);
You have to persist the user entered information on the first page either using a hidden variable as mentioned above by JB Nizet. Or you can set the value in the model attribute that will be returned on your corresponding controllers.
The pseudo code for you.
formPage1.jsp --> Controller1 --> set the values in this form by retrieving it from the Request object --> formPage2a.jsp --> Controller2 will have val frm both pg1 & pg2a.
In this way there is no need to maintain a session attribute.
The simplest way is to use hidden fields in the second page(s) to store what the user has enetered in the first form. This way, all the fields, inclusing those from the first page, will be submitted with the second form(s).

Categories