I'm trying to create a questionnaire website using GlassFish, JSF/Primefaces and for database, I'm using the embedded derby DB of Glassfish.
I followed this video tutorial (http://www.youtube.com/watch?v=aBjlR9HoR50) which is really good but I haven't managed to get my project to work properly.
My project deploys successfully on Glassfish but when I see the webpage on the browser, it is obvious that the backing bean is not called from the xhtml page.
Here is the backing bean code:
package ac.hw.questionnaire;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import ac.hw.questionnaire.model.Question;
/**
* Session Bean implementation class QuestionsEJB
*/
#Stateless
#LocalBean
#Named
public class QuestionsEJB {
private Logger logging = Logger.getLogger(this.getClass().getName());
#PersistenceContext (unitName="QuestionnaireEmbeddedDB")
EntityManager em;
private List<Question> questions;
private String name;
/**
* Default constructor.
*/
private EntityManager getEntityManager() {
if (em==null){
logging.info("EntityManager is null!");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("QuestionnaireEmbeddedDB");
em = emf.createEntityManager();
if (em==null){
logging.info("EntityManager is STILL null!");
}
}
return em;
}
public QuestionsEJB() {
// TODO Auto-generated constructor stub
logging.info("Logger: Constructor of QuestionsEJB called");
if (getEntityManager()==null){
return;
}
List resultList = em.createQuery("select q from Question q").getResultList();
if (resultList==null){
logging.info("ResultList is null");
}else{
logging.info("Constructor/Retrieved "+resultList.size()+" questions");
}
}
public List<Question> getQuestions() {
System.out.println("getQuestions method called");
if (questions==null){
this.questions = em.createQuery("select q from questions q").getResultList();
System.out.println("Retrieved "+questions.size()+" questions");
}
return questions;
}
public String getMyText(){
return "myTextFromEJB";
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public String getName() {
this.logging.info("Get name!");
return name;
}
public void setName(String name) {
this.logging.info("Set name!");
this.name = name;
}
}
Here is my xhtml page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="WEB-INF/template.xhtml">
<ui:define name="content">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="myText" value="MyText is:"></h:outputLabel>
<h:outputText id="myText" value="#{QuestionsEJB.myText}">
</h:outputText>
</h:panelGrid>
<h:panelGrid columns="4" cellpadding="5">
<h:outputLabel for="name" value="Name:" style="font-weight:bold" />
<p:inputText id="name" value="#{QuestionsEJB.name}" />
<p:commandButton value="Submit" update="display" />
<h:outputText value="#{QuestionsEJB.name}" id="display" />
</h:panelGrid>
<br />
<p:dataTable var="qVar" value="#{QuestionsEJB.questions}">
<h:column>#{qVar.questionText}</h:column>
</p:dataTable>
</ui:define>
</ui:composition>
</html>
When I visit the xhtml page on the browser, none of the values are displayed and the Submit button doesn't do anything which tells me that the facelet doesn't bind to the EJB.
My web.xml (inside WebContent/WEB-INF/) has the following content:
<web-app version="3.0" 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_3_0.xsd" >
<display-name>Questionnaire</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>/faces/*</url-pattern>
</servlet-mapping>
</web-app>
My beans.xml file (also inside WebContent/WEB-INF) is empty (nothing at all).
My glassfish-web.xml file (also inside WebContent/WEB-INF) has the following content:
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app>
<context-root>/QuestionnaireEmbeddedDB</context-root>
<parameter-encoding default-charset="UTF-8"/>
</glassfish-web-app>
I have no exceptions on the server.log and the only unorthodox thing is that the EntityManager is null until I explicitly call the getEntityManager() method on the QuestionEJB.
Why can't I get the xhtml to connect to the backing bean?
Also, the template.xhtml has the following content:
<!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:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title><ui:insert name="title">Questionnaire</ui:insert></title>
</h:head>
<body>
<ui:debug hotkey="x"
rendered="#{initParam['javax.faces.FACELETS_DEVELOPMENT']}" />
<div id="header">
<ui:insert name="header">
<h1>Welcome to the privacy questionnaire... (header section)</h1>
<!-- include your header file or uncomment the include below and create header.xhtml in this directory -->
<!-- <ui:include src="header.xhtml"/> -->
</ui:insert>
</div>
<h:body>
<h:form id="mainForm" enctype="multipart/form-data">
<div id="content">
<ui:insert name="content">
Content area. See comments below this line in the source.
<!-- include your content file or uncomment the include below and create content.xhtml in this directory -->
<!-- <div> -->
<!-- <ui:include src="content.xhtml"/> -->
<!-- </div> -->
</ui:insert>
</div>
</h:form>
</h:body>
<div id="footer">
<ui:insert name="footer">
<br />
<br />Powered by Glassfish & Eclipse.
<br />
<!-- include your header file or uncomment the include below and create footer.xhtml in this directory -->
<!--<ui:include src="footer.xhtml"/> -->
</ui:insert>
</div>
</body>
</html>
Related
I'm using Jakarta EE 9, Glassfish 6.0, and JSF 3.0 and getting "Target Unreachable, identifier '' resolved to null..." I know questions like this have been asked before but I tried all proposed solutions. Also, I could find very few discussions about version 3.0 of JSF. I would appreciate it if someone could help me spot what wrong is.
BookController.java
import entities.Book;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Inject;
import jakarta.inject.Named;
#Named
#RequestScoped
public class BookController{
private String test = "dada";
#Inject
private BookEJB bookEJB;
private Book book = new Book();
public String doCreateBook(){
bookEJB.createBook(book);
FacesContext.getCurrentInstance().addMessage(
null, new FacesMessage("Book created"));
return "newBook.xhtml";
}
public void doFindBookById(){
book = bookEJB.findBookById(book.getId());
}
public Book getBook() {
return book;
}
}
BookEJB.java
import entities.Book;
import jakarta.annotation.sql.DataSourceDefinition;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
#Named
#jakarta.ejb.Stateless(name = "BookEJB")
public class BookEJB {
#PersistenceContext
private EntityManager em;
public BookEJB() {
}
public Book createBook(Book book){
em.persist(book);
return book;
}
public List<Book> findAllBooks() {
return em.createNamedQuery("findAllBooks", Book.class).getResultList();
}
public Book findBookById(Long id){
return em.find(Book.class, id);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>jakarta.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>
</web-app>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="3.0" xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-facesconfig_3_0.xsd">
</faces-config>
beans.xml (in both WEB-INF and META-INF)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd"
version="3.0"
bean-discovery-mode="all">
</beans>
layout.xhtml
<?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://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title><ui:insert name="title">Default title</ui:insert></title>
<link rel="icon" href="https://i.loli.net/2021/06/12/im236Uy7FLhxCJ1.png"/>
</h:head>
<h:body>
<h:link value="Create a book" outcome="newBook.xhtml"/>
<h1><ui:insert name="title">Default title</ui:insert></h1>
<hr/>
<!-- <h:message for="errors"/>-->
<ui:insert name="content">Default content</ui:insert>
<hr/>
<h:outputText value="APress"></h:outputText>
</h:body>
</html>
newBook.xhtml
<?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://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="layout.xhtml">
<ui:define name="title">Create a new book</ui:define>
<ui:define name="content">
<h:outputText value="#{bookController.test}"/>
<h:form id="bookForm">
<h:outputLabel value="Title: "/>
<h:inputText value="#{bookController.book.title}"/>
<h:outputLabel value="Price : "/>
<h:inputText value="#{bookController.book.price}"/>
<h:commandButton value="Create a book" action="#{bookController.doCreateBook}">
<f:ajax execute="#form" render=":booklist :errors"/>
</h:commandButton>
</h:form>
<hr/>
<h1>List of Books</h1>
<h:dataTable id="booklist" value="#{bookEJB.findAllBooks()}" var="bk">
<h:column>
<f:facet name="header">
<h:outputText value="Title"/>
</f:facet>
<h:link outcome="viewBook.xhtml?id=#{bk}" value="#{bk.title}"/>
</h:column>
</h:dataTable>
</ui:define>
</ui:composition>
</html>
It is because of Application Server that cannot fully support to JSF-3.0. I've got same error when I tested jakartaee-tutorial-examples/web/jsf/guessnumber-jsf project. I've tried guessnumber-jsf.war file on WildFly 24.0.0.Final and wildfly-23.0.2.Final Application servers. I got same error on both servers. But when I tested on Wildfly-preview-23.0.2.Final which supports JakartaEE 9.1 and JDK 11, it is working well.
I have problem with the Push Technology, the project is to:
Primefaces 3.5
WebLogic 12c
Atmosphere Runtime 2.2
The configuration is:
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>cupertino</param-value>
</context-param>
<servlet>
<servlet-name>Push Servlet</servlet-name>
<servlet-class>org.primefaces.push.PushServlet</servlet-class>
</servlet>
The View:
#Named
#SessionScoped
public class FrmNotificacion implements Serializable
...
public void send() {
...
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Usuario: "+getUser(), getMensajeDetalle());
PushContext pushContext = PushContextFactory.getDefault().getPushContext();
pushContext.push("/notificacion", msg);
System.out.println("......");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
The XHTML:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" >
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Enivar Notificación</title>
</h:head>
<h:body>
<h:form id="frmPrincipal" >
<p:growl id="message" showDetail="true" />
<p:panel header="Notificación" >
<p:panelGrid columns="2" columnClasses="ui-widget-header,,ui-widget-header,,ui-widget-header,," >
<p:outputLabel id="lblNombre" value="Ingrese Usuario a Notificar:" />
<p:inputText id="txtNombre" value="#{frmNotificacion.user}" />
<p:outputLabel id="lblMensaje" value="Ingresar Mensaje Notificación" />
<p:inputTextarea id="txtMensaje" autoResize="true" value="#{frmNotificacion.mensajeDetalle}"/>
</p:panelGrid>
<p:commandButton id="btnNotifica"
value="Notifica"
update="message"
actionListener="#{frmNotificacion.send()}"
icon="ui-icon-arrowthickstop-1-e" />
</p:panel>
</h:form>
<p:socket onMessage="handleMessage" channel="/notificacion" />
<script type="text/javascript">
function handleMessage(msg) {
msg.severity = 'info';
grow.show([msg]);
}
</script>
</h:body>
</html>
But the action notify push Faces Message not working
Maybe the configuration is wrong
It also shows me this console:
INFO: Installed AtmosphereInterceptor Atmosphere LifeCycle with priority AFTER_DEFAULT
03-feb-2015 9:09:50 org.atmosphere.cpr.AsynchronousProcessor action
ADVERTENCIA: Websocket protocol not supported
03-feb-2015 9:09:50 org.atmosphere.cpr.AsynchronousProcessor action
GRAVE: Invalid request state. AsyncContext#startAsync not supported. Make sure async-supported is set to true in web.xml
03-feb-2015 9:09:52 org.atmosphere.cpr.AtmosphereFramework$4 run
INFO: Latest version of Atmosphere's JavaScript Client 2.2.6
Change JavaScript:
Last:
<script type="text/javascript">
function handleMessage(msg) {
msg.severity = 'info';
grow.show([msg]);
}
</script>
For This:
<script type="text/javascript">
function handleMessage(data) {
alert("Hola");
}
</script>
as I do that I work at the FacesMessage ¿?
I using spring security+JSF+primefaces
in custom login, i put a command button
but command button no workin ...
and when in p:commandbutton ----------> ajax="false" ---------> is work!
and when used f:ajax in jsf(core) --------> no work
and i use in spring security.xml file :
test.xhtml ----> jsf(core) --------> no work
<?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" xmlns:f="http://java.sun.com/jsf/core"
xml:lang="en" lang="en">
<head>
<title>faces-request</title>
</head>
<body>
<h:form>
<center>
<h:outputText id="outtxt" value="#{authentiocationBean.ajaxTest}"/><br/>
<h:inputText id="intxt" value="#{authentiocationBean.ajaxTest}"/><br/>
<h:commandButton value="Submit">
<f:ajax execute="intxt" render="outtxt"/>
</h:commandButton>
</center>
</h:form>
</body>
</html>
Spring_security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/Admin/*" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/user/*" access="hasAnyRole('ROLE_USER,ROLE_ADMIN')"/>
<form-login login-page="/login.xhtml"
authentication-failure-url="/Fail.xhtml?error"/>
<logout logout-url="/j_spring_security_logout" delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
invalidate-session="true"
logout-success-url="/login.xhtml"/>
<session-management session-authentication-error-url="/401.xhtml" session-fixation-protection="migrateSession">
<concurrency-control max-sessions="1" expired-url="/login.xhtml"/>
</session-management>
<remember-me key="myAppKey"/>
<access-denied-handler error-page="/AccDe.xhtml"/>
<headers>
<xss-protection/>
<frame-options/>
<cache-control/>
<content-type-options/>
</headers>
<csrf/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<jdbc-user-service data-source-ref="myDataSource"
users-by-username-query="select username, password, active from users where username=?"
authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur
where us.user_id = ur.user_id and us.username =? "
/>
<password-encoder ref="passwordEncoder" hash="sha-256"/>
</authentication-provider>
</authentication-manager>
<bean id="passwordEncoder"
xmlns="http://www.springframework.org/schema/beans"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<!--org.springframework.security.crypto.password.PasswordEncoder for salt!-->
<constructor-arg value="256"/>
</bean>
</beans:beans>
LoginPage:
<?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"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>faces-request</title>
</h:head>
<h:body>
<h:form prependId="false" id="formLogin">
<center>
<p:panelGrid style="border-width: 0px;" columns="2">
UserName:
<p:inputText required="true" id="j_username"/>
Password:
<p:password required="true" id="j_password"/>
</p:panelGrid>
<p:commandButton type="submit" id="login" action="#{authentiocationBean.doLogin()}" value="Login"/>
<p:outputLabel for="_spring_security_remember_me" value="Remember me: "/>
<p:selectBooleanCheckbox id="_spring_security_remember_me"/>
<br/>
</center>
</h:form>
</h:body>
</html>
AuthentiocationBean class
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* #author Admin
*/
#RequestScoped
#ManagedBean
public class AuthentiocationBean {
public String ajaxTest = "Test";
boolean isLogged = false;
public String role = "ROLE_ADMIN";
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String doLogin() throws IOException, ServletException {
isLogged = true;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext context = facesContext.getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");
dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
FacesContext.getCurrentInstance().responseComplete();
// It's OK to return null here because Faces is just going to exit.
return null;
}
public void doLogout() {
// FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
// return "/logout.xhtml";
// return null;
}
public boolean isLogged() {
return isLogged;
}
public void setLogged(boolean logged) {
isLogged = logged;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getAjaxTest() {
return ajaxTest;
}
public void setAjaxTest(String ajaxTest) {
this.ajaxTest = ajaxTest;
}
}
thanks
It's just a login page, so why bother with AJAX?
I have integrated Spring 3.1.4 LDAP support with JSF. Although I initially wrote a custom authentication bean, I do not use it any longer. I am not expert, and I'm sure there's a different way from what I implemented.
(1) Simple login page (excerpt):
<h:inputText id="j_username"/>
<h:inputText type="password" id="j_password" value=""/>
<h:commandButton name="submit" type="submit" value="Log In" />
<input type="reset" value="Reset" />
(2.1) In web.xml, I declare a context-param to name the security configuration file (mentioned in step 3 below).
I also declare the Spring security filter chain, which you can read about here:
http://docs.spring.io/spring-security/site/docs/3.1.4.RELEASE/reference/security-filter-chain.html#filter-chains-with-ns
(2.2) In faces-config I declare:
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
(2.3) In faces-config, I declare a custom UserSession bean with session scope.
UserSession bean has this method:
#PostConstruct
public void loadAuthorities() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
. . .
. . .
}
(3) UserSession bean is referred to from within the landing page (menu.xhtml) which is declared in my security config file (declared in web.xml in step 2.1 above):
<security:form-login default-target-url="/menu.xhtml" always-use-default-target="true" authentication-failure-url="/denied.xhtml" />
<security:logout invalidate-session="true" delete-cookies="JSESSIONID" logout-url="/j_spring_security_logout" />
(4) User is authenticated then redirected to menu.xhtml
Menu.xhtml causes UserSession bean to load.
UserSession bean pulls a list of Authorities from the SecurityContext.
UserSession bean provides simple wrappers to check whether a user has authority to view pages and resources:
public boolean isRole(String role) {
return authorities.contains((String) role);
}
public boolean roleContains(String s);
public boolean roleEndsWith(String s);
. . .
. . .
Im trying to test a sample JSF project but for some reason the command button are not being displayed that is given in the below page,
<?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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr />
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action="#{navigationController.moveToPage1}"
value="Page1" />
<h3>Using JSF outcome</h3>
<h:commandButton action="page2" value="Page2" />
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.showPage}"
value="Page1">
<f:param name="pageId" value="1" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Page2">
<f:param name="pageId" value="2" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Home">
<f:param name="pageId" value="3" />
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.processPage1}"
value="Page1" />
<h:commandLink action="#{navigationController.processPage2}"
value="Page2" />
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr />
<h:form>
<h3>Forward</h3>
<h:commandButton action="page1" value="Page1" />
<h3>Redirect</h3>
<h:commandButton action="page1?faces-redirect=true"
value="Page1" />
</h:form>
</h:body>
</html>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtm</url-pattern>
</servlet-mapping>
</web-app>
faces.config.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
view source html file
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr />
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action="#{navigationController.moveToPage1}"
value="Page1" />
<h3>Using JSF outcome</h3>
<h:commandButton action="page2" value="Page2" />
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.showPage}"
value="Page1">
<f:param name="pageId" value="1" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Page2">
<f:param name="pageId" value="2" />
</h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Home">
<f:param name="pageId" value="3" />
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr />
<h:form>
<h:commandLink action="#{navigationController.processPage1}"
value="Page1" />
<h:commandLink action="#{navigationController.processPage2}"
value="Page2" />
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr />
<h:form>
<h3>Forward</h3>
<h:commandButton action="page1" value="Page1" />
<h3>Redirect</h3>
<h:commandButton action="page1?faces-redirect=true"
value="Page1" />
</h:form>
</h:body>
</html>
Navigationcontroller
package com.tutorialspoint.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
#ManagedBean(name = "navigationController", eager = true)
#RequestScoped
public class NavigationController implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{param.pageId}")
private String pageId;
public String moveToPage1(){
return "page1";
}
public String moveToPage2(){
return "page2";
}
public String moveToHomePage(){
return "home";
}
public String processPage1(){
return "page";
}
public String processPage2(){
return "page";
}
public String showPage(){
if(pageId == null){
return "home";
}
if(pageId.equals("1")){
return "page1";
}else if(pageId.equals("2")){
return "page2";
}else{
return "home";
}
}
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
}
page1.xhtml
<?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:body>
<h2>This is Page1</h2>
<h:form>
<h:commandButton action="home?faces-redirect=true"
value="Back To Home Page" />
</h:form>
</h:body>
</html>
page2.xhtml
<?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:body>
<h2>This is Page2</h2>
<h:form>
<h:commandButton action="home?faces-redirect=true"
value="Back To Home Page" />
</h:form>
</h:body>
</html>
It's already been answered above, but I'll be specific. In your web.xml the <url-pattern> is specified as *.xhtm and your jsf files have a .xhtml extension. Note the missing letter in the pattern specification. Because of that your files aren't recognized and routed through the faces servlet. Just add the 'l' to the url-pattern in the web.xml and it should start working.
This question already has an answer here:
#ViewScoped calls #PostConstruct on every postback request
(1 answer)
Closed 6 years ago.
ARGH... This seems to have a hundred answers and I haven't found one that works for me, so I guess I will actually ask it again. Here is my scenario:
My site technically has a single page whose contents get swapped out rather than having multiple pages that you navigate to. The starting point is this chunk:
<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<ui:include src="resourceInclude.xhtml" />
<ui:include src="main.xhtml" />
</h:body>
</f:view>
The resourceInclude.xhtml includes my css file:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:outputStylesheet library="css" name="test.css" target="head" />
</ui:composition>
And main.xhtml is the view:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:panelGroup styleClass="test-container" layout="block">
<h:form id="main-form">
<h:panelGroup styleClass="test-header" layout="block">
<h:panelGroup styleClass="navigation" layout="block">
<ul>
<li><h:commandLink action="#{viewSelector.setModeHome}">
<h:outputText value="Home" />
</h:commandLink></li>
<li><h:commandLink action="#{viewSelector.setModeReports}">
<h:outputText value="ASAP Reports" />
</h:commandLink></li>
<li><h:commandLink action="#{viewSelector.setModeSupport}">
<h:outputText value="Technical Support" />
</h:commandLink></li>
<li><h:commandLink action="#{viewSelector.setModeHelp}">
<h:outputText value="Help" />
</h:commandLink></li>
</ul>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup styleClass="test-content" layout="block">
<ui:include src="#{viewSelector.modeName}-view.xhtml" />
</h:panelGroup>
<h:panelGroup styleClass="test-footer" layout="block">
<h:messages />
</h:panelGroup>
</h:form>
</h:panelGroup>
</ui:composition>
It consists of three h:panelGroups. The first is a set of four general navigation links, each link changes the viewSelector.modeName value which is used to include the contents in the second h:panelGroup thusly <ui:include src="#{viewSelector.modeName}-view.xhtml" />. I have stripped this down for this example so each view is basically this:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:panelGroup styleClass="test-home-view">
<p>home</p>
</h:panelGroup>
</ui:composition>
The third h:panelGroup is a footer for all the messages to debug what is going wrong.
Anyway, every time I click one of the navigation links, the constructor of the viewSelector bean gets called. This is what my viewSelector bean looks like:
package org.mitre.asias.aires.controller;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.apache.log4j.Logger;
#ManagedBean( name="viewSelector" )
#ViewScoped
public class ViewSelector {
protected static Logger log = Logger.getLogger( ViewSelector.class );
private Mode mode = Mode.HOME;
public static final String PORTLET_NAME = "Test";
public static enum Mode {
HOME(1, "home"),
REPORTS(2, "reports"),
SUPPORT(3, "support"),
HELP(4, "help");
private int value;
private String name;
private Mode( int value, String name ) {
this.value = value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
}
public ViewSelector() {
log.trace( "constructing new ViewSelector" );
}
public Mode getMode() {
log.trace( "getting mode" );
return mode;
}
public String getModeName() {
log.debug( "in getmodename" );
return getMode().getName();
}
public String getPortletName() {
return PORTLET_NAME;
}
public boolean isModeReports() {
return getMode() == Mode.REPORTS;
}
public void setMode( Mode mode ) {
this.mode = mode;
}
public void setModeHelp() {
setMode( Mode.HELP );
}
public void setModeHome() {
setMode( mode = Mode.HOME );
}
public void setModeReports() {
setMode( mode = Mode.REPORTS );
}
public void setModeSupport() {
setMode( mode = Mode.SUPPORT );
}
}
I know I must be doing something the wrong way, or else I missing something central as to how JSF works. Any Input?
The EL in <ui:include src> is causing that.
If disabling the partial state saving in web.xml as per issue 1492 is not an option,
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>true</param-value>
</context-param>
then you need to replace
<ui:include src="#{viewSelector.modeName}-view.xhtml" />
by something like
<h:panelGroup rendered="#{viewSelector.mode == 'HOME'}">
<ui:include src="home-view.xhtml" />
</h:panelGroup>
<h:panelGroup rendered="#{viewSelector.mode == 'REPORTS'}">
<ui:include src="reports-view.xhtml" />
</h:panelGroup>
<h:panelGroup rendered="#{viewSelector.mode == 'SUPPORT'}">
<ui:include src="support-view.xhtml" />
</h:panelGroup>
<h:panelGroup rendered="#{viewSelector.mode == 'HELP'}">
<ui:include src="help-view.xhtml" />
</h:panelGroup>
A similar question has at least been asked once before :)
How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)