I am new to STRUTS and am trying to work out simple example . When I execute the example I get the following error on the internet browser..
<< javax.servlet.ServletException: javax.servlet.jsp.JspException: Exception creating bean of class com.example.LoginForm >>
and in the Eclipse console see a similar error with additional line on Null pointer exception
<< SEVERE: Error creating form bean of class com.example.LoginForm
java.lang.NullPointerException >>
Listed below is part of my struts-config.xml
struts-config.xml - Extract
<struts-config>
< form-beans>
< form-bean name="loginRequest" type="com.example.LoginForm" />
</form-bean>
< /form-beans>
< !-- =========================================== Global Forward Definitions -->
< global-forwards>
< forward
name="welcome"
path="/Welcome.do"/>
< /global-forwards>
< !-- =========================================== Action Mapping Definitions -->
< action-mappings>
< action path="/login"
name="loginRequest"
type="com.example.LoginAction">
< forward name="success"
path="/success.jsp">
< /forward>
< forward name="failure"
path="/login.jsp">
< /forward>
</action>
<action path="/Welcome"
forward="/pages/Welcome.jsp"/>
< /action-mappings>
< !-- ======================================== Message Resources Definitions -->
< message-resources parameter="MessageResources" />
< /struts-config>
My JSP login.jsp
< %# taglib prefix="bean" uri="/WEB-INF/struts-bean.tld" %>
< %# taglib prefix="html" uri="/WEB-INF/struts-html.tld" %>
< bean:message key="title" />
< html:form action="login">
<bean:message key="login.username"/>
<html:text property="username"></html:text>
<br>
<bean:message key="login.password"/>
<html:text property="password"></html:text>
<br>
<html:submit>
<bean:message key="login.submit"/>
</html:submit>
< /html:form>
The LoginForm class
package com.example;
import org.apache.struts.action.ActionForm;
public class LoginForm extends ActionForm
{
private String username;
private String password;
public LoginForm()
{
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
The LoginAction class
package com.example;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends Action
{
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
LoginForm login = (LoginForm)form;
String name = login.getUsername();
String pass = login.getPassword();
if(name.equals("hello") && pass.equals("hello"))
return mapping.findForward("success");
else
return mapping.findForward("failure");
}
}
The MessageResources.properties class
title=Welcome
login.username=Username
loguin.password=Password
login.submit=Submit
Stack Trace
org.apache.struts.util.RequestUtils createActionForm
SEVERE: Error creating form bean of class com.example.LoginForm
java.lang.NullPointerException
=========== ======================
at org.apache.struts.config.FormBeanConfig.createActionForm(FormBeanConfig.java:289)
at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:259)
at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:213)
at org.apache.struts.taglib.html.FormTag.initFormBean(FormTag.java:526)
at org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:503)
at org.apache.jsp.login_jsp._jspx_meth_html_005fform_005f0(login_jsp.java:122)
at org.apache.jsp.login_jsp._jspService(login_jsp.java:79)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Jun 23, 2011 12:56:47 PM org.apache.struts.util.PropertyMessageResources loadLocale
WARNING: Resource org/apache/struts/taglib/html/LocalStrings_en_US.properties Not Found.
Jun 23, 2011 12:56:47 PM org.apache.struts.util.PropertyMessageResources loadLocale
WARNING: Resource org/apache/struts/taglib/html/LocalStrings_en.properties Not Found.
Jun 23, 2011 12:56:47 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception <br/><br/>
javax.servlet.jsp.JspException: Exception creating bean of class com.example.LoginForm under form name loginRequest
at org.apache.struts.taglib.html.FormTag.initFormBean(FormTag.java:536)
at org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:503)
at org.apache.jsp.login_jsp._jspx_meth_html_005fform_005f0(login_jsp.java:122)
at org.apache.jsp.login_jsp._jspService(login_jsp.java:79)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Can anyone figure out what I am doing wrong and why this error is occuring.
Thanks,
Ankit
You forgot a / in your action on html:form.
This is how you should call your action in the form.
<html:form action="/login">
Update, Make sure you clean all your XML documents including your JSP's
The following (examples) were not allowed in the XML validator:
< form-beans>
< /struts-config>
XML doesn't allow spaces inside the <></>, </> tags. This also applies to the tags too.
Update, I found the correct problem. It's your declaration for form beans in your struts-config.xml.
You have:
<form-beans>
<form-bean name="loginRequest" type="com.example.LoginForm" />
</form-bean>
</form-beans>
You're closing your <form-bean> twice.
Solution:
< form-beans>
<form-bean name="loginRequest" type="com.example.LoginForm" />
</form-beans>
Now, this must work. :-) (Sorry for the late reply, work demands me.)
Also, I suggest using an IDE such as Eclipse or NetBeans to do your Struts project (and not do this by hand-typing) especially for your XML declarations.
Check Your jsp.Its using login as action form instead of LoginForm.
Well that error is because of you have not configure you Struts-config.xml properly.
you have to give particular Form-Bean name when action of the Form is called Accordingly.
now look at you code you have give action like this.
< action path="/login" name="loginRequest" type="com.example.LoginAction">
< forward name="success" path="/success.jsp">< /forward>
but while u are calling POJO also together but you have to call that bean before you make POST action for putting any data into the user interaction.
so make one new action which can call bean class before you main action is called.
for example:
< action path="/loginPre" name="loginRequest" forward="/youloginformname.jsp">
</action>
that way problem will get solved.
Related
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.
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" />
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.
Hi can someone please help why this is giving an error when trying to display the values in a JSP page. I don't have any number been converted or String been converted to Number, however I get NumberFormatException
my Servlet getting the request to display a user record
if(action.equalsIgnoreCase("update")){
System.out.println("Came into Update");
userId=(int) Integer.parseInt(request.getParameter("userid"));
nbId=request.getParameter("nbId").trim();
System.out.println("User iD and NBid: "+ userId + nbId);
User user=new User();
user.setUser_id(userId);
user.setUser_nbk(nbId);
List userRecords=UserDAO.getUserRecord(user);
request.setAttribute("userRecords", userRecords);
List owningOrg=Owning_Org_DB.getOwningOrgRecords();
request.setAttribute("owningOrg", owningOrg);
request.getRequestDispatcher("WEB-INF/JSP/TableMaintenance/UserNewAdd.jsp").forward(request, response);
POJO:
#Entity
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User {
#Id
private int user_id;
private String user_first_name;
private String user_middle_name;
private String user_last_name;
//getters and setters methos
}
DAO:
public static List getUserRecord(User obj){
Logger lo=LoggerFactory.getLogger("UserDAO.getUserRecord");
Session session= Annotationsessionfactory.getAnnotationSession();
Transaction tx=session.beginTransaction();
lo.debug("Request for A user Record");
//List<User> recList=new ArrayList<User>();
List recList=null;
try{
//String userRecord="from User";
Criteria userList=session.createCriteria(User.class)
.add(Restrictions.eq("user_nbk", obj.getUser_nbk()))
.add(Restrictions.eq("user_id", obj.getUser_id()));
recList=userList.list();
System.out.println(recList.size());
}catch (Exception e){
lo.info("Exception Occured in UserDAO.getUserRecord");
lo.debug("Exception Occured in UserDAO.getUserRecord:"+e);
tx.rollback();
}finally{
session.close();
lo.info("Session Closed in UserDAO.userRecordslist finally block: ");
}
lo.debug("Record was sent to the requesting servlet or method: "+ recList);
return recList;
}
JSP Page
<table>
<tr>
<td>First Name</td>
<td><input type="text" id="firstname" name="firstname" maxlength="80" value="">${userRecords.user_first_name}</td>
</tr>
<tr>
<td>Middle Name</td>
<td><input type="text" id="middlename" name="middlename" maxlength="80" value="${userRecords.user_middle_name}"></td>
.......
Exception I get:
SEVERE: Servlet.service() for servlet jsp threw exception
**java.lang.NumberFormatException: For input string: "user_first_name"**
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at javax.el.ListELResolver.coerce(ListELResolver.java:166)
at javax.el.ListELResolver.getValue(ListELResolver.java:51)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.el.parser.AstValue.getValue(AstValue.java:123)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:938)
at org.apache.jsp.WEB_002dINF.JSP.TableMaintenance.UserNewAdd_jsp._jspService (UserNewAdd_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at com.servicedbUpdate.UserUpdateDB_NewAdds.doPost(UserUpdateDB_NewAdds.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:600)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1703)
at java.lang.Thread.run(Thread.java:619)
Feb 13, 2013 10:30:49 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet UserUpdateDB_NewAdds threw exception
**java.lang.NumberFormatException: For input string: "user_first_name"**
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at javax.el.ListELResolver.coerce(ListELResolver.java:166)
at javax.el.ListELResolver.getValue(ListELResolver.java:51)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at org.apache.el.parser.AstValue.getValue(AstValue.java:123)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:938)
at org.apache.jsp.WEB_002dINF.JSP.TableMaintenance.UserNewAdd_jsp._jspService(UserNewAdd_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at com.servicedbUpdate.UserUpdateDB_NewAdds.doPost(UserUpdateDB_NewAdds.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:600)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1703)
at java.lang.Thread.run(Thread.java:619)
The ${userRecords} here
${userRecords.user_first_name}
${userRecords.user_middle_name}
is a List<User>, however you're attempting to access it as if it's a single User. This is not valid. In EL, a List can only be accessed with an integer index, indicating the position of the list item you'd like to access, like so
${userRecords[0].user_first_name}
${userRecords[0].user_middle_name}
The exception is also basically telling that it expected an integer value instead of a string value. If you look closer at the stack trace, you'll see that a ListELResolver is involved.
However, your concrete problem is bigger. You should actually be iterating over the list. Use the JSTL <c:forEach> for that. E.g. (simplified from your odd code snippet):
<table>
<c:forEach items="${userRecords}" var="user">
<tr>
<td>${user.user_first_name}</td>
<td>${user.user_middle_name}</td>
</tr>
</c:forEach>
</table>
(note: keep the XSS attack hole in mind if you really intend to redisplay them as input values)
By the way, I'd work on your Java code conventions. Those underscores are really not Java-ish.
I'm creating an web application, using JSF (2.0).
It has "ViewProducts.xhtml" to view Product with page. Each time this page loaded, if parameter has some thing (Eg: page=1 (ViewProduct.xhtml?page=1)), it's will automatically set the id to setPage property in that Bean.
But, i'm keeping getting this error:
Unable to create managed bean categories. The following problems were found: - Bean or property class bean.Categories for managed bean categories cannot be found.
Here is my code (Categories act like a product container):
faces-config.xml:
<faces-config version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<navigation-rule>
<from-view-id>/template/header.xhtml</from-view-id>
<navigation-case>
<from-outcome>ViewCategories</from-outcome>
<to-view-id>/ViewCategories.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>categories</managed-bean-name>
<managed-bean-class>bean.Categories</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
</managed-bean>
ViewProducts.xhtml
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
<f:metadata>
<f:viewParam name="page" value="#{categories.page}"/>
</f:metadata>
<h:dataTable value="#{categories.listProduct}" var="cus">
<h:column>
<f:facet name="header">Name</f:facet>
<h:outputText value ="#{cus.name}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:outputText value ="#{cus.price}"></h:outputText>
</h:column>
</h:dataTable>
Categories.java (ManagedBean)
public class Categories implements Serializable {
/** Creates a new instance of categories */
public Categories() {
}
private int page = 0;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Product> listProduct = null;
public List<Product> getListProduct() {
if (listProduct != null) {
return listProduct;
} else {
listProduct = dataAccess.DataAccess.getCategories(this.page);
return listProduct;
}
}
public void setListProduct(List<Product> listProduct) {
this.listProduct = listProduct;
}
}
Stack trace:
com.sun.faces.mgbean.ManagedBeanCreationException: Unable to create managed bean categories. The following problems were found:
- Bean or property class bean.Categories for managed bean categories cannot be found.
- Bean or property class bean.Categories for managed bean categories cannot be found.
- Bean or property class bean.Categories for managed bean categories cannot be found.
- Bean or property class bean.Categories for managed bean categories cannot be found.
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:263)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:86)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:69)
at org.apache.el.parser.AstValue.getValue(AstValue.java:112)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:554)
at javax.faces.component.UIData.getDataModel(UIData.java:1248)
at javax.faces.component.UIData.setRowIndex(UIData.java:447)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823)
at javax.faces.component.UIData.encodeBegin(UIData.java:937)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1611)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
There are at least 3 problems:
The bean class bean.Categories is not in the classpath.
You cannot have a managed property which is of a narrower scope than the managed bean.
You're duplicating the managed property with <f:viewParam>.
Ensure that the bean class is in the classpath and that you didn't typo'ed the managed bean class. You also need to get rid of the <managed-property>, you don't need it if you're already using <f:viewParam>.
Not related to the problem, but as you're already on JSF2, I'd also suggest to use annotations instead of the faces-config.xml.