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

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?

Related

Spring Controller doesn't load the correct view

I am working on spring. I have the controller AdminProduitsController (code below) that doesn't load the correct view. It should load a page called produits.jsp.Instead of that, it loads the page categories.jsp of an other controller called AdminCategorieController. The two controllers belongs to the same package.
The pages produits.jsp and categories.jsp are in the same directory.
AdminProduitsController
#Controller
#RequestMapping(value="/adminProd")
public class AdminProduitsController {
#Autowired
private IAdminProduitsMetier metier;
#RequestMapping(value="/index")
public String home(Model model)
{
model.addAttribute("produits",metier.listProduits());
model.addAttribute("categories",metier.listCategories());
model.addAttribute("produit", new Produit());
return "produits";
}
}
AdminCategorieController
#Controller
#RequestMapping(value = "/adminCat")
public class AdminCategorieController implements HandlerExceptionResolver{
#Autowired
IAdminCategoriesMetier metier;
#RequestMapping(value="/index")
public String home(Model model)
{
model.addAttribute("categorie",new Categorie());
model.addAttribute("categories",metier.listCategories());
return "categories";
}
}
Here is the configuration file servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="org.aaronlbk.eboutique" />
<beans:bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="100000"></beans:property>
</beans:bean>
</beans:beans>
The jsp files are strictly differents.
categories.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<head>
<!-- .getContextPath() contexte du projet -->
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/css/style1.css">
<link href="<c:url value="/resources/css/style1.css" />" rel="stylesheet">
</head>
<body>
<div id="formCat" class="cadre">
<f:form modelAttribute="categorie" action="saveCat" method="post"
enctype="multipart/form-data">
<table class="tab1">
<tr>
<td>ID categorie</td>
<td><f:input path="idCategorie" />
<td><f:errors path="idCategorie" cssclass="errors"></f:errors></td>
</tr>
<tr>
<td>Nom categorie</td>
<td><f:input path="nomCategorie" />
<td><f:errors path="nomCategorie" cssclass="errors"></f:errors></td>
</tr>
</table>
</f:form>
</div>
</body>
produits.jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<head>
<link href="<c:url value="/resources/css/style1.css" />" rel="stylesheet">
</head>
<body>
<div id="formProd" class="cadre">
<f:form modelAttribute="produit" action="saveProd" method="post"
enctype="multipart/form-data">
<table class="tab1">
<tr>
<td>ID Produit</td>
<td><f:input path="idProduit" />
<td><f:errors path="idProduit" cssclass="errors"></f:errors></td>
</tr>
<tr>
<td>Catégorie</td>
<td><f:select path="categorie.idCategorie" items="${categories}" itemValue="idCategorie" itemLabel="nomCategorie"/>
<td><f:errors path="designation" cssclass="errors"></f:errors></td>
</tr>
</table>
</f:form>
</div>
</body>
Why can cause the controller AdminProduitsController to return the page of an other controller ?
Can you please share the URL you are hitting to call the controller ?
May be you can try ModelAndView("viewname")
#RequestMapping(value="/index")
public ModelAndView home(Model model)
{
model.addAttribute("produits",metier.listProduits());
model.addAttribute("categories",metier.listCategories());
model.addAttribute("produit", new Produit());
return new ModelAndView("produits");
}

Spring Web MVC Cannot upload file to server

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

Kendo UI gantt chart not loading the data

