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.
Related
while fetching file from spring form I am getting null value and If I try this code for rest of fields i mean non multipart input types its working fine. while debugging I am getting null value from line. If I try to fetch image from existing folder i'e image under webapp and that url is able to display image in browser but not able to read value from files using browser and sorry for my bad english
edit if i comment the image code, application is working fine but when I introduce the code for image I'm getting error
MultipartFile file = domain.getImage(); //this is getting null
this is relevent code
controller
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String formInputGet(Model model) {
model.addAttribute("domain", new Domain());
return "form";
}
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String formInputPost(#ModelAttribute("domain") Domain domain, HttpServletRequest httpServletRequest) {
MultipartFile file = domain.getImage();
if (image== null)
throw new NullPointerException("unable to fetch "+file); //getting NPE everytime
String rootDirectory = httpServletRequest.getSession().getServletContext().getRealPath("/");
if (domain.getImage() != null && !domain.getImage().isEmpty())
try {
File path = new File(rootDirectory + "images\\" + domain.getFirstName() + ".png");
file.transferTo(path);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
repositiry.addToList(domain);
return "redirect:/";
}
form.jsp
<form:form modelAttribute="domain" enctype="multipart/form-data">
First Name<br>
<form:input path="firstName" />
<br>Last Name :<br>
<form:input path="lastName" />
<br>upload Image<br>
<form:input path="image" type="file" />
<hr>
<input type="submit">
</form:form>
dispatcherServlet
<mvc:annotation-driven />
<mvc:resources location="/images/" mapping="/images/**" />
<context:component-scan base-package="com" />
<bean id="multipartReslover"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
I added some extra code to find if I am getting domain as null came to be true. And I have no Idea how to solve that.
after adding check for file i'm getting error
java.lang.NullPointerException: unable to fetch : null
domain.java
public class Domain {
private String firstName;
private String lastName;
private MultipartFile image;
//getters and setters
NOTE any helpful answer if it have other way of working is welcomed too :)
any help is appreciated, thanks :)
you should do everything #kuhajeyen said and if getting image from domain object didnt go well you can try this
public String formInputPost(#ModelAttribute("domain") Domain domain,
#RequestParam("image") MultipartFile imagefile,
HttpServletRequest httpServletRequest ) {
imagefile.transferTo(path);
}
edit :- change method attribute to POST inside the form otherwise it will make a GET request.
<form:form modelAttribute="domain" method="post" enctype="multipart/form-data">
and replace your input type file with this line, i think there is some issues when trying to bind input type file with an object.
<input type="file" name="image" />
You need to tell the spring, how to resolve multipart file
add this bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="409600"/>
</bean>
And also it seems you have not mapped your action in form
<form:form modelAttribute="domain" enctype="multipart/form-data" action="xxxx/form">
....
</form:form>
There were two typos in my configuration file as they are
1) <mvc:resources location="/images/" mapping="/images/**" /> here mapping was supposed to be like mapping ="images/**"
2)File path = new File(rootDirectory + "images\\" + domain.getFirstName() + ".png"); here path is supposed to be as rootDirectory+"\\images\\"+.... instead
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 welcome.jsp which has signUp link when it is clicked javascript function showSignUp is called which invokes controller and controller should redirect it to the signUp form(signup.jsp).But redirect is not happening and I am getting Error 405 Method Not Found.(Controller call is happening I am able to print sysout "In ShowSignUp method" )
Welcome.jsp
<body>
<a href="javascript:signupObj.showSignup ();" >SignUP</a>
</body>
signup.js
var signupObj = {
showSignup : function() {
$.ajax({
url: "showSignup",
success: function(response) {
alert("sucessful");
}
});
}
};
Controller Class
#RequestMapping(value="/showSignup")
public String showSignup(HttpServletRequest httprequest,HttpServletResponse httpResponse) {
System.out.println("In ShowSignUp method");
return "redirect:signup";
}
Signup.jsp
<form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username : </td>
<td><input id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
Web.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<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>
You can return just view name without redirect like this:
return "Signup";
But redirect is not happening and I am getting Error 405 Method Not
Found
You are using ajax call in your application and i dont understand why you need to redirect it to another page . the purpose of ajax is to update the part of a page.
return "redirect:signup";
As you redirect it to signup have you handled it with another request mapping url like this,
#RequestMapping(value="/signup",,method=RequestMethod.GET)
public String showSignup(HttpServletRequest httprequest,HttpServletResponse httpResponse) {
System.out.println("In ShowSignUp method");
return "View Name Here";
}
Remember you should follow P-R-G pattern once you redirect
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.
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");
}