File upload in Spring MVC gives NullPointerException - java

I have a simple JSP form as follows:
<p>Please select a file and <i>click</i> <i>Upload file</i> to upload the file to the server:</p>
<c:url value="/upload/display" var="displayUploadedFileURL" />
<form:form action="${displayUploadedFileURL}" method="post" modelAttribute="upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload file" /> <form:errors path="file" />
<input type="Reset" value="Reset">
</form:form>
Which is for a user to upload a file to the server. The controller's method is as follows:
#Controller
#RequestMapping("/upload")
public class UploadController {
#Autowired
private UploadValidator uploadValidator;
#RequestMapping(value="/display", method=RequestMethod.POST)
public String displayUploadedFile(#ModelAttribute("upload") Upload upload,
BindingResult bindingResult,
Model model) {
// Validate Upload.
uploadValidator.validate(upload, bindingResult);
if (bindingResult.hasErrors()) {
return ("view/upload/select");
}
else {
String fileName = upload.getFile().getOriginalFilename();
System.out.println("Here: " + upload.getFile().getOriginalFilename());
model.addAttribute("fileName", fileName);
return ("view/upload/display");
}
}
...
But when I select a file and use the Upload file button I get the following:
Your page request has caused a NullPointerException: error:
library.validator.UploadValidator.validate(UploadValidator.java:29)
library.controller.upload.UploadController.displayUploadedFile(UploadController.java:45)
The validator concerned is very simple:
package library.validator;
import library.model.Upload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
#Component
public class UploadValidator implements Validator {
private static final Logger logger = Logger.getLogger(UploadValidator.class);
public UploadValidator() {
}
#Override
public boolean supports(Class cls) {
return Upload.class.isAssignableFrom(cls);
}
#Override
public void validate(Object target, Errors errors) {
logger.info(UploadValidator.class.getName() + ".validate() method called.");
Upload upload = (Upload) target;
if (upload.getFile().getSize() == 0) {
errors.rejectValue("file", "file.required");
}
}
}
I have all the relevant .jar files in the application's .lib folder, and I'mincluding the following:
<bean id="uploadValidator" class="library.validator.UploadValidator" />
<!-- Spring multipartResolver. -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
In the DispatcherServlet.
The Upload object type is as follows:
import org.springframework.web.multipart.MultipartFile;
public class Upload {
private MultipartFile file;
And appropriate getter and setter.
So why is my code not working?
Stacktrace for current problem, i.e. allowing for changes to controller method in answer below, is:
org.springframework.util.Assert.notNull(Assert.java:112)
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:171)
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:89)
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:744)

Configuring the multipartResolver bean is important thing, but also you should check that your .xml config file with this bean is imported in your general applicationContext.xml, if you have some. I had same problem and this did the thing.

This has now been solved. The problem was that the following was incorrectly defined in the DispatcherServlet:
<!-- Spring multipartResolver. -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

Related

Spring MVC - File upload - Etat HTTP 500 error message

I am getting the error below when trying to upload file using spring mvc.
"Etat HTTP 500 - Request processing failed; nested exception is java.lang.NullPointerException".
It is the first time i am doing this.
I have an idea of the cause but i can't till now find the solution.
Thanks to anybody who can help.
FileModel.java
package com.model;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
FileUploadController.java
package com.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.model.FileModel;
#Controller
public class FileUploadController {
public Logger logger = Logger.getLogger(FileUploadController.class);
public FileUploadController(){
System.out.println("FileUploadController");
}
#Autowired
private ServletContext context;
#RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
System.out.println("Multipart "+multipartFile);
String uploadPath = context.getRealPath("") + File.separator + "fichiers" + File.separator;
System.out.println(uploadPath);
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
model.addAttribute("fileName", fileName);
return "success";
}
}
}
FileUpload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload</title>
</head>
<body>
<form:form action="fileUploadPage" method = "POST" modelAttribute = "fileUpload" enctype = "multipart/form-data">
Please select a file to upload : <input type = "file" name = "file" />
<input type = "submit" value = "upload" />
</form:form>
</body>
</html>
Console
GRAVE: Servlet.service() for servlet [spring] in context with path [/oracle_spring_user_test_project] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.controller.FileUploadController.fileUpload(FileUploadController.java:56)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
You are using modelAttribute = "fileUpload" in your JSP form. So you should use #ModelAttribute spring annotation as method argument in order to indicate the argument that should be retrieved from the model. This is not necessary although it is the best practice.
The fileUpload model attribute should be populated with data from your form submitted to the fileUploadPage endpoint. So try the below snippet of code:
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#ModelAttribute("fileUpload") FileModel fileUpload, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile file = fileUpload.getFile();
...
On Spring documentation you can read the official information regarding this annotation.

