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.
Related
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?
I work with a Spring Mvc app and get HTTP Status [404] – [Not Found]. The landing page is namely index.jsp,
and called from the controller method,
#Controller
public class BitcoinWalletController {
#RequestMapping("/")
public String showBitcoinWallet() {
return "index";
}
}
In the index.jsp page, send money button is initially disabled,
<div class="buttons_box">
<button type="button" class="btn btn-default btn-lg active" <%= canSendMoney ? "" : "disabled='true'"%>
data-toggle="modal" data-target="#myModal">Send money
</button>
</div>
and only be active if the synchronization is completed and boolean canSendMoney returns true.
If the button is active, the code handles the POST operation is provided,
<%--modal contents here--%>
<div class="modal-content">
<div class="model-header">
<button type="button" class="close" data-dismiss="modal">×!</button>
<h4 class="modal-title">Send Money</h4>
</div>
<form id="send-form" class="form-horizontal" action="sendMoney.jsp" method="POST">
<div class="modal-body">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<input id="amount" name="amount" class="form-control" value="0">
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<input id="address" name="address" class="form-control">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
</div>
The sendMoney.jsp code is provided below,
<body>
<%
String amount = request.getParameter("amount").trim();
String address = request.getParameter("address").trim();
WalletSendMoneyController.getSendMoneyController().send(address, amount);
// New location to be redirected
String site = new String("/");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
When I put all the required and correct infos and press the button, It should return to the original page- index.jsp. Instead, I get the error, HTTP Status [404] – [Not Found],
I currently don't have any handle for the address http://localhost:8080/sendMoney.jsp. Because, if the POST submission is correct, I would like to redirect to the "/".
I have the jsps in the WEB-INF folder in the project directory,
The jsps location provided in the dispatcher-servlet.xml file,
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
The we.xml knows where the dispatcher-servlet.xml is located,
<servlet>
<description></description>
<display-name>dispatcher</display-name>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
How to solve the issue? Thanks.
Your code showing: You are actually trying to submit form to sendMoney.jsp which is not exist(might be, cause i can't see your whole project). Though you need to submit the form to a controller with a ModelAttribute which you need to create.
The following things you have to do for POST to controller from form.
Make a class for form fields
public class Data {
private String address;
private String amount;
public Data() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Bind a new Data object in GET controller where you load the form in HTML
#RequestMapping("/")
public String showBitcoinWallet() {
model.addAttribute("data", new Data());
return "index";
}
The following form will be in your index.jsp page, Where /send is the controller's mapping where to POST the form
<form:form id="send-form" modelAttribute="data" class="form-horizontal" action="/send" method="POST">
<div class="modal-body">
<spring:bind path="amount">
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Send</label>
<div class="col-xs-4">
<form:input path="amount" id="amount" name="amount" class="form-control" value="0"></form:input>
</div>
<div class="btc-col">
<span>BTC</span>
</div>
</div>
</spring:bind>
<spring:bind path="address">
<div class="form-group">
<label for="address" class="col-sm-2 control-label">to</label>
<div class="col-sm-10">
<form:input path="address" id="address" name="address" class="form-control"></form:input>
</div>
</div>
</spring:bind>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">Send</button>
</div>
</form:form>
Following controller for /send POST
#RequestMapping(value = "/send", method = RequestMethod.POST)
public String sendMoney(Data data) {
//here will be your code for send money and whatever you have to do..
...send(data.getAddress(), data.getAmount());
return "redirect:/"; //here will the location where you want to redirect
}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Have you defined this in your spring-config.xml file ??
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
I am working on a Spring-MVC application in which I am using Spring-security for authentication and authorization. I am connecting to the webapp via Android using RestTemplate.
Currently, the problem I am having is that even if Login fails, i am receiving 302 instead of 200. Because of that, on the client-side I don't know that login has failed. After which when the user tries to access secured-resource, access is denied and the app dies.
Can anyone tell me how to return correct response-code when there is a Login failure and how to detect it via Response code. Thanks a lot.
securityApplicationContext.xml :
<security:http pattern="/resources/template/demo/clients" security="none"/>
<security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
<security:form-login login-page="/login" username-parameter="j_username" password-parameter="j_password"
login-processing-url="/j_spring_security_check" default-target-url="/dashboard"
always-use-default-target="true" authentication-failure-url="/denied"/>
<security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService"
token-validity-seconds="1209600" data-source-ref="dataSource"/>
<security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<!--<security:intercept-url pattern="/**" requires-channel="https"/>-->
<security:port-mappings>
<security:port-mapping http="80" https="443"/>
</security:port-mappings>
<security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>
<security:session-management session-fixation-protection="migrateSession">
<security:concurrency-control session-registry-ref="sessionReg" max-sessions="5" expired-url="/sessionexpired"/>
</security:session-management>
</security:http>
<beans:bean id="sessionReg" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<beans:bean id="rememberMeAuthenticationProvider"
class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:constructor-arg index="0" value="_spring_security_remember_me"/>
<beans:constructor-arg index="1" ref="userDetailsService"/>
<beans:constructor-arg index="2" ref="jdbcTokenRepository"/>
<property name="alwaysRemember" value="true"/>
</beans:bean>
<beans:bean id="jdbcTokenRepository"
class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="createTableOnStartup" value="false"/>
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<!-- Remember me ends here -->
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="LoginServiceImpl">
<security:password-encoder ref="encoder"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="LoginServiceImpl"/>
<beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>
</beans>
On Android side, here is how I am doing authentication :
private class LoginUserViaRest extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
final EditText userEmail = (EditText) findViewById(R.id.usernameText);
final EditText userPassword = (EditText) findViewById(R.id.PasswordField);
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
StaticRestTemplate.jsessionid = rest.execute(StaticRestTemplate.baseURL+"j_spring_security_check", HttpMethod.POST,
new RequestCallback() {
#Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
request.getBody().write(("j_username=" + userEmail.getText().toString() + "&j_password=" + userPassword.getText().toString()).getBytes());
}
}, new ResponseExtractor<String>() {
#Override
public String extractData(ClientHttpResponse response) throws IOException {
// Here I can get the code to determine if login was successful
List<String> cookies = response.getHeaders().get("Cookie");
if (cookies == null) {
cookies = response.getHeaders().get("Set-Cookie");
}
String cookie = cookies.get(cookies.size() - 1);
int start = cookie.indexOf('=');
int end = cookie.indexOf(';');
return cookie.substring(start + 1, end);
}
});
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
If there is any further explanation necessary, kindly let me know. Thanks a lot. :-)
Update
Login.jsp :
<div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-4 col-lg-offset-4">
<div class="container-fluid white-div">
<div class="col-xs-12 col-md-12">
<h2><spring:message code="login.title"/></h2>
<form id="login-form" class="login-page" action="<c:url value='/j_spring_security_check'/>" method="POST">
<div class="form-group">
<label><spring:message code="login.label.email"/> <span id="eMailError" class="red-font"></span></label>
<div class="wrapper">
<input type="email" name="j_username" id="j_username" value="" class="form-control input" placeholder="<spring:message code="common.input.email.placeholder"/>">
<i class="fa fa-user"></i>
</div>
</div>
<div class="form-group">
<label><spring:message code="login.label.password"/> <span id="passwordError" class="red-font"></span></label>
<div class="wrapper">
<input type="password" name="j_password" id="j_password" class="form-control input" placeholder="<spring:message code="login.password.placeholder"/>">
<i class="fa fa-lock"></i>
</div>
</div>
<div class="checkbox">
<div class="col-xs-5">
<div class="row">
<label class="pull-left" for="show-password">
<input type="checkbox" id="show-password"><spring:message code="common.label.showpassword"/>
</label>
</div>
</div>
<spring:message code="login.forgotpassword"/>
</div>
<br>
<div class="form-group">
<button class="btn btn-primary btn-lg pull-right"><spring:message code="login.submit"/></button>
</div>
<div class="form-group">
<span><spring:message code="login.registration.text"/> <spring:message code="login.registration.link"/></span>
</div>
</form>
</div>
</div>
<!-- <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> -->
<c:if test="${not empty url}">
<%-- <spring:message code="common.facebook"/> --%>
</c:if>
</div>
</div>
security:form-login is designed for web apps rather than REST clients. Although you can use it, you'll run into the kind of trouble you've described here.
I recommend using security:http-basic instead (secured over HTTPS) and sending the login details each time.
Edit: If you insist on using form login, you'll need to tell the RestTemplate not to follow redirects, which you can do with the following (using Apache HttpComponents instead of the standard JRE HttpUrlConnection):
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(
new DefaultRedirectStrategy() {
#Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
}
).build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
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";
}