download Document object using spring mvc without jsp - spring

I am trying to create pdf file using POJO and download it using spring mvc.i have got the Document object but can not download the file. it gives error "could not find convertor".
#RequestMapping(value = "/downloadPDF", method = RequestMethod.GET)
public Document downloadPDF() throws FileNotFoundException, DocumentException {
// create some sample data
List<EmployeeInfo> employeeList = new ArrayList<EmployeeInfo>();
employeeList.add(new EmployeeInfo("1", "Anish", "surat"));
return downloadPDFService.createPDF(employeeList);
how can i download this file.
please provide answer
public Document createPDF( List<EmployeeInfo> employeeList) throws FileNotFoundException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf"));
document.open();
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100); //Width 100%
table.setSpacingBefore(10f); //Space before table
table.setSpacingAfter(10f); //Space after table
PdfPCell cell = new PdfPCell();
cell.setBackgroundColor(BaseColor.BLUE);
cell.setPadding(5);
Font font = FontFactory.getFont(FontFactory.HELVETICA);
font.setColor(BaseColor.WHITE);
cell.setPhrase(new Phrase("Id", font));
table.addCell(cell);
cell.setPhrase(new Phrase("Name", font));
table.addCell(cell);
cell.setPhrase(new Phrase("Address", font));
table.addCell(cell);
for (EmployeeInfo aBook : employeeList) {
table.addCell(aBook.getEmpId());
table.addCell(aBook.getEmpName());
table.addCell(aBook.getEmpAddress());
}
document.add(table);
document.close();
writer.close();
return document;
}
this is a view creator.next is stack trace
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException:
No converter found for return value of type: class com.itextpdf.text.Document
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class com.itextpdf.text.Document
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalArgumentException: No converter found for return value of type: class com.itextpdf.text.Document
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:178)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:153)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:165)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Though you don't want jsp, you still can use ModelAndView.
Change your DownloadPDFService as below.
#Component
public class DownloadPDFService extends AbstractPdfView {
#Override
protected void buildPdfDocument(Map<String, Object> model, Document doc,
PdfWriter writer, HttpServletRequest req, HttpServletResponse resp)
throws Exception {
// Retrieve your model as below
List<EmployeeInfo> employeeList = (List<EmployeeInfo>) model.get("employeeList");
// continue your document build logic
}
}
Change your controller as below
#RequestMapping(value = "/downloadPDF", method = RequestMethod.GET)
public Document downloadPDF() throws FileNotFoundException, DocumentException {
// create some sample data
List<EmployeeInfo> employeeList = new ArrayList<EmployeeInfo>();
employeeList.add(new EmployeeInfo("1", "Anish", "surat"));
return new ModelAndView("pdfView", "employeeList", employeeList);
}
Add below views configuration in views.properties
pdfView.(class)= YourpackageName.DownloadPDFService
Configure a new ResourceBundleViewResolver for above "views" properties.

Related

FileSystemResource to MultipartFile

I want to send my image from my storage using the path like this:
MultiValueMap<String, Object> image = new LinkedMultiValueMap<String, Object>();
image.add("image", new FileSystemResource("C:\\xx\\xx\\xx\\xx\\xx\\xx\\xx\\img\\xx.jpg"));
so I call the object using the code below:
MultiValueMap<String, Object> body = new LinkedMultiValueMap<String,Object>();
body.add("image", image);
Then, I get this error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class sun.nio.ch.ChannelInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class sun.nio.ch.ChannelInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["image"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["inputStream"])
I am using the Rest Template of spring boot, which requires me to send by POST Method the MultipartFile object. Now, I do not know how to convert into the MultipartFile type,
so the Rest Template can accept my request post.
Note: I want to use the body.add("image", image.getResource()); but It did not show up in selection since image wasn't of MultipartFile type.
This worked for me.
#GetMapping(path = "/copy", produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> copyFile() {
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("image", new FileSystemResource("test.jpg"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8080/upload";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity(serverUrl, requestEntity, String.class);
return response;
}
#PostMapping(path = "/upload", produces = MediaType.TEXT_PLAIN_VALUE)
public String uploadFile(#RequestParam("image") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("./uploadedImages/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
return "Error";
}
return "File Uploaded";
}

Spring MockMvc Post Test: Comparison Failure