NullPointerException in simple fileupload form using Spring MVC

I am trying to implement simple fileupload using Spring 4.2.3 and HTML form.
I have controller class which handles whole action, simple wrapper class for file, validator and simple view with form in HTML & Thymeleaf.
Almost everything is running fine, mapping works properly and view is appearing. But when I select file from disk and press upload button I have NullPointerException. Can anyone have a look and give some tips please? I have to mention that I am novice in Spring.
Controller:
#Controller
public class FileUploadController {
private static String UPLOAD_LOCATION = "C:/Temp/";
#Autowired
FileValidator fileValidator;
#InitBinder("file")
protected void initBinderFileBucket(WebDataBinder binder) {
binder.setValidator(fileValidator);
}
#RequestMapping(value = "/upload", method = RequestMethod.GET)
public String getSingleUploadPage(ModelMap model) {
FileBucket fileModel = new FileBucket();
model.addAttribute("fileBucket", fileModel);
return "views/fileUploader";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String singleFileUpload(#Valid FileBucket file, BindingResult result, ModelMap model)
throws IOException {
if (result.hasErrors()) {
System.out.println("File Uploader validation error");
return "views/fileUploader";
} else {
System.out.println("Fetching file"); //prints out in console
MultipartFile multipartFile = file.getFile();
System.out.println(multipartFile.getName()); //NullPointer here
return "views/success";
}
}
}
File wrapper:
public class FileBucket {
private MultipartFile file;
//getters & setters + soon other stuff
}
Validator:
#Component
public class FileValidator implements Validator {
public boolean supports(Class<?> clazz) {
return FileBucket.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
FileBucket file = (FileBucket) obj;
if(file.getFile()!=null){
if (file.getFile().getSize() == 0) {
errors.rejectValue("file", "missingfile");
}
}
}
}
View:
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorator="templates/baseTemplate">
<head>
<title>Upload Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div layout:fragment="contentPanel" class="form-container">
<h1>Simple upload</h1>
<form method="POST" enctype="multipart/form-data" action="upload" >
<input type="file" name="file" /> <br />
<input type="submit" value="Upload" />
</form>
</div>
Demo
</body>
</html>
Stacktrace:
INFO: Starting ProtocolHandler ["http-bio-8080"]
Fetching file
kwi 23, 2016 12:39:36 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at web.controllers.FileUploadController.singleFileUpload(FileUploadController.java:52)
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:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
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:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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)
Okay I found out what's causing the problem.
After correcting name in #InitBinder to match argument in controller it was necessary to rename bean responsible for multipart resolving.
From:
#Bean public CommonsMultipartResolver commonsMultipartResolver() {
return new CommonsMultipartResolver();
}
To:
#Bean public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
Otherwise it doesn't work.

CXF JSONProvider marshalling causes java.lang.ClassNotFoundException: com.sun.xml.bind.marshaller.NamespacePrefixMapper

