I am using Spring MVC and have a form that looks like this : https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-ash3/1526193_10152219199443013_1553859401_n.jpg
On the form there is a button for uploading pictures and when I try to get the file into my controller using an argument I get HTTP-400 status when i press the ok button.
What is the problem and how to fix this issue with files
My jsp code :
<form:form method="post" commandName="editPersonBean" enctype="multipart/form-data">
<form:hidden path="id" />
<table class="myTable">
<c:if test="${editPersonBean.id > 0}">
<tr>
<th>ID</th>
<td>${editPersonBean.id}</td>
</tr>
</c:if>
<tr>
<td>Förnamn</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Efternamn</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td>Telefon nummer</td>
<td><form:input path="phoneNumber" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Övrigt</td>
<td><form:input path="otherInfo" /></td>
</tr>
<tr>
<td>Bild</td>
<td><form:label path ="image" />
<input type="file" name="file" />
</td>
</tr>
<br>
<br>
<tr>
<td><c:set var="submitText">
OK
</c:set> <input type="submit" size="20" value="${submitText}" /> </td>
<td></td>
</tr>
</table>
</form:form>
When I am passing in this argument into the controller to catch up the uploaded file its then I get the problem.
#RequestParam("file") MultipartFile file
And the controller I am having problem with looks like the following :
#Controller
#RequestMapping("/editPerson/{id}.html")
public class EditPersonContoller {
#Autowired
PersonService service;
#RequestMapping(method = RequestMethod.GET)
public ModelAndView index(#PathVariable int id) {
EditPersonBean bean = new EditPersonBean();
if (id > 0) {
Person person = service.getPerson(id);
bean.copyValuesToBean(person);
}
ModelAndView mav = new ModelAndView("editPerson");
mav.addObject("editPersonBean", bean);
return mav;
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView handleSubmit(EditPersonBean bean, BindingResult errors, #RequestParam("file") MultipartFile file) {
if (errors.hasErrors()) {
ModelAndView mav = new ModelAndView("editPerson");
mav.addObject("editPersonBean", bean);
return mav;
}
if (bean.getId() > 0) {
Person person = service.getPerson((int) bean.getId());
bean.copyBeanValuesToPerson(person);
saveImage(person, file);
service.updatePerson(person);
} else {
Person person = new Person();
bean.copyBeanValuesToPerson(person);
saveImage(person, file);
service.createPerson(person);
}
return new ModelAndView("redirect:/person.html");
}
public void saveImage(Person person, #RequestParam("file") MultipartFile file) {
try {
Blob blob = Hibernate.createBlob(file.getInputStream());
person.setImage(blob);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Also I am trying to save the picture using a bean :
public class EditPersonBean {
private int id;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String otherInfo;
private Blob image;
public void copyValuesToBean(Person person){
setId((int) person.getId());
setFirstName(person.getFirstName());
setLastName(person.getLastName());
setEmail(person.getEmail());
setPhoneNumber(person.getPhoneNumber());
setOtherInfo(person.getOtherInfo());
setImage(person.getImage());
}
public void copyBeanValuesToPerson(Person person){
person.setId((int) getId());
person.setFirstName(getFirstName());
person.setLastName(getLastName());
person.setEmail(getEmail());
person.setPhoneNumber(getPhoneNumber());
person.setOtherInfo(getOtherInfo());
person.setImage(image);
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOtherInfo() {
return otherInfo;
}
public void setOtherInfo(String otherInfo) {
this.otherInfo = otherInfo;
}
public Blob getImage() {
return image;
}
public void setImage(Blob image) {
this.image = image;
}
}
And I am trying to save it into the database through a service that just calls the repository :
#Override
public void createPerson(Person person) {
session.getCurrentSession().save(person);
}
And finally it should go down to the model and persist it into the database:
#Column(name = "image")
#Lob
private Blob image;
But no image is being saved into the database and instead the page return an http : 400- Status.
Whats the problem here?
The Spring MVC documentation explains its support for multipart file uploading.
Basically, you need to provide a MultipartResolver in the ApplicationContext that will be available to the DispatcherServlet. You have a few options. A common one is CommonsMultipartResolver, for which you will need Apache's commons-fileupload.jar. The documentation provides the following example
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
The DispatcherServlet will detect this bean in your ApplicationContext and register it so that it can process requests that have a Content-Type of multipart/.... On each such request, it will wrap the HttpServletRequest in a MultipartHttpServletRequest.
Spring uses a RequestParamMethodArgumentResolver to resolve arguments for parameters annotated with #RequestParam in your #RequestMapping annotated handler methods.
If the parameter is also of type MultipartFile, Spring will cast the HttpServletRequest to a MultipartHttpServletRequest created earlier and use it to retrieve the parts, one of which is your file.
If this configuration is not done, the whole process fails and you likely get a 400 Bad Request.
how you are getting file in the controller which is uploaded by the JSP, put the below method in your controller and debug your code
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
FileUpload file = (FileUpload)command;
MultipartFile multipartFile = file.getFile();
String fileName="";
if(multipartFile!=null){
fileName = multipartFile.getOriginalFilename();
//do whatever you want
}
System.out.println("filename :" + fileName);
return new ModelAndView("FileUploadSuccess","fileName",fileName);
}
Related
I have created a dynamic form in Thymeleaf which populates feedbacks from all users in a table format on the UI. The form is first called when the GET Api of the controller gets hit. Relevant code for the same is given below :
allfeedbacks.html
<h2>Dynamic form</h2>
<form action="#" th:action="#{/updatefb}" th:object="${feedbacklist}"
method="post">
<table>
<tr>
<th>Message</th>
<th>Status</th>
<th>Comments</th>
</tr>
<tr th:each="feedback : ${feedbacklist.myfbList}">
<td th:text="${feedback.message}" th:field="${feedback.message}">The
first name</td>
<td><select>
<option value="Pending"
th:selected="${feedback.status == 'Pending'}">Pending</option>
<option value="In Process"
th:selected="${feedback.status == 'In Process'}">In
Process</option>
<option value="Done" th:selected="${feedback.status == 'Done'}">Done</option>
</select></td>
<td><input type="text" placeholder="Enter Comment Here"
name="comments" th:text="${feedback.comment}"
th:field="${feedback.comment}" /></td>
</tr>
</table>
<button type="submit">Submit</button>
</form>
Basically I have created two beans, one is the Feedback.java bean while the other is FeedbackList.java bean. Code for the same is given below :
Feedback.java
#Entity
#Table(name = "feedback")
public class Feedback implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
#Id
private String id;
public String getId() {
return id;
}
public String getMessage() {
return message;
}
public String getStatus() {
return status;
}
public String getComment() {
return comment;
}
#Column(name = "message")
private String message;
#Column(name = "status")
private String status;
#Column(name = "comment")
private String comment;
public Feedback() {
}
public Feedback(String message, String status) {
this.message = message;
this.status = status;
this.id = UUID.randomUUID().toString();
}
FeedbackList.java
public class FeedbackList {
ArrayList<Feedback> myfbList;
public ArrayList<Feedback> getMyfbList() {
return myfbList;
}
public void setMyfbList(ArrayList<Feedback> myfbList) {
this.myfbList = myfbList;
}
}
Relevant code from my Controller class is as follows :
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public String getAllFeedbacks(#Valid FeedbackList feedbacklist,
BindingResult bindingResult, Model model) {
ArrayList<Feedback> fbarray = new ArrayList<>();
for (Feedback fb : repository.findAll()) {
fbarray.add(fb);
}
feedbacklist.setMyfbList(fbarray);
model.addAttribute("feedback", new Feedback());
model.addAttribute("feedbacklist", feedbacklist);
return "allfeedbacks";
}
#RequestMapping(value = "/updatefb", method = RequestMethod.POST)
public String updatefbStatus(#Valid FeedbackList feedbacklist,
BindingResult
bindingResult, Model model) {
//feedbacklist is coming as NULL below
for (Feedback fb : feedbacklist.getMyfbList()) {
System.out.println(fb.getComment());
System.out.println(fb.getMessage());
System.out.println(fb.getStatus());
}
// Code to update the database with the new status and comment would go
// here
return "result";
}
The form is getting properly rendered on the UI when I fire the Get request, however, when I make some changes in the form and submit it ( POST ), feedbacklist is coming as NULL. Could anyone please guide me with this ?
To use a list inside a form with Thymeleaf is a little bit more tricky, you need to use an specific syntax, here i show you an example.
<tr th:each="feedback : ${feedbacklist.myfbList}">
<td th:field="*{myfbList[__${feedbackStat.index}__].message}">The
first name
</td>
...//Same for others fields
</tr>
In thymeleaf you have to use the Stat object to say the array position where you want to set the value, also as normal fields inside an object you have to use the '*' notation.
Trying to get Spring annotation based validation working in a simple webapp. While using #ModelAttribute along with #Valid, I am getting validation error next to the field, however when I am adding object to model, not getting error messages.
Suggest any alternative approach to display form validation error message(i.e. without using #ModelAtrribute along with #Valid)
Below is the code:
EmployeeModel.java
#Entity
#Table(name = "Employee")
public class EmployeeModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#NotNull(message = "ID is required")
private Integer employee_id;
#Column(name = "Name")
#NotEmpty(message = "Name is required")
private String employee_name;
#Column(name = "Manager")
private String manager;
public Integer getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Integer employee_id) {
this.employee_id = employee_id;
}
public String getEmployee_name() {
return employee_name;
}
public void setEmployee_name(String employee_name) {
this.employee_name = employee_name;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
#Override
public String toString() {
return "Employee [id=" + employee_id + ", Name=" + employee_name
+ ", Manager=" + manager + "]";
}
}
Code snippet in Controller
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(Model model, #Valid EmployeeModel employee, BindingResult result) {
if (result.hasErrors()) {
model.addAttribute("employee", employee);
//model.addAttribute(employee);
return "EmployeeForm";
}
employeeService.addEmployee(employee);
return "forward:/";
}
View:
<form:form action="save" method="post" modelAttribute="employee">
<tr>
<td><form:label path="employee_id">Employee ID:</form:label></td>
<td><form:input path="employee_id" /></td>
<td><form:errors path="employee_id"/></td>
</tr>
<tr>
<td><form:label path="employee_name">Employee Name:</form:label></td>
<td><form:input path="employee_name" /></td>
<td><form:errors path="employee_name"/></td>
</tr>
<tr>
<td><form:label path="manager">Manager:</form:label></td>
<td><form:input path="manager" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Save"></td>
</tr>
</form:form>
In case I use the commented line
//model.addAttribute(employee)
I get exception stating: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'employee' available as request attribute.
Replacing the commented line with
model.addAttribute("employee",employee)
Page gets loaded with the previous value entered which means invalid object is not getting replaced, still error message is not displayed.
The above can be achieved using #ModelAttribute along with #Valid, but is there any other alternative i.e. without using #ModelAtrribute?
What is the difference in working with #ModelAttribute and Model, as till now I considered both works in similar way?
#ModelAttribute populates the fields of a class, which then populates an attribute of the model to be passed back to the view.
Also you make following change on your saveEmployee method. You do not need to add attribute to model. #ModelAttribute automatically add for you.
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(#Valid #ModelAttribute(name = "employee") EmployeeModel employee, BindingResult result) {
if (result.hasErrors()) {
return "EmployeeForm";
}
employeeService.addEmployee(employee);
return "forward:/";
}
The below data is stored in MongoDB. I am using Spring-Data and storing the data into mongoDB.
If I want to retrieve the fields ("id" or "Name") I can able to do, but if I want to retrieve the sub fields ("firstName" or "lastName")I can't.
(eg.)If I want to retrieve sub field "lastName" from the below data I can't.Kindly help me in this regard.
Thanks in advance.
Data Stored in MongoDB:
{
"id":101,
"name": {"firstName":"Mark",
"lastName":"Antony"
}
}
The Code I am using is:
PersonService.java
public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME);
}
PersonController.java
#RequestMapping(value = "/person/search", method = RequestMethod.GET)
public String search(#ModelAttribute Audit audit, ModelMap model) {
model.addAttribute("personList", personService.searchPerson(audit));
return "output";
}
Audit.java
#Document
public class Audit {
#Id
private String id;
private List<NameDetails> name;
public String getId() {
System.out.println("Person: getId");
return id;
}
public void setId(String id) {
System.out.println("Person: setId");
this.id = id;
}
public List<NameDetails> getName() {
System.out.println("Audit: getName");
return name;
}
public void setName(List<NameDetails> name) {
System.out.println("Audit: setName");
this.name = name;
}
}
NameDetails.java
package com.register.mongo.model;
public class NameDetails {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}
}
(output.jsp)UI Page
<form action="person/search" method="get">
<table>
<tr><td>
<label>Name</label>
<input type="text" id="lastName" name="lastName"/>
</td></tr>
<tr><td>
<input type="submit" value="Search"/>
</td></tr>
</table>
</form>
<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td>
</tr>
<tr>
<td>${person.lastName}</td>
</tr>
</c:forEach>
</table>
Change
return mongoTemplate.find(
new Query(Criteria.where("name.lastName").is(name.get(0))),
Audit.class,COLLECTION_NAME);
to
return mongoTemplate.find(
new Query(Criteria.where("name.lastName").is(name.get(0).getLastName())),
Audit.class,COLLECTION_NAME);
You are trying to use the entire NameDetails instead of just the last name.
I have looked at other posting on this subject but couldn't get it to work. This seems to be a simple issue. I would appreciate if someone could help.
Person.java
#Entity
#Table(name = "PERSON")
public class Person {
#Id
#Column(name = "PERSON_ID")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
public Person() {
}
public Person(String fname, String lname) {
this.firstName = fname;
this.lastName = lname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first_name) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last_name) {
this.lastName = last_name;
}
}
PersonController.java
#Controller
#RequestMapping("person")
public class PersonController {
#RequestMapping(value = "add", method = RequestMethod.POST)
public String addPerson(
#ModelAttribute("person") #Valid Person person, BindingResult result) {
log.info("in add");
personValidator.validate(person, result);
if (!result.hasErrors())
personService.addPerson(person);
return "redirect:/spring/person/list";
}
person.jsp
<body>
<form:form method="post" action="add.html" commandName="person">
<form:errors path="*" cssClass="errorblock" />
<table>
<tr>
<td><form:label path="firstName">First name</form:label></td>
<td><form:input path="firstName" /></td>
<td><form:errors path="*" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last name</form:label></td>
<td><form:input path="lastName" /></td>
<td><form:errors path="*" cssClass="error" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add" /></td>
</tr>
</table>
</form:form>
</body>
</html>
PersonValidator.java
#Component
public class PersonValidator implements Validator {
public void validate(Object arg0, Errors arg1) {
Person person = (Person) arg0;
if (personService.findPersonByName(person.getFirstName(), person.getLastName()) != null)
arg1.rejectValue("firstName", "first name empty");
//arg1.reject("save.person", "User already exists.");
}
}
personService.findPersonByName is not null and result.hasErrors() is true, so I know the form has errors but they don't display for some reasons.
You're performing a redirect
mav = new ModelAndView("redirect:/spring/person/list", "person", person);
Your errors are stored in the model and subsequently in the HttpServletRequest attributes. These only last for the duration of one request. A redirect causes the client to send a new request. They therefore don't exist when your redirected view is rendered.
Consider using flash attributes. Look into RedirectAttributes. That's how POST-REDIRECT-GET typically works.
How does your person bean looks like? Do you have validation annotation(s) there also? Please paste fields.
try this instead:
#RequestMapping(value = "add", method = RequestMethod.POST)
public ModelAndView addPerson(
#ModelAttribute("person") #Valid Person person, BindingResult result) {
ModelAndView mav;
log.info("in add");
personValidator.validate(person, result);
if (result.hasErrors()) {
mav = new ModelAndView("your view here");
mav.addObject("person", person);
return mav;
}
personService.addPerson(person);
mav = new ModelAndView("redirect:/spring/person/list", "person", person);
return mav;
}
If there are any errors we want to add the bean to the mav and display the view again. (If you've got validation in the bean also, the errors will display on the jsp) else the person will be created and redirect..
As you have now, the error messages cannot display because of the redirecting. Therefore we want to add the bean to the view and display the view again.
Make sure correct validation dependencies are added to your project like below 2:
<!-- https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>2.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.5.Final</version>
</dependency>
Note:
1) Even though hibernate is not used in your project you'll need a bean validation implementer. hibernate-validator provides such implementation.
2) Make sure correct dependency versions are added like below for hibernate-validator 6.2.5.Final needs jakarta.validation version 2.0.2.
I want to send data from form to PostgreSQL. When I send data by form, hibernate save (by save() method) blank record .. I did it manually (for test) without using form and then everything is ok.
Spitter.class (entity for user)
#Entity
#Table(name="spitter")
public class Spitter implements Serializable {
private static final long serialVersionUID = 829803238866007413L;
#Id
//#SequenceGenerator(name = "hibernate_sequence")
#GeneratedValue(strategy=GenerationType.AUTO) #Column(name="spitter_id")
private Long id;
#Column(unique=true) #Size(min=3, max=20) #Pattern(regexp = "^[a-zA-Z0-9]+$", message="Nie poprawna nazwa uzytkownika.")
private String username;
#Size(min=5, max=15, message="Haslo musi miec minimum 5 znakow.")
private String password;
#Size(min=3, max=25, message="Blad w imieniu i nazwisku.")
private String fullName;
#OneToMany(mappedBy="spitter")
private List<Spittle> spittles;
#Email(message="Nie poprawny adres email.")
private String email;
private boolean updateByEmail;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public List<Spittle> getSpittles() {
return spittles;
}
public void setSpittles(List<Spittle> spittles) {
this.spittles = spittles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setUpdateByEmail(boolean updateByEmail) {
this.updateByEmail = updateByEmail;
}
public boolean isUpdateByEmail() {
return updateByEmail;
}
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName) && other.username.equals(username) && other.password.equals(password);
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
SpitterController.class
createSpitterProfile - shows form (edit.jsp) and sends model object (spitter) to form
addSpitterFromForm - receives binding data from form and save it to database and redirects to simply user profile
showSpitterProfile - there is of course null model object exception
#Controller
#RequestMapping("/spitters")
public class SpitterController {
private final SpitterService spitterService;
#Inject //#Autowired
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
//...
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
#RequestMapping(value="/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
model.addAttribute(spitterService.getSpitter(username));
return "spitters/view";
}
edit.jsp (registration form for new user (Spitter))
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>New account test</h2>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="username">Username:</sf:label></th>
<td><sf:input path="username" size="15" maxlength="15" />
<small id="username_msg">No spaces, please.</small><br/>
<sf:errors path="username" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="password">Password:</sf:label></th>
<td><sf:password path="password" size="30"
showPassword="true"/>
<small>6 characters or more (be tricky!)</small><br/>
<sf:errors path="password" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="email">Email Address:</sf:label></th>
<td><sf:input path="email" size="30"/>
<small>In case you forget something</small><br/>
<sf:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<th></th>
<td>
<sf:checkbox path="updateByEmail"/>
<sf:label path="updateByEmail">Send me email updates!</sf:label>
</td>
</tr>
<tr>
<th></th>
<td>
<input name="commit" type="submit"
value="I accept. Create my account." />
</td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
and blank saved record to Postgres..
Try adding #modelattribute in this method .It fill fetch the required model object.
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(**#ModelAttribute("spitter")** #Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
and just to check if it is getting the values from form,syso some values like syso(spitter.getUserName) to check if values are coming.
ALso, I believe that you are making a constructor and passing service to it ,so there is no need of #Inject
#Inject //#Autowired///Why are you injecting it if it is a constructor?
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
You have enctype="multipart/form-data in your FORM,
Check that you have something like that in your App-servlet.xml:
<bean id="multipartResolver" class=
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxUploadSize="500000" />