I am trying to perfom a Post test on this method with mockito
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBookPost(#ModelAttribute("book") Book book, HttpServletRequest request, Model model) {
bookService.save(book);
MultipartFile bookImage = book.getBookImage();
try {
byte[] bytes = bookImage.getBytes();
String name = book.getId() + ".png";
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("src/main/resources/static/image/book/" + name)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
So far I have done this below but my result shows I have two different instance of the object save , that is the book I save and expect is not the book I am getting .
#Test
public void addBookClicked() throws Exception {
Book book1 = new Book();
// when(bookService.save(anyObject())).thenReturn(anyObject());
mockMvc.perform(post("/book/add").with(user("admin").password("admin").roles("USER", "ADMIN"))
.accept(MediaType.TEXT_HTML)
.contentType(MediaType.TEXT_HTML))
.andExpect(status().is3xxRedirection()).andDo(print())
.andExpect(view().name("redirect:bookList"))
.andReturn();
Mockito.verify(bookService).save(book1);
}
And what can I do with the try and catch block in the test because it also gives an error in test Null pointer - may be because I am not testing or adding image to the test .
error log
MockHttpServletResponse:
Status = 302
Error message = null
Argument(s) are different! Wanted:
com.valentine.service.BookService#0 bean.save(
com.valentine.domain.Book#4acc5dff
);
-> at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
Actual invocation has different arguments:
com.valentine.service.BookService#0 bean.save(
com.valentine.domain.Book#10c72a6f
);
-> at com.valentine.adminportal.controller.BookController.addBookPost(BookController.java:50)
Comparison Failure: <Click to see difference>
Argument(s) are different! Wanted:
com.valentine.service.BookService#0 bean.save(
com.valentine.domain.Book#4acc5dff
);
-> at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
Actual invocation has different arguments:
com.valentine.service.BookService#0 bean.save(
com.valentine.domain.Book#10c72a6f
);
-> at com.valentine.adminportal.controller.BookController.addBookPost(BookController.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.valentine.adminportal.controller.BookControllerTest.addBookClicked(BookControllerTest.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springf
In addBookClicked you are not actually posting book1 to your controller. The book1 instance in that test method is only referenced (1) where it is created and (2) where it is verified.
You must pass the serialised form of book1 in the body of the mockMvc.perform() invocation.
Here's an example:
mockMvc.perform(post("/book/add")
.with(user("admin").password("admin").roles("USER", "ADMIN"))
.accept(MediaType.TEXT_HTML)
.content(objectMapper.writeValueAsString(book1))
.contentType(MediaType.TEXT_HTML))
.andExpect(status().is3xxRedirection()).andDo(print())
.andExpect(view().name("redirect:bookList"))
.andReturn();
The objectMapper in this example is an instance of Jackson's ObjectMapper and its responsibility is to serialise the book1 instance to JSON for inclusion in the request body.

HTTP Status 500 - Request processing failed; nested exception

Controller:
#RequestMapping(value="/balance.html",method=RequestMethod.GET)
public ModelAndView balance_navigation(#ModelAttribute("command") NetBean netBean,BindingResult result){
System.out.println("controller balance");
//int bal= netservice.displaybalance(cid);
Map<String, Object> model = new HashMap<String, Object>();
System.out.println("controller Map object balance");
model.put("balance", netservice.displaybalance(cid));
System.out.println("controller put() balance");
return new ModelAndView("balance", model);
Dao:
`#Override
public int displaybalance(int cid) {
Session session=sessionFactory.openSession();
System.out.println("query before executed in balance");
Query query=session.createQuery("select accbal from Account as se where se.cid=cid");
////select ACCBAL from Account a join Customer s on a.cid=s.cid where s.cid=cid
System.out.println("query executed in balance");
query.setParameter(0,cid);
return (int) query.list().get(0);`
**org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public org.springframework.web.servlet.ModelAndView com.controller.Netcontroller.balance_navigation(com.bean.NetBean,org.springframework.validation.BindingResult)]; nested exception is java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.IdentNode
**
replace your #ModelAttribute("command") to #ModelAttribute("netBean")
same thing jsp also ModelAttribute="netBean"

Response Error 500 in Spring (HttpStatus field null pointer)

I have build a rest web service using spring. I am getting 500 server error when the service is called.
Controller class :
#RequestMapping(value = "/wordlist", method = RequestMethod.GET)
public ResponseEntity getList(#RequestHeader("wordid") int wordId) {
ResponseList responseObejct = wordService.getList(wordId);
return ResponseEntity.status(responseObejct.getStatusCode()).body(responseObejct.getResponseWordList());
}
DaoImplementation :
String listHql = "from Word where wordId > ? or wordId = ?";
Query query = session.createQuery(listHql);
query.setParameter(0, wordId);
query.setParameter(1, wordId);
query.setMaxResults(30);
if(query.list().size()>0){
response.setStatusCode(HttpStatus.OK);
response.setResponseWordList((ArrayList<Word>)query.list());
} else {
response.setStatusCode(HttpStatus.NOT_FOUND);
}
session.getTransaction().commit();
ResponseList.java (for response)
public class ResponseList {
private ArrayList<Word> responseWordList;
private HttpStatus statusCode ;
public ArrayList<Word> getResponseWordList() {
return responseWordList;
}
public void setResponseWordList(ArrayList<Word> responseWordList) {
this.responseWordList = responseWordList;
}
public HttpStatus getStatusCode() {
return statusCode;
}
public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}
}
Error is:
ava.lang.IllegalArgumentException: Can not set final org.springframework.http.HttpStatus field
org.springframework.http.ResponseEntity.statusCode to java.util.ArrayList
sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
sun.reflect.UnsafeQualifiedObjectFieldAccessorImpl.get(UnsafeQualifiedObjectFieldAccessorImpl.java:38)
java.lang.reflect.Field.get(Field.java:393)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:86)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.Gson.toJson(Gson.java:586)
com.google.gson.Gson.toJson(Gson.java:565)
org.springframework.http.converter.json.GsonHttpMessageConverter.writeInternal(GsonHttpMessageConverter.java:199)
org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:222)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:183)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
I cannot understand why the error is coming. Please help.
The way you are calling ResponseEntity.status() is not valid.
It says
The method status(HttpStatus) is undefined for the type
ResponseEntity
To fix this try returning a ResponseEntity from your controller method like :
#RequestMapping(value = "/wordlist", method = RequestMethod.GET)
public ResponseEntity<ResponseList> getList(#RequestHeader("wordid") int wordId) {
ResponseList responseObejct = wordService.getList(wordId);
ResponseEntity<ResponseList> responseEntity = new ResponseEntity<>(responseObejct, HttpStatus.OK);
return responseEntity;
}
I ran into the same issue, and it turned out that this was fixed in Spring 4.3.1.
However, I cannot find a JIRA issue for that. Maybe it is a side-effect on another fix.
If you still have the problem (or if anyone else steps into this), please try again with 4.3.1 or higher.

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException

