Form my client application (AngularJS), I am uploading a file and some other data as FormData.
var formData=new FormData();
formData.append("file",file.files[0]); //files
formData.append("docData", angular.toJson($scope.docdata)); //invoice
Value of angular.toJson($scope.docdata) is like {"configuration":20,"title":"invoicedata"}
This is my HTTP post
$http({
method: 'POST',
url: uploadurl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("Error");
})
.error(function(data, status) {
alert("Error");
});
The request is getting in my Spring MVC controller and I am able to process with the file. But the other data (docData), I am not able to get.
Here is my UploadController.java
#Controller
public class UploadController {
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile file=mRequest.getFile(itr.next());
String fileName=file.getOriginalFilename();
try {
File newFile = new File("/home/myHome/file-uploaded/"+fileName);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getBytes(), newFile);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Enumeration<String> parametrs = request.getParameterNames();
while(parametrs.hasMoreElements()) {
String param=parametrs.nextElement();
System.out.println("Param : " + param);
Object object=request.getAttribute(param);
System.out.println("Param Instance" + object.getClass().getName());
}
}
}
The first part is working perfectly. (Copying file to the directory). But the second part giving me an exception. First it prints the value of param which is docData the one I send form client app in FormData. Then it throws the exception
java.lang.NullPointerException
at com.serverapp.demoapp.web.UploadController.UploadFile(UploadController.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Line 63 refers to System.out.println("Param Instance" + object.getClass().getName());
which means the object is null
How to get the values?
When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.
This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+value);
}
if (!item.isFormField())
{
//your code for getting multipart
}
}
}
Related
I'm developing a Spring-MVC project that requires uploading images by the users of the app. I'm using apache.commons, Eclipse Mars2 and Java1.8. Everytime I test the upload, eclipse console throws this:
EDIT: it seems the problem is to find the path to the project independently of the OS. At this moment we are using:
File localFile = new File(System.getProperty("user.home")+File. separator+ "workspace"+File. separator+"ProyectoSpring"+File. separator + "WebContent" + File. separator+"usr"+File. separator+imagen.getNombreImagen());
The problem is the workspace is hardcoded and the app is being developed by more people. Any way to find the path to the project? user.dir returns the eclipe path, not the project or workspace.
Original question:
java.io.FileNotFoundException: C:\Users\UserName\workspace\ApacheTomcat7\ProyectoSpring\WebContent\usr\back.jpg (El sistema no puede encontrar la ruta especificada)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at controller.ImagenController.grabarFicheroALocal(ImagenController.java:84)
at controller.ImagenController.processAddSubmit(ImagenController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Controller methods:
#RequestMapping(value="/uploadImagen" , method=RequestMethod.GET)
public String addImagen(Model model) {
model.addAttribute("imagen", new Imagen());
return "imagen/uploadImagen";
}
#RequestMapping(value="/uploadImagen", method=RequestMethod.POST)
public String processAddSubmit(#ModelAttribute("imagen") Imagen imagen,
BindingResult bindingResult) {
//if (bindingResult.hasErrors())
// return "imagen/uploadImagen";
//
try {
String aux = imagen.getFichero().getOriginalFilename();
imagen.setImageName(System.getProperty("catalina.home")+ File. separator +"ProyectoSpring"+ File. separator +"WebContent"+ File. separator +"usr"+ File. separator + aux);
grabarFicheroALocal(imagen);
} catch (Exception e) {
e.printStackTrace();
return "user/error";
}
return "redirect:../index.jsp";
}
private void grabarFicheroALocal(Imagen imagen) throws Exception {
CommonsMultipartFile uploaded = imagen.getFichero();
File localFile = new File(imagen.getImageName());
FileOutputStream os = null;
try {
os = new FileOutputStream(localFile);
os.write(uploaded.getBytes());
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
An extract from the object:
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class Imagen {
private String imageName;
private CommonsMultipartFile fichero;
public Imagen(){
super();
}
//GETTERS AND SETTERS
public CommonsMultipartFile getFichero() {
return fichero;
}
public void setFichero(CommonsMultipartFile fichero) {
this.fichero = fichero;
}
...
Of course, the image is not uploaded. In other pc with Linux (I'm using W7-64) the code works, so I suspect it may be a permissions problem, but all folders in the path have write permissions. Any ideas? Thx.
Java Controller class:
#RequestMapping(value = "/upload" , method = RequestMethod.POST , consumes="multipart/form-data")
public void upload(#RequestParam MultipartFile file1) {
System.out.println("*****"+ file1);
}
html file:
<input id="file-0a" class="file" type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
angular js:
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var fd = new FormData();
fd.append('file', file);
var resource = /upload;
$http.post(resource, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(){ }).error(function(){ });
}
And this is the error I dont understand in the server log:
INFO: Server startup in 38138 ms
Feb 14, 2015 11:45:17 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet dispatcher threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:348)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
at org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler.handleRequest(DefaultServletHttpRequestHandler.java:122)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:467)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:434)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:205)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Feb 14, 2015 11:45:17 PM org.apache.catalina.core.StandardHostValve custom
SEVERE: Exception Processing ErrorPage[errorCode=0, location=/error.html]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Cannot forward after response has been committed
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
Try the following. It is working fine for me.
HTML You should have
<input id="file-0a" class="file" type="file" file-model="myFile" name="myFile" />
<button ng-click="uploadFile()">upload me</button>
Note the name of the input.
Then in JS controller method you should have
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file",myFile.files[0]); //myFile.files[0] will take the file and append in formData since the name is myFile.
$http({
method: 'POST',
url: '/upload', // The URL to Post.
headers: {'Content-Type': undefined}, // Set the Content-Type to undefined always.
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
})
.error(function(data, status) {
});
}
Now in Your Java Controller class
#RequestMapping(value = "/upload" , method = RequestMethod.POST)
public void upload(HttpServletRequest request) {
//org.springframework.web.multipart.MultipartHttpServletRequest
MultipartHttpServletRequest mRequest;
mRequest = (MultipartHttpServletRequest) request;
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext()) {
//org.springframework.web.multipart.MultipartFile
MultipartFile mFile = mRequest.getFile(itr.next());
String fileName = mFile.getOriginalFilename();
System.out.println("*****"+ fileName);
//To copy the file to a specific location in machine.
File file = new File('path/to/new/location');
FileCopyUtils.copy(mFile.getBytes(), file); //This will copy the file to the specific location.
}
}
Hope this works for You. And do Exception Handling also.
I encounter IllegalArgumentException while sending a post request to the restful web-service.
If i comment the method for post request(getEmplByPostReqParam()) then, code works fine for get request but with getEmplByPostReqParam(), all request throws IllegalArgumentException.
Can you please help in identifying the problem.
Web service code:
#Path("/employee")
public class EmployeeInfoService {
// This method is called if TEXT_PLAIN is request
#GET
#Path("/get/{id}")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplById(#PathParam("id") String id) {
System.out.println("sayPlainTextHello");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplByGetReqParam(#QueryParam("param1") String id) {
System.out.println("getEmplByGetReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#POST
#Path("/get")
#Produces("MediaType.TEXT_PLAIN")
public String getEmplByPostReqParam(#FormParam("param1") String id) {
System.out.println("getEmplByPostReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee.toString();
}
}
I used two client to test the service:
1. Google chrome's Advance Rest client
url - http://myhost:14443/de.vogella.jersey.first/rest/employee/get
payload - [param1: 1]
method type - [post]
core java code
String url = "http://myhost:14443/de.vogella.jersey.first/rest/employee/get";
String charset = "UTF-8";
String param1 = "1";
String query = String.format("param1=%s",
URLEncoder.encode(param1, charset));
URL service = new URL(url);
URLConnection connection = service.openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = connection.getOutputStream();
try {
output.write(query.getBytes(charset));
} catch (Exception e) {
// TODO: handle exception
}
Stacktrace:
</pre></p><p><b>root cause</b> <pre>java.lang.IllegalArgumentException: java.text.ParseException: End of header
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:289)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
</pre></p><p><b>root cause</b> <pre>java.text.ParseException: End of header
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.getNextCharacter(HttpHeaderReaderImpl.java:168)
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.next(HttpHeaderReaderImpl.java:129)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:111)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:98)
com.sun.jersey.core.header.reader.HttpHeaderReader.nextSeparator(HttpHeaderReader.java:116)
com.sun.jersey.core.header.QualitySourceMediaType.valueOf(QualitySourceMediaType.java:85)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:360)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:358)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:481)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:473)
com.sun.jersey.core.header.reader.HttpHeaderReader.readAcceptableList(HttpHeaderReader.java:461)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:365)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:373)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:287)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
If you notice your annotation (#Produces) argument is passed in double quotes. remove the double quotes and it should work
#Produces("MediaType.TEXT_PLAIN")
should look like below
#Produces(MediaType.TEXT_PLAIN)
I resolved the issue by changing the getEmplByPostReqParam() as follows:
#POST
#Path("/get")
public Response getEmplByPostReqParam(#FormParam("param1") String id) {
EmployeeDAO dbHandler = new EmployeeDAOImpl();
System.out.println("getEmplByPostReqParam");
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
ResponseBuilder rb = new ResponseBuilderImpl();
rb.type(MediaType.APPLICATION_ATOM_XML);
rb.entity(fetchedEmployee);
return rb.build();
}
This is working fine for me, if there is some better approach or there is something wrong with this approach, please post a comment.
I am trying to use content - disposition to save something from server to client computer. When I click on button in jsp, dialog opens and I choose to save file. File is saved but I get this exception. I have read on other similar topics something like "Somewhere, your application is calling getOutputStream or getWriter more than once." but I don't know/understand where?
#Controller
public class ExportPhonebook2 {
#Autowired
private PhoneBookService phoneBookSer;
private void setResponseHeader(HttpServletResponse response, String imenikTXT, File file){
response.setHeader("Content-Length", "" + file.length());
response.setContentType("application/txt; charset=UTF-8");
response.setHeader("content-disposition", "attachement; filename=imenik.txt" );
response.setHeader("Content-Transfer-Encoding", "binary");
}
#RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public String exportPhonebook(Model model, HttpServletResponse response) {
List<User> listOfAllUsers = phoneBookSer.fetchAllUsers();
String imenik = "";
for (User user : listOfAllUsers) {
imenik = imenik + user.getPrezime() + " " + user.getIme() + ", Telefon: " + user.getTelefon() + ";\r\n" ;
}
try {
File file = new File("c:\\imenik.txt");
setResponseHeader(response, "imenik.txt", file);
FileInputStream fileIn;
fileIn = new FileInputStream(file);
OutputStream outTXT = response.getOutputStream();
byte[] outputByte = new byte[8192];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 8192) != -1){
outTXT.write(outputByte, 0, 8192);
}
fileIn.close();
outTXT.flush();
outTXT.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "homepage";
}
}
stacktrace:
Exception initializing page context
java.lang.IllegalStateException: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2705)
at org.apache.catalina.connector.Request.getSession(Request.java:2231)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:899)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:572)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:517)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:146)
at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:125)
at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112)
at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65)
at org.apache.jsp.WEB_002dINF.jsp.homepage_jsp._jspService(homepage_jsp.java:58)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:328)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:95)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:175)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This particular exception is caused because Spring MVC apparently needs to create a session during rendering of the view, but couldn't because the response is already committed with the file download. But your real problem is bigger, Spring MVC should not be rendering a view at all.
You need to tell Spring MVC to not render a view after having taken over the control of the HTTP response from Spring MVC. It is otherwise trying to append the rendered view to the end of the HTTP response which would only corrupt the file download.
I don't do Spring MVC, so I can't answer from top of head, but it appears that just returning void instead of String from the controller's action method should be sufficient in order to tell Spring MVC to not render a view.
java.lang.IllegalStateException: Cannot create a session after the response has been committed
Session creation requires a session cookie to be written to the HTTP header, before the body. Something is trying to create a session after you've flushed and closed your response.
Consider creating the session prior to writing the response.
I'm trying to upload some Image file to my database. When I run my code It produces the error java.lang.IndexOutOfBoundsException:. But the same code works well in another form.
My code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String uname = (String) request.getSession().getAttribute("uname");
//set content type
response.setContentType("text/html");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
if (! ServletFileUpload.isMultipartContent(request)) {
System.out.println("sorry. No file uploaded");
return;
}
// parse request
List<?> items = uploadHandler.parseRequest(request); //getting error
System.out.println(items.size());
// get uploaded file
FileItem file = (FileItem) items.get(0);
Connection con=prepareConnection();
con.setAutoCommit(false);
//Part photo=request.getPart("photo");
BufferedImage originalImage=ImageIO.read(file.getInputStream());
int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(resizeImageJpg, "png", baos);
baos.flush();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
StringBuilder sb=new StringBuilder(1024);
sb.append("insert into ").append(uname).append("PROFILEPICTURE values(?,?)");
String query = sb.toString();
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
ps.setBinaryStream(2, is);
int i=ps.executeUpdate();
con.commit();
con.close();
if(i==1)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("/sp/profile");
if(dispatcher != null) {
dispatcher.forward(request, response);
}
}
else
{
out.println("Error ocuured");
}
out.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
console output :
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at skypark.AddProfilePict.doPost(AddProfilePict.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
And my form is:
<form id="form" method="post" action="AddProfilePict" enctype="multipart/form-data">
<input type="file" accept="image/*" style="width: 450px; border:0px; background:none; margin-top:5px; width:245px;" value="">
<input class="upld" type="submit" value="Upload">
</form>
Can anyone help me figure out what is causing the error?
items should indeed be empty. You should first check it's length and then try to fetch the items using
if(! items.isEmpty()) {
FileItem file = (FileItem) items.get(0);
}
or
if(items.size() > 0) {
FileItem file = (FileItem) items.get(0);
}