viewscope bean gets instantiated on every request - java

There are other questions about this but none of them solved my problem.
viewscope bean is instantiated(its constructor is called) whenever I refresh same page in browser.
here is 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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{products.list}" var="p" id="betDt1"
styleClass="tableSorter">
<h:column>
<f:facet name="header">name </f:facet>
#{p.pname}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</f:view>
</html>
viewscoped bean:
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.hibernate.Session;
import model.Product;
#ViewScoped
#ManagedBean
public class Products implements Serializable {
private List<Product> list;
private Session ss;
#SuppressWarnings("unchecked")
public Products() {
this.ss = FaceUtils.openHibernateSession();
System.out.println("products constructor called");
ss.getTransaction().begin();
list = ss.createCriteria(Product.class).list();
this.ss.getTransaction().commit();
}
public List<Product> getList() {
return list;
}
public void setList(List<Product> list) {
this.list = list;
}
public String delete(Product pro) {
FaceUtils.log.finest("delete pro.id" + pro.getId());
FaceUtils.hibernateDelete(this.ss, pro);
list.remove(pro);
return null;
}
/**
*
*/
private static final long serialVersionUID = -2018425860394584424L;
}
And web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>fazlastoks</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
index.xhtml
</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>org.omnifaces.FACES_VIEWS_SCAN_PATHS</param-name>
<param-value>/*.xhtml</param-value>
</context-param>
Any idea what may cause the problem?

Related

Spring +AngularJs + Tomcat 9.0 - 403 error when sending a PUT request

I am getting the following error when I click on 'Add To Cart'.
PUT http://localhost:8080/emusicstore/rest/cart/add/97 403 ()
viewProduct.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<div class="page-header">
<h1>Product Detail</h1>
<p class="lead">Here is the detail information of the product!</p>
</div>
<div class="container" ng-app = "cartApp">
<div class="row">
<div class="col-md-5">
<img src="<c:url value="/resources/images/${product.productId}.png" /> " alt="image"
style="width:100%"/>
</div>
<div class="col-md-5">
<h3>${product.productName}</h3>
<p>${product.productDescription}</p>
<p>
<strong>Manufacturer</strong> : ${product.productManufacturer}
</p>
<p>
<strong>Category</strong> : ${product.productCategory}
</p>
<p>
<strong>Condition</strong> : ${product.productCondition}
</p>
<h4>${product.productPrice} USD</h4>
<br>
<c:set var="role" scope="page" value="${param.role}" />
<c:set var="url" scope="page" value="/productList" />
<c:if test="${role='admin'}">
<c:set var="url" scope="page" value="/admin/productInventory" />
</c:if>
<p ng-controller="cartCtrl">
Back
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')"><span
class="glyphicon glyphicon-shopping-cart"></span>Add To Cart</a>
<span class="glyphicon glyphicon-hand-right"></span>View Cart
</p>
</div>
</div>
</div>
<script src="<c:url value="/resources/js/controller.js" /> "></script>
controller.js
var cartApp = angular.module ("cartApp", []);
cartApp.controller("cartCtrl", function ($scope, $http){
$scope.refreshCart = function (cartId) {
$http.get('/emusicstore/rest/cart/'+$scope.cartId).success(function (data) {
$scope.cart=data;
});
};
$scope.clearCart = function () {
$http.delete('/emusicstore/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));
};
$scope.initCartId = function (cartId) {
$scope.cartId = cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});
};
$scope.removeFromCart = function (productId) {
$http.put('/emusicstore/rest/cart/remove/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
});
};
});
CartController.java
package com.store.emusicstore.controller;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.store.emusicstore.dao.CartDao;
import com.store.emusicstore.dao.ProductDao;
import com.store.emusicstore.model.Cart;
import com.store.emusicstore.model.CartItem;
import com.store.emusicstore.model.Product;
#Controller
#RequestMapping("/rest/cart")
public class CartController {
#Autowired
private CartDao cartDao;
#Autowired
private ProductDao productDao;
#RequestMapping(value="/{cartId}" , method = RequestMethod.GET)
public #ResponseBody Cart read(#PathVariable(value ="cartId") String cartId){
return cartDao.read(cartId);
}
#RequestMapping(value="/{cartId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(#PathVariable(value = "cartId" ) String cartId, #RequestBody Cart cart) {
cartDao.update(cartId, cart);
}
#RequestMapping(value = "/{cartId}", method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(#PathVariable(value="cartId") String cartId) {
cartDao.delete(cartId);
}
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#RequestMapping(value="/remove/{productId}", method=RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void removeItem(#PathVariable Long productId, HttpServletRequest request) {
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
Product product = productDao.getProductById(productId);
if (product == null || cart == null) {
throw new IllegalArgumentException(new Exception());
}
cart.removeCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#ExceptionHandler(IllegalArgumentException.class)
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal request, please verify your payload")
public void handleClientErrors(Exception e){}
#ExceptionHandler(Exception.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server")
public void handleServerErrors(Exception e){}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Things I have tried inorder to resolve this but DID NOT WORK :
Set 'readonly' as false in tomcat's web.xml
Disabled csrf by adding
security:csrf disabled="true"
in root-context inside security:http tag.
Added CorsFilter
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,authorization,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
I am still not able to get rid of the 403 error when it sends the put request.
I don't know if that is the problem, but just from reading your code:
in your js:
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});};
and in your java:
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
you're java returns no data in the response, but in the js your function expects the data.
note that 403 is usually bad mapping or security issues.

javax.el.PropertyNotFoundException: Target Unreachable, identifier 'unregisteredUserPost' resolved to null

I'm trying to implement a simple guestbook.
When user clicks "Submit", the UnregisteredUserPost CDI bean is supposed to be instantiated. However, instead I get the following exception:
javax.servlet.ServletException: /guestbook.xhtml #11,57 value="#{unregisteredUserPost.name}": Target Unreachable, identifier 'unregisteredUserPost' resolved to null
I will appreaciate if you help me to find the root cause of the problem.
guestbook.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>#{msg.page_title}</title>
<link rel="stylesheet" type="text/css" href="css.css"/>
</h:head>
<h:body>
<h:form>
<h:outputText value="#{msg.your_name} "/>
<h:inputText value="#{unregisteredUserPost.name}"/>
<br/><br/>
<h:outputText value="#{msg.your_msg}"/>
<br/>
<h:inputTextarea
rows="5" cols="100" value="#{unregisteredUserPost.content}"/>
<br/><br/>
<h:commandButton
value="#{msg.submit}" action="#{unregisteredUserPost}"/>
</h:form>
</h:body>
</html>
UnregisteredUserPost.java
package learning.javaee.guestbook;
import java.time.OffsetDateTime;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class UnregisteredUserPost extends AbstractPost {
private String name;
private OffsetDateTime dateTime;
public UnregisteredUserPost() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OffsetDateTime getDateTime() {
return dateTime;
}
public void setDateTime(OffsetDateTime dateTime) {
this.dateTime = dateTime;
}
}
AbstractPost.java
package learning.javaee.guestbook;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Named;
import javax.interceptor.AroundConstruct;
import javax.interceptor.InvocationContext;
#Named
public abstract class AbstractPost implements Serializable {
private String content;
#Inject
private static Logger log;
#AroundConstruct
private void logConstruction(InvocationContext ic) {
try {
ic.proceed();
log.fine("Created " + getClass().getName());
} catch (Exception e) {
log.severe(e.toString());
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans 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/beans_1_0.xsd">
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>guestbook1</display-name>
<welcome-file-list>
<welcome-file>guestbook.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>MessagesBundle</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
Looks like you're missing bean-discovery-mode="all" in your beans.xml . CDI needs this directive to inject the bean, from your explicit archive.
Related
CDI deployment configuration

Does JAAS Works with AJAX Partial Request?

I have a sample project configured with JAAS, JSF-2 and Primefaces. Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JAASProject</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>start</param-value>
</context-param>
<context-param>
<param-name>primefaces.SUBMIT</param-name>
<param-value>partial</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/app/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>adbADRealm</realm-name>
<form-login-config>
<form-login-page>/login.xhtml</form-login-page>
<form-error-page>/login.xhtml</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>*</role-name>
</security-role>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
I have set <session-timeout> for testing purpose. The welcome file index.jsp is:
<%
response.sendRedirect("app/home.xhtml");
%>
So that when I am browsing localhost:8080/JAASProject I am navigating to the login page, but the URL remains localhost:8080/JAASProject/app/home.xhtml. I guess it is desired. In login.xhtml I have:
<!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:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Login</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel value="Username" />
<p:inputText value="#{authenticationController.username}" required="true"/>
<p:outputLabel value="Password" />
<p:password value="#{authenticationController.password}" required="true"/>
<f:facet name="footer">
<p:commandButton id="loginButton" actionListener="#{authenticationController.login}" value="Login"/>
</f:facet>
</h:panelGrid>
</h:form>
</h:body>
</html>
And the AuthenticationController is:
package com.myself.jassproject.controller;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
#ManagedBean(name = "authenticationController")
#ViewScoped
public class AuthenticationController implements Serializable{
private static final long serialVersionUID = 7083052321396088714L;
private String originalURL;
private String username;
private String password;
public AuthenticationController() {
}
#PostConstruct
public void initialize() {
ExternalContext externalContext = getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if (originalURL == null) {
originalURL = externalContext.getRequestContextPath() + "/app/home.xhtml";
}
System.out.println(originalURL);
}
public void login(ActionEvent event){
System.out.println("==");
try {
getServletRequest().login(username, password);
getExternalContext().redirect(originalURL);
} catch (Exception ex) {
ex.printStackTrace();
}
}
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;
}
private ExternalContext getExternalContext() {
return getFacesContext().getExternalContext();
}
private FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
private HttpServletRequest getServletRequest() {
return (HttpServletRequest) getExternalContext().getRequest();
}
}
The authentication is working and I am getting navigated to the home. In home I have three buttons: one Primesfaces', one JSF's (non-ajax) and one JSF's (ajax-enabled).
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Home</title>
</h:head>
<h:body>
<h:form>
<p:commandButton value="Click me (Primefaces)" actionListener="#{homeController.doSomething}"/>
<h:commandButton value="Click me (JSF)" actionListener="#{homeController.doSomething}" />
<h:commandButton value="Click me (JSF - AJAX)" actionListener="#{homeController.doSomething}">
<f:ajax execute="#form"/>
</h:commandButton>
</h:form>
</h:body>
</html>
So far everything goes well untill now. When the session timeout occur and if I click on the Primefaces's button or the ajax enabled JSF's button it does nothing, neither any exception nor the actionListener get called; that is okay; but I am excepting that I would get navigated to the login page.
I can see a POST get fired if I click on the ajax enabled buttons by Firebugging but that is it. If I click on the JSF's button (non-ajax) I am navigating to the login page but not if I click on the other two.
Does JAAS works with AJAX POST? Is it an issue of my code? Am I missing something?
My configuration is:
Server - JBoss AS 7.1
Mojara - 2.1.7
Primefaces - 3.4.2

Target Unreachable, 'null' returned null in JSF [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I want to create a simple Book Management in JSF. I am using Glashfish Server 3.1
Book Controller:
#Named(value = "bookController")
#SessionScoped
public class BookController implements Serializable {
#EJB
BookFacadeLocal bookFacade;
Book book = new Book();
private List<Book> booklist = new LinkedList<Book> ();
/** Creates a new instance of BookController */
public BookController() {
}
public Book getBook() {
if (book == null)
book = new Book();
return book;
}
public void setBook(Book book) {
this.book = book;
}
public List<Book> getBooklist() {
return booklist;
}
public void setBooklist(List<Book> booklist) {
this.booklist = booklist;
}
public String createNewBook()
{
setBook(new Book());
return "createBook";
}
public String saveNewBook()
{
bookFacade.create(book);
booklist=bookFacade.findAll();
return "listBooks";
}
public String createBookList()
{
booklist=bookFacade.findAll();
return "listBooks";
}
}
CreateBook View:
<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Create Book
<h:form id="createBook">
<h:panelGrid id="grid" columns="2" >
<h:outputLabel value="Title" for="title"></h:outputLabel>
<h:inputText id="title" value="#{bookController.book.title}"></h:inputText>
<h:outputLabel value="Price" for="price"></h:outputLabel>
<h:inputText id="price" value="#{bookController.book.price}"></h:inputText>
<h:outputLabel value="Description" for="description"></h:outputLabel>
<h:inputTextarea id="description" value="#{bookController.book.description}"></h:inputTextarea>
<h:outputLabel value="ISBN" for="isbn"></h:outputLabel>
<h:inputText id="isbn" value="#{bookController.book.isbn}"></h:inputText>
<h:outputLabel value="Pages" for="pages"></h:outputLabel>
<h:inputText id="pages" value="#{bookController.book.nbOfPage}"></h:inputText>
<h:outputLabel value="Illustration" for="illustrations"></h:outputLabel>
<h:selectBooleanCheckbox id="illustrations" value="#{bookController.book.illustrations}"> </h:selectBooleanCheckbox>
<h:panelGroup> </h:panelGroup>
<h:commandButton id="submit" value ="Save" action="#{bookController.saveNewBook}"> </h:commandButton>
</h:panelGrid>
</h:form>
</h:body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.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-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
BookController: #{bookController} --> BookController: at.em.controller.BookController#107dd383
Error:
/createBook.xhtml #13,82 value="#{bookController.book.title}": Target
Unreachable, 'null' returned null
/createBook.xhtml #13,82 value="#{bookController.book.title}": Target Unreachable, 'null' returned null
The #{bookController} is not available anywhere in the scope. This is normally the responsibility of #Named annotation. This annotation will only be scanned on webapp's startup when there's a /WEB-INF/beans.xml file present. So make sure that that file is present (it can be kept empty).
Alternatively, you can also just use the standard JSF annotations:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class BookController {
// ...
}
(note that I didn't use javax.faces.bean.SessionScoped because that's the wrong scope for a normal controller; if it was used, the same bean instance would be shared among multiple browser tabs/windows in the same session which would only lead to unintuitive webapp behaviour)