I am trying to set up a JAX-RS service with CXF that will accept and return both json and xml. Also I want the request message to be validated through JAXB with an xsd.
To achieve this I've been through a few issues but there is always another one to overcome.
So this question is about
java.lang.ClassNotFoundException: com.sun.xml.bind.marshaller.NamespacePrefixMapper
My configuration and exception that I get is shown below
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans namespaces....>
<jaxrs:server address="/">
<jaxrs:serviceBeans>
<bean class="com.ba.sysman.services.events.IncidentService"></bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean id="jaxbJSONProvider" class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
<property name="namespaceMap" ref="jsonNamespaceMap"/>
<property name="schemaHandler" ref="schemaHolder"/>
<property name="serializeAsArray" value="true"/>
<property name="produceMediaTypes" ref="jsonTypes"/>
<property name="consumeMediaTypes" ref="jsonTypes"/>
</bean>
<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
<property name="schemaHandler" ref="schemaHolder"></property>
</bean>
</jaxrs:providers>
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
</jaxrs:server>
<bean id="schemaHolder" class="org.apache.cxf.jaxrs.utils.schemas.SchemaHandler">
<property name="schemaLocations" ref="theSchemas"/>
</bean>
<util:list id="theSchemas">
<value>../../xsd/incident.xsd</value>
</util:list>
<util:map id="jsonNamespaceMap" map-class="java.util.Hashtable">
<entry key="http://www.ba.com/schema/BAserviceDeskAPI/incident" value=""/>
<entry key="http://www.ba.com/schema/BAserviceDeskAPI" value=""/>
</util:map>
<util:list id="jsonTypes">
<value>application/json</value>
<value>application/x-javascript</value>
<value>application/vnd.example-com.foo+json</value>
</util:list>
</beans>
My Service
#Path("incident")
public class IncidentService {
#POST
#Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createIncident(Incident incident,
#HeaderParam("Accept") String acceptHeader,
#HeaderParam("skip-creation") boolean skip) {
String responseType = null;
if (acceptHeader.equals(MediaType.APPLICATION_XML)) {
responseType = MediaType.APPLICATION_XML;
} else {
responseType = MediaType.APPLICATION_JSON;
}
IncidentServiceResponse response = getResponse();
return Response.ok(response).type(responseType).build();
}
}
IncidentServiceResponse
package com.ba.sysman.assyst.rest.responses;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class IncidentServiceResponse {
#XmlElement
Integer ticketId;
#XmlElement
String errorMessage;
#XmlTransient
String rawResponse;
public IncidentServiceResponse() {
// TODO Auto-generated constructor stub
}
public IncidentServiceResponse(Integer id, String rawResponse) {
this.ticketId = id;
this.rawResponse = rawResponse;
}
public Integer getTicketId(){
return ticketId;
}
public String getRawResponse() {
return rawResponse;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
pacage-info.java for IncidentServiceResponse
#XmlSchema(namespace = "http://www.ba.com/schema/BAserviceDeskAPI", elementFormDefault = XmlNsForm.QUALIFIED)
package com.ba.sysman.assyst.rest.responses;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;
The Exception
org.apache.cxf.interceptor.Fault: com/sun/xml/bind/marshaller/NamespacePrefixMapper
at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.handleWriteException(JAXRSOutInterceptor.java:363)
at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.serializeMessage(JAXRSOutInterceptor.java:266)
at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.processResponse(JAXRSOutInterceptor.java:117)
at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.handleMessage(JAXRSOutInterceptor.java:80)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.interceptor.OutgoingChainInterceptor.handleMessage(OutgoingChainInterceptor.java:83)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:243)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:197)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:206)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262)
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:745)
Caused by: java.lang.NoClassDefFoundError: com/sun/xml/bind/marshaller/NamespacePrefixMapper
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2895)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at org.apache.cxf.common.classloader.ClassLoaderUtils.loadClass(ClassLoaderUtils.java:256)
at org.apache.cxf.common.jaxb.JAXBUtils.createNamespaceWrapper(JAXBUtils.java:1024)
at org.apache.cxf.common.jaxb.JAXBUtils.setNamespaceMapper(JAXBUtils.java:559)
at org.apache.cxf.jaxrs.provider.AbstractJAXBProvider.setNamespaceMapper(AbstractJAXBProvider.java:155)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.marshal(JSONProvider.java:499)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.marshal(JSONProvider.java:611)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.writeTo(JSONProvider.java:388)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.writeMessageBody(JAXRSUtils.java:1363)
at org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor.serializeMessage(JAXRSOutInterceptor.java:244)
... 31 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.marshaller.NamespacePrefixMapper
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
... 47 more
In my request I am sending a JSON message which is getting unmarshalled and validated successfully thus I didn't include the Incident object above. But in the response, the unmarshalling of the IncidentServiceResponse is failing with the exception above.
I have spend a whole day looking for a solution but no luck. Any ideas?
I am using tomcat 7.0.42 with java 1.7.0_55 and CXF 3.0.1.
In the rt.jar of java the com.sun.xml.bind.marshaller.NamespacePrefixMapper does not exist (which the reason for the exception) but the com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper exists. Why cxf is not picking up this implementation?
Thanks
After one day of searching and despair and after posting this big question, after 5 minutes I found the solution. Hilarious!!!
I was missing this dependency in my pom
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-databinding-jaxb</artifactId>
<version>3.0.1</version>
</dependency>
Thanks anyway