I am trying to use kendo ui gantt chart in a jsp file. I am using spring mvc and maven for the project. I was following the tutorial given in spring demos, but still I am not getting the result. Nothing is getting displayed in the jsp page.
JSP
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%#page import="java.util.HashMap"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Date"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<kendo:gantt name="gantt" height="700" showWorkDays="false" showWorkHours="false" snap="false">
<kendo:gantt-views>
<kendo:gantt-view type="day" />
<kendo:gantt-view type="week" selected="true" />
<kendo:gantt-view type="month" />
</kendo:gantt-views>
<kendo:gantt-columns>
<kendo:gantt-column field="id" title="ID" width="50" />
<kendo:gantt-column field="title" title="Title" editable="true" />
<kendo:gantt-column field="start" title="Start Time" format="{0:MM/dd/yyyy}" width="100" />
<kendo:gantt-column field="end" title="End Time" format="{0:MM/dd/yyyy}" width="100" />
</kendo:gantt-columns>
<kendo:dataSource batch="false">
<kendo:dataSource-schema>
<kendo:dataSource-schema-model id="id">
<kendo:dataSource-schema-model-fields>
<kendo:dataSource-schema-model-field name="id" type="number" />
<kendo:dataSource-schema-model-field name="orderId" type="number" />
<kendo:dataSource-schema-model-field name="parentId" defaultValue="null" nullable="true" type="number" />
<kendo:dataSource-schema-model-field name="start" type="date" />
<kendo:dataSource-schema-model-field name="end" type="date" />
<kendo:dataSource-schema-model-field name="title" defaultValue="No title" type="string" />
<kendo:dataSource-schema-model-field name="percentComplete" type="number" />
<kendo:dataSource-schema-model-field name="expanded" type="boolean" defaultValue="true" />
<kendo:dataSource-schema-model-field name="summary" type="boolean" />
</kendo:dataSource-schema-model-fields>
</kendo:dataSource-schema-model>
</kendo:dataSource-schema>
<kendo:dataSource-transport>
<kendo:dataSource-transport-read url="/Gantt/tasks/read" dataType="json" type="POST" contentType="application/json" />
<kendo:dataSource-transport-parameterMap>
<script>
function parameterMap(options, type) {
return JSON.stringify(options.models || [ options ]);
}
</script>
</kendo:dataSource-transport-parameterMap>
</kendo:dataSource-transport>
</kendo:dataSource>
<kendo:dependencies batch="false">
<kendo:dataSource-schema>
<kendo:dataSource-schema-model id="id">
<kendo:dataSource-schema-model-fields>
<kendo:dataSource-schema-model-field name="id" type="number" />
<kendo:dataSource-schema-model-field name="predecessorId" type="number" />
<kendo:dataSource-schema-model-field name="successorId" type="number" />
<kendo:dataSource-schema-model-field name="type" type="number" />
</kendo:dataSource-schema-model-fields>
</kendo:dataSource-schema-model>
</kendo:dataSource-schema>
<kendo:dataSource-transport>
<kendo:dataSource-transport-read url="/Gantt/dependencies/read" dataType="json" type="POST" contentType="application/json" />
<kendo:dataSource-transport-parameterMap>
<script>
function parameterMap(options, type) {
return JSON.stringify(options.models || [ options ]);
}
</script>
</kendo:dataSource-transport-parameterMap>
</kendo:dataSource-transport>
</kendo:dependencies>
</kendo:gantt>
Controller
#Controller
public class IndexController {
#Autowired
private GanttTaskDao taskDao;
#Autowired
private GanttDependencyDao dependencyDao;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(Locale locale, Model model) {
return "index";
}
#RequestMapping(value = "/tasks/read", method = RequestMethod.POST)
public #ResponseBody List<GanttTask> read_tasks() {
return taskDao.getList();
}
#RequestMapping(value = "/dependencies/read", method = RequestMethod.POST)
public #ResponseBody List<GanttDependency> read_dependencies() {
return dependencyDao.getList();
}
}
I also used debug mode to run the project but request is going only till /index method and no request is getting send to /gantt/tasks/read or /gantt/dependency/read methods.
I tried using different url in case there might be some error in that. but its still not working.
I dont know where I went wrong. Anybody knows the answer. Is there anything else which i might be missing?
Okay I had done some silly mistake I forgot to include the js and css files to my jsp. I have include it now. When i use debug mode it is retrieving the tasks and dependencies but it is not showing it in my jsp. I can only see the empty chart window. please somebody help.

Spring, Spring-security : Spring-security returning 302, even if login failed

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);

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.

Categories