ContextNotActiveException with CDI - java

I am trying to set up CDI (for #ConversationScoped) within an app using JSF/Primefaces and deployed on Jetty. I am receiving this exception with (what I believe is) a very basic ConversationScoped bean. Have combed through all relevant search results I can find and come up with nothing, so will appreciate any advice.
#Named
#ConversationScoped
public class RegisterBean implements Serializable {
...
private #Inject Conversation conversation;
...
public String doSubmitBasicInfo() {
conversation.begin();
if(accountType == null)
return null;
if(accountType.equals("seller_account"))
return "register_seller_1?faces-redirect=true";
else if(accountType.equals("buyer_account"))
return "register_buyer_1?faces-redirect=true";
return null;
}
...
The relevant portion of the JSF page is:
<div style="text-align:center;" class="noBorder autoMargin">
<p:commandButton type="submit" action="#{registerBean.doSubmitBasicInfo}" ajax="false" value="Submit" styleClass="autoMargin"></p:commandButton>
</div>
The exception is:
javax.enterprise.context.ContextNotActiveException: Conversation Context not active when method called on conversation Conversation with id: 1
at org.jboss.weld.context.conversation.ConversationImpl.verifyConversationContextActive(ConversationImpl.java:197)
at org.jboss.weld.context.conversation.ConversationImpl.getLastUsed(ConversationImpl.java:154)
at org.jboss.weld.context.AbstractConversationContext.isExpired(AbstractConversationContext.java:337)
at org.jboss.weld.context.AbstractConversationContext.invalidate(AbstractConversationContext.java:285)
at org.jboss.weld.jsf.WeldPhaseListener.deactivateConversations(WeldPhaseListener.java:146)
at org.jboss.weld.jsf.WeldPhaseListener.afterPhase(WeldPhaseListener.java:91)
at com.sun.faces.lifecycle.Phase.handleAfterPhase(Phase.java:189)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:107)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:598)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:486)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:350)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:630)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:606)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:46)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:603)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:538)
at java.lang.Thread.run(Thread.java:722)

Related

If else ladder in Spring and Hibernate using JSP