using hibernate3 and struts2

Im trying to implement a struts 2 and hibernate login application following this tutorial:
Link to the tutorial
When I push login bottton I have an exeption :
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.ClassNotFoundException: org.jboss.logging.BasicLogger
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2918)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1174)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1669)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:192)
at org.aymen.slimi.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:10)
at org.aymen.slimi.util.HibernateUtil.<clinit>(HibernateUtil.java:5)
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
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)
mai 04, 2014 6:26:37 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/Test] threw exception [L''exécution du filtre (Filter) a lancé une exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class org.aymen.slimi.utilisateur.UserService
at org.aymen.slimi.utilisateur.UserAction.<init>(UserAction.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:151)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:182)
at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:171)
at com.opensymphony.xwork2.factory.DefaultActionFactory.buildAction(DefaultActionFactory.java:22)
at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:297)
at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:397)
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:194)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:552)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
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: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)
The index.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sj" uri="/struts-jquery-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Struts2 Bootstrap Plugin Showcase - <s:text name="showcase.version"/> - Client Validation</title>
<meta charset="utf-8"/>
<meta name="keywords" content="struts2, twitter, bootstrap, plugin, showcase" />
<meta name="description" content="A Showcase for the Struts2 Bootstrap Plugin" />
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<sj:head jqueryui="false"/>
<sb:head includeScripts="true" includeScriptsValidation="true"/>
<style type="text/css">
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<a class="brand" href="#" style="margin-left:-2px" >Welcome to Aymen Slimi Server</a>
<!--/.nav-collapse -->
</div>
</div>
The User.java:
package org.aymen.slimi.utilisateur;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1020834391383853442L;
private String userId;
private String password;
private String firtName;
private String lastName;
#Id
#Column(name="user_name")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name="user_password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="first_name")
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The UserService.java:
package org.aymen.slimi.utilisateur;
import java.util.ArrayList;
import java.util.List;
import org.aymen.slimi.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public class UserService extends HibernateUtil{
public boolean verifyAccess(User user) {
User userDB = this.getUser(user.getUserId());
if (userDB!=null){
if(user.getUserId().equals(userDB.getUserId()) && user.getPassword().equals(userDB.getPassword())) {
return true;
}
}
return false;
}
public User add(User user) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return user;
}
public User delete(String username) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, username);
if(null != user) {
session.delete(user);
}
session.getTransaction().commit();
return user;
}
public User getUser(String username){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
User user = null;
Query query = session
.createQuery("select * from user where username = :username");
query.setString("username", username);
user = (User) query.uniqueResult();
return user;
}
#SuppressWarnings("unchecked")
public List<User> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> user = null;
try {
user = ((List<User>)session.createQuery("from user").list());
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
if(user != null) {
return user;
}
return new ArrayList<User>();
}
}
The struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<!--constant name="struts.devMode" value="false" /-->
<!--constant name="struts.custom.i18n.resources"
value="resources" /-->
<include file="struts-login.xml"></include>
<!--include file="struts-security.xml"></include-->
<package name="default" namespace="/" extends="struts-default" >
<action name="/*">
<result>/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The struts-login.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="login" namespace="/" extends="struts-default" >
<interceptors>
<interceptor name="login" class="org.aymen.slimi.utilisateur.LoginInterceptor"></interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="login" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="login" class="org.aymen.slimi.utilisateur.UserAction" method="verifyLogin">
<result name="success">/WEB-INF/jsp/main.jsp</result>
<result name="input">/WEB-INF/jsp/index.jsp</result>
</action>
</package>
</struts>
The HibernateUtil.java:
package org.aymen.slimi.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
The list of jar:
Add the JBoss Logging jar to your classpath. If you use Maven, it will add this and any other required jars to the classpath
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
The solution was changing the HibernateUtil.java:
import org.hibernate.*;
import org.hibernate.cfg.*;
#SuppressWarnings("deprecation")
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Création de la SessionFactory à partir de hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
#SuppressWarnings("rawtypes")
public static final ThreadLocal session = new ThreadLocal();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And the jar liste is:

