Yes, I read it is pretty common problem, but reading those post did not really help me.
The short story is that I wanna submit a form on showAllComments.jsp
<form:form method="post" action="postNewComment.html">
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>
Here is the controller:
#Controller
#SessionAttributes
public class CommentController {
#Autowired
private CommentService commentService;
#RequestMapping(value = "/postNewComment", method = RequestMethod.POST)
public ModelAndView showAllUsers(#ModelAttribute("command") Comment comment, BindingResult result) {
System.out.println(comment.getComment());
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", commentService.getComments());
return new ModelAndView("showAllComments", model);
}
}
and here is the result:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
But probably you need to see the whole story, from the beginning:
The user starts the application on index.jsp by clicking
Log in
That link takes him to LoginController
#RequestMapping("/toLoginPage")
public ModelAndView goToLoginPage() {
return new ModelAndView("login", "command", new User());
}
Then he is taken to login.jsp where he provides his username and password.
<form:form method="post" action="log_in.html">
<input type="text" name="uName" />
<input type="password" name="pW" />
<input type="submit" value="Log IN">
</form:form>
he submits the form and he is taken back to LoginController
#RequestMapping(value = "/log_in", method = RequestMethod.POST)
public ModelAndView tryToLogin(#RequestParam("uName") String uName, #RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) {
ModelAndView ret = new ModelAndView("login", "command", new User());
User user = userService.existingUser(uName, pW);
loggedInUser = new User();
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", allComments);
model.put("LOGGED_IN_USER", loggedInUser);
ret = ModelAndView("showAllComments", model);
}
return ret;
}
After successful login he is on the showAllComments page where he sees all the comments and he should be able to add his own comment but submitting the above mentioned form throws the above mentioned exception. I feel something is missing but I can't figure out what it is. Just for the record I show the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
and the spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="net" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>net.model.User</value>
<value>net.model.Comment</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
</beans>
You need to add a your form bean class ie Comment, as an attribute to your model when you show the showAllComments.jsp in the logincontroller.
#RequestMapping(value = "/log_in", method = RequestMethod.POST)
public ModelAndView tryToLogin(#RequestParam("uName") String uName, #RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) {
ModelAndView ret = new ModelAndView("login", "command", new User());
User user = userService.existingUser(uName, pW);
loggedInUser = new User();
model.addAttribute("command", new Comment());
if (user != null) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", allComments);
model.put("LOGGED_IN_USER", loggedInUser);
ret = ModelAndView("showAllComments", model);
}
return ret;
}
This should work fine.
UPDATE
And it is not a good practise to use 'command' as the command object name. For the class comment you can use a 'comment' or something like that.
If your doing that, Update your form with the following code.
<form:form method="post" action="postNewComment.html" commandName="comment">
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>
Do the same change at all other places, viz
model.addAttribute("comment", new Comment());
and
#ModelAttribute("comment")
UPDATE 2
#RequestMapping(value="userRegistration", method = RequestMethod.GET)
public ModelAndView showUserRegistrationForm(Model model){
model.addAttribute("user", new AccountDetailsForm());
return new ModelAndView("userRegistration");
}
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 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 try to implement loading a photo and String object. Here is a declaration of my method.
#RequestMapping(method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public #ResponseBody ResponseEntity<UserWithPhoto> update(#RequestHeader(value="Access-key") String accessKey,
#RequestHeader(value="Secret-key") String secretKey,
#RequestPart("user") String string,
#RequestPart("photo") MultipartFile file) throws Exception
And this is my multi part resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10000000" />
</beans:bean>
And I havn't idea why I get
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
I always wrap multipart files in a POJO with other properties needed:
public class FileUpload {
private Long id;
private MultipartFile file;
// getters and setters
}
In my view:
<spring:url value="/myEndpoint" var="url_upload"/>
<form:form method="POST" enctype="multipart/form-data" commandName="fileUpload" action="${url_upload}" >
<form:hidden path="id" />
<input type="file" name="file" id="inputFile"/>
<input type="submit" value="Upload" />
</form:form>
And in the endpoint:
#RequestMapping(value = "/myEndpoint", method = RequestMethod.POST)
public String uploadFile(#ModelAttribute("fileUpload") FileUpload dto, Model uiModel) {
// Process file
}
Try adding this block code to your config:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/index" />
<property name="suffix" value=".jsp" />
</bean>
and load your config on web.xml
i have a problem to retrieve the Collection(or ArrayList) from a Controller to jsp using ajax in Spring MVC.
The Controller code is:
ProjectController.java
#Controller
public class ProjectController {
protected final Logger log = Logger.getLogger(ProjectController.class);
#Autowired
private AziendaService service;
#RequestMapping(value ="/companyList", method = RequestMethod.GET,headers = "application/javascript")
public #ResponseBody Object getCompanyList_AJAX() {
log.info("initiale getCompanyList_AJAX method.....");
Collection<Company> collection = service.getAllCompany();
return collection;
}
}
where Company(Azienda) is Class POJO and Entity in my DBMS.
and the dispatcher-servlet.xml is:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven />
<context:property-placeholder location="classpath:properties/*.properties"/>
<context:component-scan base-package="spring.hibernate"/>
<tx:annotation-driven />
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${connection.driver_class}" />
<property name="url" value="${connection.url}" />
<property name="username" value="${connection.username}" />
<property name="password" value="${connection.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>spring.hibernate.model.Account</value>
<value>spring.hibernate.model.Assegnazione</value>
<value>spring.hibernate.model.Attivita</value>
<value>spring.hibernate.model.Azienda</value>
<value>spring.hibernate.model.Comune</value>
<value>spring.hibernate.model.Dipendente</value>
<value>spring.hibernate.model.Persona</value>
<value>spring.hibernate.model.Progetto</value>
<value>spring.hibernate.model.Provincia</value>
<value>spring.hibernate.model.Regione</value>
<value>spring.hibernate.model.Timesheet</value>
<value>spring.hibernate.model.Workpackage</value>
</list>
</property>
</bean>
<bean id="accountDAO" class="spring.hibernate.dao.AccountDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="aziendaDAO" class="spring.hibernate.dao.AziendaDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
and The ajax in JSP code is: addProject.jsp
<script type="text/javascript">
$(window).load(function () {
$.ajax({
type: 'GET',
url: 'companyList.htm',
datatype:'text',
success: function(response, status, xhr) {
if(xhr.readyState == 4 &&(xhr.status == 200 || xhr.status == 0)) {
var values = [];
values = response;
$.each(values, function( index, value ) {
alert( index + ": " + value );
});
document.getElementById("loaderCompany").style.display = "none";
}
else if(xhr.readyState < 4) {
document.getElementById("loaderCompany").style.display = "inline";
}
}
</script>
I don't know why i can't retrieve the list of company in ajax. I debugged it in Chrome console and the error is GET http://localhost:8060/Project/companyList.htm 404 (Not Found).
Someone Can help me to resolve the problem??.
Thanks.
There are couple things here.
Firstly refer to this post about 406 regarding JSON responses that will help you understand what it is all about: What is "406-Not Acceptable Response" in HTTP?
Secondly i couldn't help notice the following piece of code:
public #ResponseBody Object getCompanyList_AJAX() {
and you are returning:
Collection<Company> collection = service.getAllCompany();
return collection;
Personal issues that i have had with 406 is due to declaration not having same type as actual return variable.
Change it to
public #ResponseBody Collection<Company> getCompanyList_AJAX() {
Finally you can also in your ajax call remove the datatype: 'text', and let it determine it intelligently as per API documentation https://api.jquery.com/jQuery.ajax/
Give that a go and if it still doesn't work then we have to dig into your configuration further.
In case your Spring MVC configuration is correct I recommend to do the following:
Remove the headers attributes and try to reach the URL within the browser. If this works, your Request Mapping is ok. If not there is something wrong with your MVC config and/or the servlet mapping.
In case the first step is successful, you can try to add the headers again, but like this:
headers = "x-requested-with=XMLHttpRequest"
The consequence of setting this is header: The URL is not reachable by a normal browser GET. The request header "x-requested-with" is expected to be set. (just a note)
Have fun!
Thanks everybody for the answer.. i resolved the problem using another JSP page(test.jsp) to get my collection which contain the list of company. This page is callback in the ajax code and append <option> </option> from companyList.jsp in addproject.jsp
This is ProjectController.java:
#Controller
public class ProjectController {
protected final Logger log = Logger.getLogger(ProjectController.class);
#Autowired
private AziendaService service;
#RequestMapping(value ="/addProject", method = RequestMethod.GET)
public String addProject(HttpServletRequest request) {
log.info("initiale createProject method.....");
HttpSession session = request.getSession();
if(session.getAttribute("username") == null){
log.info("la session è expire....");
return "sessionExpired";
}
return "addProject";
}
#RequestMapping(value ="/companyList", method = RequestMethod.GET)
public String getCompanyList_AJAX(WebRequest request) {
log.info("initiale getCompanyList_AJAX method.....");
Collection<Company> collection = service.getAllCompany();
request.setAttribute("modelList", collection,WebRequest.SCOPE_REQUEST);
return "companyList";
}
}
and the Test.jsp is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<select>
<c:forEach items="${modelList}" var="model">
<option value="${model.ragione_sociale}">${model.ragione_sociale}</option>
</c:forEach>
</select>
</body>
</html>
and finally in addProject.jsp part of ajax:
<script type="text/javascript">
$(window).load(function () {
$.ajax({
type: 'GET',
url: 'companyList.htm',
success: function(response, status, xhr) {
if(xhr.readyState == 4 &&(xhr.status == 200 || xhr.status == 0)) {
var html = $(response).filter('select').html();
$('#company').append(html);
}
}
});
});
</script>
And That's all. See and thx again.
I keep getting this error when i do with my spring mvc code i am trying to do image upload using spring mvc what is the arguments I am missing.
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is java.lang.IllegalArgumentException: argument type mismatch
java.lang.IllegalArgumentException: argument type mismatch
...
My dispatcher servlet is
<context:component-scan base-package="com.ImageUploadSpring.Controller" />
<!-- <bean id="simpleHandler" class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/Upload.html">FileUpload</prop>
</props>
</property>
</bean>
<bean id="FileUpload" class="com.ImageUploadSpring.Controller.FileUpload">
<property name="commandName" value="ImageUpload"/>
<property name="commandClass" value="com.ImageUploadSpring.Bean.UploadItem"/>
<property name="formView" value="ImageUpload"/>
<property name="successView" value="message"/>
</bean>
<bean id="FileUpload" class="com.ImageUploadSpring.Controller.FileUpload"></bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
</bean>
controller class is
public class FileUpload extends SimpleFormController{
#RequestMapping(value = "/Upload.html", method = RequestMethod.POST)
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors,HttpSession session) {
System.out.println("inside submit method");
try{
UploadItem item=(UploadItem)command;
MultipartFile file = item.getFile();
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
outputStream = new FileOutputStream("D:/UploadedFiles/Images/"
+ file.getOriginalFilename());
System.out.println(file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "D:/UploadedFiles/Images/"
+ file.getOriginalFilename());
}
}catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("message");
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws ServletException {
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
And my html page is
<form name="ImageUpload" action="/ImageUploadSpring/service/Upload.html" method="POST" enctype="multipart/form-data">
<div>
Select images:
<input type="text" id="box"/>
<input type="file" id="UploadFile" name="UploadFile" onchange="CopyMe(this,'box');" accept="image/*" size="40" style="width: 91px;" multiple />
<br><br>
<input type="submit" value="Upload" /><br><br>
</div>
</form>
Try this:
protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="UploadFile") MultipartFile image, BindException errors,HttpSession session)
While defining <input type="file"> you have specified the name name="UploadFile". Whereas in your UploadItem command object the file attribute is file (guessing from item.getFile()). Are you sure you are correctly mapping the filename?
Please refer to this tutorial for working tutorial on Spring MVC File Upload
this tutorial http://www.journaldev.com/2573/spring-mvc-file-upload-example-tutorial-single-and-multiple-files also works well for me. it is quite simple.
the important is when you use
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
,
don't forget to add commons-fileupload to your pom dependencies.