NullPointerException in simple fileupload form using Spring MVC - java

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.

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.

SetViewNames, spring 4 and thymeleaf and java

I try to develop an aplication that just has to send a email with an image.
I saw some solutions that refer configuring the following property
<property name="viewNames" value="templates/*, pages/*" />
but I dont know how I have to configure in java way, thus this way doesnt works:
thymeleaf.setViewNames("templates/*"),
However, it is appearing an error message:
2015-11-01 18:30:31.481 ERROR 1003 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "error": Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
2015-11-01 18:30:31.483 ERROR 1003 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet dispatcherServlet threw exception
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:468)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:439)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:305)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:399)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
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)
2015-11-01 18:30:31.484 ERROR 1003 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:468)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:439)
This is the code:
the configuration
#Bean
public ServletContextTemplateResolver templateResolver(){
ServletContextTemplateResolver resolver=new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".html");
resolver.setCharacterEncoding("UTF-8");
resolver.setTemplateMode("HTML5");
return resolver;
}
#Bean
public ThymeleafViewResolver thymeleafView(){
ThymeleafViewResolver thymeleaf = new ThymeleafViewResolver();
thymeleaf.setTemplateEngine(templateEngine());
thymeleaf.setCharacterEncoding("UTF-8");
thymeleaf.setOrder(1);
return thymeleaf;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
return engine;
}
#Bean
public SpringResourceTemplateResolver SourceTemplateResolver(){
SpringResourceTemplateResolver sourceTemplateResolver = new SpringResourceTemplateResolver();
sourceTemplateResolver.setSuffix(".html");
sourceTemplateResolver.setTemplateMode("HTML5");
return sourceTemplateResolver;
}
The view:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:remove="all">Template for HTML email with inline image</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<p> Hello, everybody!</p>
<p> You have been successfully subscribed to the <b>Fake newsletter</b> on</p>
<p>Your hobbies are:</p>
<p> You can find <b>your inlined image</b> just below this text.</p>
<p><img src="LogoLehrer.jpg" th:src="'cid:' + ${imageResourceName}"/></p>
<p> Regards, <br/> <em>The Thymeleaf Team</em></p>
</body>
</html>
and the controller:
#RequestMapping("/sendmail")
public void sendMail(final Locale locale, HttpServletRequest request,
HttpServletResponse response,
#RequestParam("imageResourceName") final MultipartFile image)
throws MessagingException, IOException {
mailSender.send("lehrerxx#gmail.com", "prueba spring final",
"I have luck", "Lehrer", locale,request,
response, image, image.getBytes(), image.getName());
}
And the method which sends an email:
public void send(String to, String subject, String body,
String recipientName, String recipientEmail,
Locale locale,HttpServletRequest request,
HttpServletResponse response, final MultipartFile image,
final byte[] imageBytes, final String imageResourceName) throws MessagingException {
// final Context ctx = new Context(locale);
final WebContext ctx = new WebContext(request, response, servletContext, locale);
ctx.setVariable("name", recipientName);
ctx.setVariable("mail", recipientEmail);
ctx.setVariable("imageResourceName", imageResourceName);
final String htmlContent = this.templateEngine.process("email_Template", ctx);
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message,true);
helper.setSubject(subject);
helper.setTo(to);
helper.setText(htmlContent, true);
final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
helper.addInline(image.getName(), imageSource, image.getContentType());
this.javaMailSender.send(message);
}

File upload in Spring MVC gives NullPointerException

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" />

How to read properties from resource file using java