Navigation case not working in JSF

We're working on our first JSF project, and we have some problems. We are making the login functionality, and when we hit the login button, it throws:
an IllegalArgumentException - null
source
a NullPointerException -
Servlet.service() for servlet [Faces
Servlet] in context with path
[/jsf-blank] threw exception
Do you have any idea why it's not working? Please enlighten us.
Here is out User bean:
public class User
{
private long id;
private String username;
private String password;
public User()
{
}
public User(String username, String password)
{
this.username = username;
this.password = password;
}
public User(long id, String username, String password)
{
super();
this.id = id;
this.username = username;
this.password = password;
}
public String getNextPage()
{
return "failure"; //or "admin" or "client"
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public void setUsername(String username)
{
this.username = username;
}
public void setPassword(String password)
{
this.password = password;
}
}
Our login.jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<f:view>
<h:form>
Username: <h:inputText value="#{userBean.username}"></h:inputText>
<br />
Password: <h:inputText value="#{userBean.password}"></h:inputText>
<br />
<h:commandButton value="Login" action="#{userBean.getNextPage}" ></h:commandButton>
</h:form>
</f:view>
</body>
</html>
Our faces-config.xml:
<?xml version="1.0"?>
<faces-config 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"
version="2.0">
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>data_layer.model.User</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-action>#{userBean.getNextPage}</from-action>
<from-outcome>admin</from-outcome>
<to-view-id>/admin.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{userBean.getNextPage}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/failure.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{userBean.getNextPage}</from-action>
<from-outcome>client</from-outcome>
<to-view-id>/client.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Our web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<!-- <welcome-file>index.html</welcome-file> -->
</welcome-file-list>
</web-app>
And our directory structure is:
You're intermixing JSF 1.x and JSF 2.x approaches. Maybe you're reading from an outdated book/tutorial which is targeted on JSF 1.x while the IDE is autogenerating JSF 2.x stuff?
JSF 2.0 doesn't support JSP by default anymore. The legacy JSP has been succeeded by Facelets which offers far more superior templating capabilities. Although you can configure JSF 2.0 to use the vintage JSP again, I strongly recommend to not do so. Rather rewrite login.jsp to login.xhtml:
<!DOCTYPE html>
<html lang="en"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login</title>
</head>
<body>
<h:form>
Username: <h:inputText value="#{userBean.username}" />
<br />
Password: <h:inputText value="#{userBean.password}" />
<br />
<h:commandButton value="Login" action="#{userBean.getNextPage}" />
</h:form>
</body>
Unrelated to the problem, with JSF 2.0 you can also get rid of the whole faces-config.xml as you currently have. Add the following javax.faces.bean annotations to the User class:
#ManagedBean(name="userBean")
#RequestScoped
public class User {
// ...
}
With the new implicit navigation, the outcome will be by default treated as filename of the view. You've already done it fine, so you don't need those navigation rules at all.

Categories

Resources