JSF and ManagedBean : NullPointerException [duplicate]

This question already has an answer here:
Caused by: javax.naming.NameNotFoundException - Name [Class/object] is not bound in this Context
(1 answer)
Closed 9 years ago.
I'm designing a JSF application with managed beans.
For the moment, I've only been trying to create a simple login page (username and password are hard-coded for the moment) :
<h:form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2><hr />
<input name="username" type="text" class="input-block-level" placeholder="Username" />
<input name="password" type="password" class="input-block-level" placeholder="Password" />
<h:commandButton action="#{userController.login}" class="btn btn-block btn-primary" type="submit" value="Sign in" />
</h:form>
Here is the controller (UserController.java) :
#ManagedBean(name="userController")
#ApplicationScoped
public class UserController {
#EJB
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public UserController() {
}
public void login() throws IOException {
Boolean login = userService.login("admin", "p4ssw0rd");
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
if (login == true) {
externalContext.redirect("dashboard.xhtml");
} else {
externalContext.redirect("login.xhtml");
}
}
}
And this is the UserService.java file :
#Stateless
public class UserService {
#PersistenceContext
private EntityManager em;
public static String md5(String input) {
// Removed for clarity...
}
public Boolean login(String username, String password) {
//String hash = md5(password);
return Boolean.TRUE; // As you can see, nothing can fail for the moment
}
}
When I submit the login form, a NullPointerException shows up :
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
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: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:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
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:722)
Caused by: java.lang.NullPointerException
at com.myname.myproject.managedbean.UserController.login(UserController.java:33)
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:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more
In UserController.java, if I replace this line :
Boolean login = userService.login("admin", "p4ssw0rd");
By this one :
Boolean login = true; // Or false (I've tested twice)
Everything works OK, so it seems like Java fails to find the UserService...
Thanks for your help, I'm completely lost.
Did you check putting getters and setters in your managed bean called UserController?
If you did not, even if the code compiles correctly, dependency injection would not be held correctly.
I believe that the problem is the EJB. It should be annotated #LocalBean if it is no-interface bean or implement an interface otherwise. Try something like this:
#Stateless
public class UserService implements UserServiceLocal {
#Override
public boolean login () {
//dummy implementation
return true;
}
}
where UserServiceLocal is:
#Local
public interface UserServiceLocal {
public boolean login();
}
Usage:
#ManagedBean(name="userController")
#ApplicationScoped
public class UserController {
#EJB
private UserServiceLocal userService;
public void login() {
userService.login();
}
}
Regarding your question about why it should implement an interface, please see EJB's - when to use Remote and/or local interfaces?. An EJB (enterprise java bean) can have an interface (which can be annotated with #Remote, meaning that the bean who implements it runs in a distributed environment, or annotated with #Local meaning the bean runs inside the same JVM. In contrast, a no-interface bean is a bean that does not implements any interface. Therefore, you should instruct JVM to treat it as a bean instead of a POJO (plain old java object); this can be accomplished by adding #LocalBean annotation on the class that it is supposed to be your bean /EJB.

Categories

Resources