For displaying error message value in JSF page using Java when I read the name lblFathersOrGuardianName from resource mysqlmaven.properties file I got below error.
Mar 04, 2014 2:53:21 PM com.sun.faces.application.ActionListenerImpl processAction
SEVERE: java.lang.ExceptionInInitializerError
javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
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:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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)
Caused by: java.lang.ExceptionInInitializerError
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.validationRegistration(RegistrationBean.java:198)
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.submitRegistrationAction(RegistrationBean.java:189)
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.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:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
... 24 more
Caused by: java.lang.NullPointerException
at java.util.ResourceBundle$CacheKey.calculateHashCode(ResourceBundle.java:593)
at java.util.ResourceBundle$CacheKey.<init>(ResourceBundle.java:522)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1259)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:721)
at com.uk.mysqlmaven.util.ResourceKeys.<init>(ResourceKeys.java:12)
at com.uk.mysqlmaven.util.ResourceKeys.<clinit>(ResourceKeys.java:8)
... 34 more
Mar 04, 2014 2:53:21 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{registrationBean.submitRegistrationAction}: java.lang.ExceptionInInitializerError
javax.faces.FacesException: #{registrationBean.submitRegistrationAction}: java.lang.ExceptionInInitializerError
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:114)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
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:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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)
Caused by: javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
... 23 more
Caused by: java.lang.ExceptionInInitializerError
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.validationRegistration(RegistrationBean.java:198)
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.submitRegistrationAction(RegistrationBean.java:189)
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.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:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
... 24 more
Caused by: java.lang.NullPointerException
at java.util.ResourceBundle$CacheKey.calculateHashCode(ResourceBundle.java:593)
at java.util.ResourceBundle$CacheKey.<init>(ResourceBundle.java:522)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1259)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:721)
at com.uk.mysqlmaven.util.ResourceKeys.<init>(ResourceKeys.java:12)
at com.uk.mysqlmaven.util.ResourceKeys.<clinit>(ResourceKeys.java:8)
... 34 more
javax.faces.FacesException: #{registrationBean.submitRegistrationAction}: java.lang.ExceptionInInitializerError
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:85)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
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:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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)
Caused by: javax.faces.FacesException: #{registrationBean.submitRegistrationAction}: java.lang.ExceptionInInitializerError
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:114)
at javax.faces.component.UICommand.broadcast(UICommand.java:311)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
... 19 more
Caused by: javax.faces.el.EvaluationException: java.lang.ExceptionInInitializerError
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:98)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
... 23 more
Caused by: java.lang.ExceptionInInitializerError
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.validationRegistration(RegistrationBean.java:198)
at com.uk.mysqlmaven.jsf.beans.RegistrationBean.submitRegistrationAction(RegistrationBean.java:189)
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.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:102)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
... 24 more
Caused by: java.lang.NullPointerException
at java.util.ResourceBundle$CacheKey.calculateHashCode(ResourceBundle.java:593)
at java.util.ResourceBundle$CacheKey.<init>(ResourceBundle.java:522)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1259)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:721)
at com.uk.mysqlmaven.util.ResourceKeys.<init>(ResourceKeys.java:12)
at com.uk.mysqlmaven.util.ResourceKeys.<clinit>(ResourceKeys.java:8)
... 34 more
mysqlmaven.properties
#registration.xhtml
lblFirstName=First Name
lblMiddleName=Middle Name
lblLastName=Last Name
lblDateOfBirth=Date Of Birth
lblFathersOrGuardianName=Father's / Guardian Name
RegistrationBean.java
package com.uk.mysqlmaven.jsf.beans;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import com.uk.mysqlmaven.util.ResourceKeys;
public class RegistrationBean {
private String fathersOrGuardianName;
public String getFathersOrGuardianName() {
return fathersOrGuardianName;
}
public void setFathersOrGuardianName(String fathersOrGuardianName) {
this.fathersOrGuardianName = fathersOrGuardianName;
}
public String submitRegistrationAction() {
if (validationRegistration()) {
return "views/home.faces?faces-redirect=true&param=98";
} else {
return "";
}
}
public Boolean validationRegistration() {
if (this.fathersOrGuardianName.length() == 0) {
FacesContext.getCurrentInstance().addMessage(fathersOrGuardianName, new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceKeys.getInstance().get("lblFathersOrGuardianName"), "Fathers/GurdianName can't be empty."));
}
return Boolean.FALSE;
}
public void clearRegistrationAction(ActionEvent event) {
this.fathersOrGuardianName = "";
}
}
ResourceKeys.java
package com.uk.mysqlmaven.util;
import java.util.ResourceBundle;
public class ResourceKeys {
private static ResourceKeys instance = new ResourceKeys();
private final ResourceBundle resourceBundle;
private ResourceKeys() {
resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
}
/**
* Return singleton instance of this class
* #return singleton instance
*/
public synchronized static ResourceKeys getInstance() {
return instance;
}
private static String BUNDLE_NAME = "/MySqlMavenJSF/com/uk/mysqlmaven/resources/mysqlmaven";
/**
* Return value of the key
* #param key
* #return value
*/
public String get(String key) {
return resourceBundle.getString(key);
}
}
How to get name from resource file in java.
mysqlmaven.properties file is placed in my project as shown in below screenshot.
mysqlmaven.properties file path is not accessed in ResourceKeys.java file.
For accessing properties file from package in java I used below path in Constants.java.
Constants.java
package com.uk.mysqlmaven.util;
public class Constants {
public class Resources {
public static final String BUNDLENAME_MYSQLMAVEN = "com.uk.mysqlmaven.resources.mysqlmaven";
}
}
ResourceKeys.java
package com.uk.mysqlmaven.util;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
public class ResourceKeys {
private static ResourceKeys instance = new ResourceKeys();
private ResourceBundle resourceBundle;
private ResourceKeys() {
}
/**
* Return singleton instance of this class
* #return singleton instance
*/
public synchronized static ResourceKeys getInstance() {
return instance;
}
/**
* Return value of the key
* #param key
* #param bundleName
* #return value
*/
public String get(String key, String bundleName) {
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
resourceBundle = ResourceBundle.getBundle(bundleName, locale);
return resourceBundle.getString(key);
}
}
RegistrationBean.java
package com.uk.mysqlmaven.jsf.beans;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import com.uk.mysqlmaven.util.Constants;
import com.uk.mysqlmaven.util.ResourceKeys;
public class RegistrationBean {
private String fathersOrGuardianName;
public String getFathersOrGuardianName() {
return fathersOrGuardianName;
}
public void setFathersOrGuardianName(String fathersOrGuardianName) {
this.fathersOrGuardianName = fathersOrGuardianName;
}
public String submitRegistrationAction() {
if (validationRegistration()) {
return "views/home.faces?faces-redirect=true&param=98";
} else {
return "";
}
}
public Boolean validationRegistration() {
if (this.fathersOrGuardianName.length() == 0) {
String commonName = ResourceKeys.getInstance().get("lblPleaseEnter", Constants.Resources.BUNDLENAME_MYSQLMAVEN);
String displayName = ResourceKeys.getInstance().get("lblFathersOrGuardianName", Constants.Resources.BUNDLENAME_MYSQLMAVEN);
FacesContext.getCurrentInstance().addMessage(fathersOrGuardianName, new FacesMessage(FacesMessage.SEVERITY_ERROR, commonName +" "+ displayName , "Fathers/GurdianName can't be empty."));
}
return Boolean.FALSE;
}
public void clearRegistrationAction(ActionEvent event) {
this.fathersOrGuardianName = "";
}
}
Registration.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
<f:view>
<h:head>
<title>Registration</title>
<f:loadBundle var="mysqlmaven" basename="com.uk.mysqlmaven.resources.mysqlmaven" />
<h:outputStylesheet name="style/mysqlmaven.css"></h:outputStylesheet>
</h:head>
<h:form id="registrationForm">
<table align="center">
<tr>
<td><h:panelGrid>
<h:messages id="registrationMessageId" errorClass="lblRed" warnClass="lblWarning" infoClass="lblGreen"></h:messages>
<h:message for="registrationMessageId"></h:message>
</h:panelGrid> <h:panelGrid columns="1" cellpadding="2" frame="hsides" border="0">
<h:panelGrid columns="2">
<h:panelGroup>
<p:outputLabel value="*" styleClass="lblRed"></p:outputLabel>
<p:outputLabel value="#{mysqlmaven.lblFathersOrGuardianName}"></p:outputLabel>
<p:inputText id="fathersOrGuardianNameId" label="#{mysqlmaven.lblFathersOrGuardianName}" value="#{registrationBean.fathersOrGuardianName}"></p:inputText>
</h:panelGroup>
</h:panelGrid>
</h:panelGrid> <h:panelGrid columns="2">
<p:commandButton id="submitId" value="Submit" title="Submit" actionListener="#{registrationBean.submitRegistrationAction}" update="registrationMessageId"></p:commandButton>
<p:commandButton id="clearId" value="Clear" actionListener="#{registrationBean.clearRegistrationAction}"></p:commandButton>
</h:panelGrid>
</td>
</tr>
</table>
</h:form>
</f:view>
</html>

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