What is correct way to make AJAX call in Spring Boot web Thymeleaf application Getting getOutputStream() has already been called for this response - ajax

I am working on Spring boot based web application and using Thymeleaf on front end. I have a requirement to make a AJAX call, POST the data and on-success display data returned from the AJAX call.
below is the AJAX call to call the Controller method
var myObject = new Object();
myObject.acctTypeValue = 22;
myObject.amtBalance = "121334";
myObject.custNo="12121";
myObject.userId="2345rest";
$.ajax({
url : '/testDocWeb/forwardToCallingSystem',
type :'POST',
data : myObject,
dataType:'html',
cache: false,
timeout: 600000,
success : function(data) {
alert('Data: '+JSON.stringify(data));
},
error : function(request,error)
{
alert("Error : "+JSON.stringify(request));
}
});
and below is the Spring MVC controller:-
#PostMapping(path="/forwardToCallingSystem")
public #ResponseBody DummuyResponse forwardToCallingSystem(#ModelAttribute DummyInput dummyInput,Model model, HttpServletRequest request) {
log.info("Inside forwardToCallingSystem method." );
DummuyResponse dummyResponse = new DummuyResponse ();
dummyResponse .setDocId("756");
dummyResponse .setReasonCode('0');
dummyResponse .setReturnCode(100);
dummyResponse .setStatusCode(200);
return dummyResponse ;
}
and below is the Model object which I am returning :-
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class DummyResponse implements Serializable {
private static final long serialVersionUID = -8191562770215698813L;
private int statusCode;
private char reasonCode;
private int returnCode;
private String docId;
}
I am not sure what is wrong but I am getting the below error on making that AJAX call:-
[ERROR]~2019-06-12-10.32.54.030CDT~~~~~~ o.a.c.c.C.[.[localhost] Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:580)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:516)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:388)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:253)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:348)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:173)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at net.rakugakibox.spring.boot.logback.access.tomcat.LogbackAccessTomcatValve.invoke(LogbackAccessTomcatValve.java:91)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: getOutputStream() has already been called for this response
I am getting issue only on making AJAX call form Thymeleaf web page for normal Spring MVC its working fine .Any help will be appreciated

In your ajax request you are using dataType:'html', But from your controller, you are returning back an Object, According to jQuery’s Ajax-Related Methods Description
// The type of data we expect back
dataType : "html"
Update your ajax request to
$.ajax({
url : '/testDocWeb/forwardToCallingSystem',
type :'POST',
data : myObject,
cache: false,
timeout: 600000,
success : function(data) {
alert('Data: ' + JSON.stringify(data));
},
error : function(request,error) {
alert("Error : " + JSON.stringify(request));
}
});
Also, this Post can be helpful.

Related

HTTP Status 500 – Internal Server Error while uploading multipart/form-data

I am getting error when i uploading 20 MB Size of csv file in Spring MVC by using CommonsMultipartResolver library. I have done following setting in Config File :
#Bean(name = "filterMultipartResolver")
public CommonsMultipartResolver multipartResolver() throws IOException {
logger.info("CommonsMultipartResolver Set!!");
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxInMemorySize(600 * 1024 * 1024);
multipartResolver.setMaxUploadSizePerFile(100*1024 * 1024);
multipartResolver.setMaxUploadSize(600 * 1024 * 1024);
return multipartResolver;
}
Controller :
#RequestMapping(value = "/FileUploadModel", method = { RequestMethod.POST, RequestMethod.GET })
public #ResponseBody String fileuploadInObjectStorage(#RequestParam(value = "jobType", required = false) String jobType,
#RequestParam(value = "scheduleRule", required = false) String scheduleRule,
#RequestParam(value = "automationRule", required = false) String automationRule,
#RequestParam(value = "importDateFormat", required = true) String importDateFormat,
#RequestParam(value = "file", required = false) MultipartFile[] multiFile1,
#RequestParam(value = "companyName2", required = true) String company,
#RequestParam(value = "className2", required = true) String className,
HttpServletRequest request,HttpSession session) throws Exception {...}
Ajax Call:
$.ajax({
url: contextPath+'/FileUploadModel',
type: "POST",
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
timeout:0,
beforeSend: function() {
$("#scheduleRuleDiv,#automationRuleDiv,#JSDateFormatDiv,#JSUploadfileDiv,#uploadGobtnDiv,#uploadFiles").hide();
$.blockUI({
fadeIn: 1000,
message:msg1
});
},
But I am not understanding what is issue. I tried to set up size and setting header also enctype="multipart/form-data", but yet not resolved.
Given below are error:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. java.net.SocketTimeoutException
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. java.net.SocketTimeoutException
org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:165)
org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:112)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Root Cause
org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. java.net.SocketTimeoutException
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:158)
org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:112)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Root Cause
org.apache.catalina.connector.ClientAbortException: java.net.SocketTimeoutException
org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:322)
org.apache.catalina.connector.InputBuffer.checkByteBufferEof(InputBuffer.java:600)
org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:340)
org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132)
java.io.FilterInputStream.read(FilterInputStream.java:133)
org.apache.commons.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:134)
org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:999)
org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:903)
java.io.InputStream.read(InputStream.java:101)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:100)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:70)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:347)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:158)
org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:112)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Root Cause
java.net.SocketTimeoutException
org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1290)
org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1207)
org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:805)
org.apache.coyote.http11.Http11InputBuffer.access$300(Http11InputBuffer.java:42)
org.apache.coyote.http11.Http11InputBuffer$SocketInputBuffer.doRead(Http11InputBuffer.java:1172)
org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:101)
org.apache.coyote.http11.Http11InputBuffer.doRead(Http11InputBuffer.java:249)
org.apache.coyote.Request.doRead(Request.java:640)
org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:317)
org.apache.catalina.connector.InputBuffer.checkByteBufferEof(InputBuffer.java:600)
org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:340)
org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132)
java.io.FilterInputStream.read(FilterInputStream.java:133)
org.apache.commons.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:134)
org.apache.commons.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:999)
org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:903)
java.io.InputStream.read(InputStream.java:101)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:100)
org.apache.commons.fileupload.util.Streams.copy(Streams.java:70)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:347)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:158)
org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:112)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/9.0.50
NOTE : same code is working fine on IBM Liberty server for 99mb file.
you can see SocketTimeOut in tomcat's error log.
maybe increasing server's connectionTimeout resolve the error.
check this Spring boot java.net.SocketTimeoutException while uploading large files