I am working on a Spring MVC application and have an issue with the validation. I need to create an user and it is a 2 step process(meaning 2 jsps with the same controller). The jsps have 2 different commandNames. So when I created the validator for the first model and initialize it, the first page loads fine. For testing, I am not using an if condition, but forwarding to next page. I get an error as the controller tries to load the validator with the current commandName object and it fails.
When I enter the url http://ip:port/data, the page loads as there is no validation, it is just initial load
When I try to submit the page without entering the firstName and submit, the method #RequestMapping(value = "/user") is called and the the next page 2 is supposed to be loaded. But the page 2 fails.
binder.getTarget() prints UserData the first time which is right
binder.getTarget() prints userinfo the 2nd time, when the next page is loading and it fails with the error
StackTrace:
HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [.validator.UserDataValidator#4366febc]: .model.UserInfo#4e3a061b
type Exception report
message Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [.validator.UserDataValidator#4366febc]: .model.UserInfo#4e3a061b
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [.validator.UserDataValidator#4366febc]: .model.UserInfo#4e3a061b
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
java.lang.IllegalStateException: Invalid target for Validator [.validator.UserDataValidator#4366febc]: .model.UserInfo#4e3a061b
org.springframework.validation.DataBinder.assertValidators(DataBinder.java:516)
org.springframework.validation.DataBinder.setValidator(DataBinder.java:507)
.controller.AccountDataController.initBinder(AccountDataController.java:65)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:62)
org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:53)
org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:251)
Any suggestions on how to handle this would be helpful. Is there a way to make this work - having 2 different commandNames and trying to validate using one controller or do I need to update the commandName to one object and that object has all the classes inside it.
e.g.
class Parent{
UserData UserData;
UserInfo userInfo;
getter & setter
}
My Controller:
#Controller
#SessionAttributes("userData")
public class AController {
#Autowired
#Qualifier("userDataValidator")
private Validator validator;
#InitBinder
private void initBinder(WebDataBinder binder) {
System.out.println("getTarget: "+binder.getTarget()); ------------
binder.setValidator(validator);
}
#RequestMapping(value = "/data", method = RequestMethod.GET)
public String initForm(Model model){
UserData userData = new UserData();
model.addAttribute("userData", userData);
return "page1";
}//
#RequestMapping(value = "/user", method=RequestMethod.POST )
public String details(Model model, #Validated UserData userData, BindingResult result) {
*****
model.addAttribute("userinfo", userinfo);
return "page2";
}//
**EDIT**
#RequestMapping(value = "/create", method=RequestMethod.POST )
*****************
public String create(Model model, Userinfo userinfo, UserData userData) {
*********************user creation
}
**EDIT**
}
My JSPs
page1.jsp
<form:form method="POST" action="user" commandName="userData">
<form:label path="firstName"><b>Name</b></form:label> <br />
<form:input class="formLabel" path="firstName" />
****
</form>
page2.jsp
<form:form method="POST" action="create" commandName="userinfo">
***********fields
</form>
My validator
public class UserDataValidator implements Validator{
public boolean supports(Class<?> paramClass) {
return UserData.class.equals(paramClass);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "valid.firstName");
}
}
My Model
UserData.java
public class UserData {
String firstName;
getter & setter for firstName
}
Let me know if any more details are needed. Thanks.

Resources