I'm trying to implement the filter in two fields i.e. category and itemBrand by using Spring, Hibernate and JSP. The scenario is if I pass category then it will return the records of that category or if I pass the itemBrand the it will return the records of that itemBrand and if I pass both category and itemBrand then it will return the records in combination of both and if I pass nothing that means both the fields (category and itemBrand) are empty the it will return all the record from that table.
But I'm getting the below while implementing it.
Can anyone help me out for this ?
Type Exception Report
Message Request processing failed; nested exception is java.lang.IllegalArgumentException: Unknown parameter name : category
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unknown parameter name : category
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.IllegalArgumentException: Unknown parameter name : category
org.hibernate.query.internal.QueryParameterBindingsImpl.getBinding(QueryParameterBindingsImpl.java:208)
org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:486)
org.hibernate.query.internal.AbstractProducedQuery.setParameter(AbstractProducedQuery.java:104)
grocery.stock.managment.dao.AdminDaoImpl.searchByCategory(AdminDaoImpl.java:148)
grocery.stock.managment.services.AdminServiceImpl.searchByCategory(AdminServiceImpl.java:125)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
com.sun.proxy.$Proxy75.searchByCategory(Unknown Source)
grocery.stock.managment.controller.MainController.itemFilter(MainController.java:238)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:901)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Below is the form
<form class="mg-b-20" action="itemFilter" method="post">
<div class="row gutters-8">
<div class="col-3-xxxl col-xl-3 col-lg-4 col-12 form-group">
<input type="text" placeholder="Search by Category"
name="category" class="form-control">
</div>
<div class="col-3-xxxl col-xl-3 col-lg-4 col-12 form-group">
<input type="text" placeholder="Search by Brand" name="itemBrand"
class="form-control">
</div>
<div class="col-1-xxxl col-xl-2 col-lg-3 col-12 form-group">
<button type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
Below is the Main Controller's code
#PostMapping("itemFilter")
public ModelAndView itemFilter(#RequestParam("category") String category,
#RequestParam("itemBrand") String itemBrand) {
ModelAndView modelAndView = new ModelAndView("allitems");
if (itemBrand == "") {
List<Item> items = adminService.searchByCategory(category);
modelAndView.addObject("items", items);
} else if (category == "") {
List<Item> items = adminService.searchByItemBrand(itemBrand);
modelAndView.addObject("items", items);
} else if (category == "" || category == null && itemBrand == "" || itemBrand == null) {
List<Item> items = adminService.getAllItems();
modelAndView.addObject("items", items);
} else {
List<Item> items = adminService.searchByCategoryAndItemBrand(category, itemBrand);
modelAndView.addObject("items", items);
}
return modelAndView;
}
Don't use those constructs and especially not in a controller (it belongs in the service). Instead, create a single service method that dynamically creates a query (or Criteria API) based on those parameters.
#Service
#Transactional
public class AdminService {
#PersistenceContext
private EntityManager em;
public List<Item> search(String category, String itemBrand) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<item> cq = cb.createQuery(Item.class);
Root<Item> c = cq.from(Item.class);
List<Predicate> predicates = new ArrayList<>();
if (StringUtils.hasText(category) {
predicates.add(cb.equals(c.get("category", category)));
}
if (StringUtils.hasText(itemBrand) {
predicates.add(cb.equals(c.get("itemBrand", itemBrand)));
}
cq = cq.where(predicates.toArray(new Predicate[0]{});
return em.getCriteriaQuery(cq).getResultLlist();
}
}
Something along these lines will do the trick (from the top of my head, so it might need some work). Adding an additional criteria is now a simple matter of checking for a value and add it to the list.
When generating a JPA metamodel you could even make it less error-prone by replacing the c.get("category") etc. with safer constructs.

Java Play 2.3.8: DataSource user is null? bindFromRequest() does not work properly

I started learning Play this week. Now I am trying to write a Code that creates a session, when a user logs in.
Sorry, but the post looks a bit messy because I am new user, who is not allowed to post pictures.
I am using Java play 2.3.8 and eclipse 4.4.1 (and I already tried the other tips i saw here)
At the moment I always get this errormessage:
play.api.Application$$anon$1: Execution exception[[RuntimeException: java.lang.reflect.InvocationTargetException]]
at play.api.Application$class.handleError(Application.scala:296) ~[play_2.11-2.3.6.jar:2.3.6]
at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.11-2.3.6.jar:2.3.6]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.6.jar:2.3.6]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.6.jar:2.3.6]
at scala.Option.map(Option.scala:145) [scala-library-2.11.1.jar:na]
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at play.data.Form.bind(Form.java:394) ~[play-java_2.11-2.3.6.jar:2.3.6]
at play.data.Form.bindFromRequest(Form.java:221) ~[play-java_2.11-2.3.6.jar:2.3.6]
at controllers.Application.authenticate(Application.java:70) ~[classes/:na]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$11$$anonfun$apply$11.apply(routes_routing.scala:209) ~[classes/:na]
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$11$$anonfun$apply$11.apply(routes_routing.scala:209) ~[classes/:na]
Caused by: java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_31]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_31]
at play.data.Form.bind(Form.java:391) ~[play-java_2.11-2.3.6.jar:2.3.6]
Caused by: java.lang.RuntimeException: DataSource user is null?
at com.avaje.ebeaninternal.server.lib.sql.DataSourcePool.(DataSourcePool.java:204) ~[avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServerFactory.getDataSourceFromConfig(DefaultServerFactory.java:419) ~[avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServerFactory.setDataSource(DefaultServerFactory.java:385) ~[avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServerFactory.createServer(DefaultServerFactory.java:163) ~[avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServerFactory.createServer(DefaultServerFactory.java:125) ~[avaje-ebeanorm-3.3.4.jar:na]
This is my method, that is called:
public static Result authenticate() {
Form<Login> loginForm = Form.form(Login.class);
Login loginUser = loginForm.bindFromRequest().get();
if (!usersList.getUsers().contains(loginForm)) {
return ok(login.render("test"));
} else {
session().clear();
session("email", loginForm.get().email);
System.out.println("ich bin hier");
return redirect(routes.Application.login());
}
}
This is the model (getters and setters are there, too):
public class Login {
public Login(){
}
public String email;
public String password;
public Login(String email, String password){
this.email=email;
this.password=password;
}
public String validate() {
if (Users.authenticate(email, password) == null) {
return "Invalid user or password";
}
return null;
}
public static Finder<String,Login> find = new Finder<String,Login>(
String.class, Login.class
);
And here the scala.html document:
<div class="Login">
<br>
<br>
<br>
<br>
<h1>Login</h1>
<form action="#routes.Application.authenticate()" method="post">
<p><input type="email" name="email" placeholder="Email" value=""></p>
<p><input type="password" name="password" placeholder="Password" value=""></p>
<p class="submit"><input type="submit" name="Login" value="Login"></p>
</form>
And last but not least the error message in my browser says the exception is thrown in line 70:
[RuntimeException: java.lang.reflect.InvocationTargetException]
System.out.println("nach loginform");
68
69 //System.out.println(loginForm.bindFromRequest().toString());
70 Login loginUser = loginForm.bindFromRequest().get();
71
72 System.out.println(loginForm.toString());
73// Form loginForm = form(Login.class).bindFromRequest();
74
75 if (!usersList.getUsers().contains(loginForm)) {
thanks in advance for helping me with this issue
Are you missing something
#Entity
public class Login extends Model {
and also check if ebean.default="models.*" line is uncommented in application.conf

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

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.

Using Bean (View Scope) in JSF to show data

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.

Categories

Resources