Apollo Client throwing NPE when ApolloQueryCall.enqueue is called

I am learning GraphQL Client to Server communication using JAVA. I am using Apollo-Client now. facing issue on executing query throug java client.
My GraphQL Schema:
type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
My Query Schema
query BookById($id: ID!) {
bookById(id: $id) {
name
}
}
I have generated Java Client code from Apollo Gradle Plugin.
Below is my client code:
public class Client {
private static final String BASE_URL = "https://localhost:8080/graphql";
private ApolloClient apolloClient;
private AtomicInteger result;
#Test
public void connectServer() throws InterruptedException {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
apolloClient = ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttpClient)
.build();
BookByIdQuery bookByIdQuery = new BookByIdQuery("book-1");
ApolloQueryCall<BookByIdQuery.Data> query = apolloClient
.query(bookByIdQuery);
System.out.println(bookByIdQuery.queryDocument());
query.enqueue(new CallBackImpl());
Thread.currentThread().join();
}
private class CallBackImpl extends ApolloCall.Callback<BookByIdQuery.Data> {
#Override
public void onResponse(#Nonnull Response<BookByIdQuery.Data> response) {
log.info(response.data().bookById().name());
}
#Override
public void onFailure(#Nonnull ApolloException e) {
log.info("Fail:" + e.getMessage());
}
}
}
When I ran this client program it is throwing:
Exception in thread "OkHttp Dispatcher" java.lang.NullPointerException
at Client$CallBackImpl.onFailure(Client.java:61)
at com.apollographql.apollo.ApolloCall$Callback.onNetworkError(ApolloCall.java:115)
at com.apollographql.apollo.internal.RealApolloCall$1.onFailure(RealApolloCall.java:238)
at com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor$1$1.onFailure(ApolloCacheInterceptor.java:91)
at com.apollographql.apollo.internal.interceptor.ApolloParseInterceptor$1.onFailure(ApolloParseInterceptor.java:63)
at com.apollographql.apollo.internal.interceptor.ApolloServerInterceptor$1$1.onFailure(ApolloServerInterceptor.java:89)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:148)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Server Side Error:
ava.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:414) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:294) ~[tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.14.jar:9.0.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.14.jar:9.0.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.14.jar:9.0.14]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
From insomnia client the same call is working fine on URL: https://localhost:8080/graphql:
Replaced https to http in BASE_URL.
Server was not able to understand https request.

Spring ParamsInterceptor complains about #RequestParam- BEFORE REQUEST

i'am sending ajax get request to spring mvc handler and i can pass parameter-values.
Problem is, that i became ERROR everytime:
spring.interceptor.ParamsInterceptor - BEFORE REQUEST:
org.springframework.beans.NotWritablePropertyException: Invalid
property 'fromDate' of bean class
[com.example.CallDbController]: Bean
property 'fromDate' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the
getter?
[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
My Ajax-Requst:
$.ajax({
type : "GET",
url : 'myUrl.action',
data : {
"fromDate" : start
},
success : function(msg) {
console.log('something to do...');
}
});
and my controller handler:
#Controller
#RequestMapping("/calldb/*")
public class CallDbController {
#RequestMapping(value = { "myUrl.action" }, method = RequestMethod.GET)
public #ResponseBody String[] getTimeDifference(#RequestParam("fromDate") String startDate) {
//something to do...
}
}
I'am confusing, that "fromDate" Request-Parameter from GET-Request
is being interprited as Bean-Property.
i've finde my problem. Exception has been thrown due to Implementation of some interceptor.

download Document object using spring mvc without jsp

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.

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