Richfaces 4.5.17 Menuitem action method not working - jsf-2

developers !!
I am migrating a web application from JEE5 to JEE7. My problem concerns to the presentation layer.
All the system pages are being migrated from RichFaces 3.3.3 to 4.5.17. I have been following the official migration guide ([https://developer.jboss.org/wiki/RichFacesMigrationGuide33x-4xMigration][1]), the Richfaces forum (https://developer.jboss.org/en/richfaces) and of course StackOverflow. But none has provided me a solution to my problem:
The app menu is built dinamically on the managedbean (not with tags on xhtml). It worked fine on RF 3.3.3, using the classes HtmlToolBar, HtmlDropDownMenu, HtmlMenuGroup and HtmlMenuItem. However, after migrating to the RF4 corresponding classes, the MenuItem action method is not fired anymore. After the user clicks on the MenuItem, page refreshes and request is made to the current page itself, instead of the desired page.
The migrated code follows below:
ManagedBean
package br.gov.serpro.sfitweb.ui.managedbean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.apache.log4j.Logger;
import org.richfaces.component.Mode;
import org.richfaces.component.UIDropDownMenu;
import org.richfaces.component.UIMenuGroup;
import org.richfaces.component.UIMenuItem;
import org.richfaces.component.UIToolbar;
import br.gov.serpro.sfitweb.bean.entity.Usuario;
import br.gov.serpro.sfitweb.bean.enums.Permissao;
import br.gov.serpro.sfitweb.context.ContextFinder;
import br.gov.serpro.sfitweb.context.SFITSecurityContext;
#Named
#SessionScoped
public class MenuMBTrecho implements Serializable {
private static final long serialVersionUID = 1L;
private UIToolbar toolbar;
public MenuMBTrecho() {
}
#PostConstruct
public void init() {
montarToolbar();
}
public void montarToolbar() {
FacesContext ctx = FacesContext.getCurrentInstance();
this.toolbar = (UIToolbar) ctx.getApplication().createComponent(ctx, UIToolbar.COMPONENT_TYPE,
"org.richfaces.ToolbarGroupRenderer");
// log.debug("User" + secCtx.getUserPrincipal().getCpf());
UIDropDownMenu menuPlanejamento = new UIDropDownMenu();
menuPlanejamento.setLabel("Planejamento");
boolean mostraMenu = false;
///////// Submenu PPA /////////
boolean mostraSubMenuPPA = false;
UIMenuGroup subMenuPPA = new UIMenuGroup();
subMenuPPA.setLabel("PPA");
UIMenuItem menuItem = new UIMenuItem();
menuItem.setMode(Mode.ajax);
menuItem.setLabel("Cadastrar perĂ­odo de PPA");
ExpressionFactory factory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
ELContext ELCtx = FacesContext.getCurrentInstance().getELContext();
menuItem.setActionExpression(
factory.createMethodExpression(ELCtx, "#{ppaMB.listarPpas}", String.class, new Class[] {}));
subMenuPPA.getChildren().add(menuItem);
}
public UIToolbar getToolbar() {
return toolbar;
}
public void setToolbar(UIToolbar toolbar) {
this.toolbar = toolbar;
}
}
menu.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:richext="http://java.sun.com/jsf/composite/richext"
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:rich="http://richfaces.org/rich"
xmlns:p="http://primefaces.org/ui">
<div id="menu">
<h:form id="menuForm">
<rich:toolbar binding="#{menuMB.toolbar}"/>
</h:form>
</div>
</ui:composition>
common.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j">
<f:view contentType="text/html">
<h:head>
<ui:include src="/public/pages/scriptTags.xhtml" />
</h:head>
<link rel="stylesheet"
href="#{configMB.context}/public/resources/styles/richfaces.css" />
<h:body onload="ajustaAltura();"
style="width:100%; padding:0px; margin: 0px; border-spacing: 0px;">
<h:form id="principalMenu">
<rich:messages globalOnly="false" errorClass="errorFatalMessage"
fatalClass="errorFatalMessage" infoClass="infoMessage"
warnClass="warnMessage" showSummary="true" showDetail="true">
</rich:messages>
<ui:insert name="top">
<ui:include src="/public/pages/top.xhtml" />
</ui:insert>
<ui:insert name="header">
<ui:include src="/public/pages/header.xhtml" />
</ui:insert>
<ui:insert name="menu">
<ui:include src="/private/pages/menu.xhtml" />
</ui:insert>
<div id="corpo" align="center">
<rich:panel style="width: 97%;border:0">
<ui:insert name="body" />
</rich:panel>
</div>
<ui:insert name="footer">
<ui:include src="/public/pages/footer.xhtml" />
</ui:insert>
</h:form>
</h:body>
</f:view>
</html>
faces-config.xml
<?xml version="1.0"?>
<faces-config version="2.2" 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">
<application>
<resource-bundle>
<base-name>br.gov.serpro.sfitweb.utils.MsgReaderUTF8</base-name>
<var>msg</var>
</resource-bundle>
</application>
<lifecycle>
<phase-listener>br.gov.serpro.sfitweb.ui.MessagePhaseListener</phase-listener>
</lifecycle>
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>com.example.faces.i18n.Text</base-name>
<var>text</var>
</resource-bundle>
</application>
</faces-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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-app_3_1.xsd">
<display-name>sfitweb</display-name>
<distributable />
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<!-- parametros necessario para processar os JS internos do Richfaces https://developer.jboss.org/thread/203506 -->
<context-param>
<param-name>org.richfaces.resourceOptimization.enabled</param-name>
<param-value>true</param-value>
</context-param>
<servlet>
<servlet-name>Resource Servlet</servlet-name>
<servlet-class>org.richfaces.webapp.ResourceServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resource Servlet</servlet-name>
<url-pattern>/org.richfaces.resources/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/tomahawk.taglib.xml;
/WEB-INF/taglib/sfit.taglib.xml;</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>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<!-- parametros do Richfaces 4 -->
<context-param>
<param-name>org.richfaces.enableControlSkinning</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>wine</param-value>
</context-param>
<context-param>
<param-name>weblets.CONFIG_FILES</param-name>
<param-value>weblets-config.xml</param-value>
</context-param>
<!-- https://developer.jboss.org/wiki/RichFacesMigrationGuide33x-4xMigration-Upgrading
filtro do richfaces nao eh mais necessario no JSF 2 -->
<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
<init-param>
<param-name>uploadMaxFileSize</param-name>
<param-value>20m</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<!-- <listener> -->
<!-- <listener-class>br.gov.serpro.sfitweb.context.SFITSecurityServletRequestListener</listener-class> -->
<!-- </listener> -->
<listener>
<listener-class>net.java.dev.weblets.WebletsContextListener</listener-class>
</listener>
<!-- WebService para consulta de permissoes -->
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Weblets Servlet</servlet-name>
<servlet-class>net.java.dev.weblets.WebletsServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ImageUploadServlet</servlet-name>
<servlet-class>br.gov.serpro.sfitweb.utils.ImageUploadServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ImageDownloadServlet</servlet-name>
<servlet-class>br.gov.serpro.sfitweb.utils.ImageDownloadServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>PossuiPermissao</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</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>
<servlet-mapping>
<servlet-name>Weblets Servlet</servlet-name>
<url-pattern>/weblets/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ImageUploadServlet</servlet-name>
<url-pattern>/imageUpload</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ImageDownloadServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PossuiPermissao</servlet-name>
<url-pattern>/PossuiPermissao</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- Pages Configuration -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/public/pages/error/HTTP404.jsf</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/public/pages/error/HTTP500.jsf</location>
</error-page>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/public/pages/login.jsf</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/public/pages/error/global.jsp</location>
</error-page>
</web-app>
Please, any help that points me at least to the cause of this problem would be appreciated.
Thank you in advance !
William

Solved it !
1.) Modified init() on ManagedBean:
#PostConstruct
public void init(){
menuPlanejamento = (UIDropDownMenu)FacesContext.getCurrentInstance().getApplication().createComponent(UIDropDownMenu.COMPONENT_TYPE);
}
2.) Added menuItem.setMode(Mode.ajax) on montarToolbar() method;
3.) Modified the xhtml page:
<div id="menu">
<h:form id="menuForm">
<rich:toolbar id="menuToolbar">
<rich:dropDownMenu id="menuPlanejamento" binding="#{menuMB.menuPlanejamento}"/>
</rich:toolbar>
</h:form>
</div>
That's it !!

Related

How Shiro can protect JSF-2 page from unprotected page without login?

I try to set up Apache Shiro to JSF 2 pages.
I want to protect page1 but I can reach it without login from the unprotected home.xhtml.
From page1.xhtml with redirect I get to the loginpage.xhtml. (As defined)
If logged in it works fine.
It looks not the target but the 'from' page is supervised.
How do I have to modify shiro.ini to set
home.xhtml available without login AND page1.xhtml NOT available without login?
shiro.ini .....
[main]
authc.loginUrl = /faces/loginpage.xhtml
//authc = org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter - It was the same without REM
securityManager.rememberMeManager.cookie.name = demoRememberMe
[users]
a = q
[roles]
a = *
[urls]
/home.xhtml = anon
/loginpage.xhtml = authc
/page1.xhtml = authc
/protected.xhtml = authc
/faces/home.xhtml = anon
/faces/loginpage.xhtml = authc
/faces/page1.xhtml = authc
/faces/protected.xhtml = authc
/** = anon
home.xhtml:
<h:commandButton action="#{navigationController.moveToPage1}" value="Page 1" >
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:head>
<title>BEMO - Page 1</title>
<h:outputStylesheet library="css" name="styles.css" />
</h:head>
<h:form>
<h:commandButton action="home?faces-redirect=true"
value="Back To Home Page" />
</h:form>
</h:body>
</html>
web.xml:
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

Custom Login validation Spring Security

am trying to do custom login validation using spring security as i am a starter i don't know the error below is my code, project structure,jar files and error
My Project Structure and Jars
Error:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:605)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:509)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4760)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5184)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more
Aug 17, 2016 2:56:56 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Aug 17, 2016 2:56:56 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/CustomLoginValidation] startup failed due to previous errors
Aug 17, 2016 2:56:56 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Aug 17, 2016 2:56:56 PM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1000)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:976)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:928)
at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:583)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:116)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4801)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5401)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>spring_mvc</display-name>
<welcome-file-list><welcome-file>/WEB-INF/jsp/index.jsp</welcome-file> </welcome-file-list>
<!-- Single Servlet -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- create ds , only app start.. -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<!-- map all action to ds -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security Configuration -->
<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>
</web-app>
Spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.pradeep.demo" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<import resource="SpringSecurity.xml"/>
</beans>
SpringSecurity.xml
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:bean="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_USER" />
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="mkyong" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</bean:beans>
jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.error {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.msg {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
#login-box {
width: 300px;
padding: 20px;
margin: 100px auto;
background: #fff;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border: 1px solid #000;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>
<h1>Spring Security Custom Login Form (Annotation)</h1>
<div id="login-box">
<h2>Login with Username and Password</h2>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='user' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='pass' /></td>
</tr>
<tr>
<td colspan='2'>
<input name="submit" type="submit" value="submit" />
</td>
</tr>
</table>
<input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</div>
</body>
</html>
Controller class:
package org.pradeep.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloController {
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Custom Login Form");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Custom Login Form");
model.addObject("message", "This is protected page!");
model.setViewName("admin");
return model;
}
//Spring Security see this :
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
}
The error itself is pretty self explainatory: FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml].
You did configure the XML file for the DispatcherServlet, but did not configure the root context, so the Spring ContextLoaderListener tries to bootstrap the root context from the default /WEB-INF/applicationContext.xml.
Anyway, you should not declare the Spring security configuration inside the DispatcherServlet application context, but in the root one. Spring security in implemented through filters, and filters run before the DispatcherServlet has been called. You should remove <import resource="SpringSecurity.xml"/> from your Spring-config.xml file and add an applicationContext.xml file under WEB-INF for it, in which you will later add the service and persistence beans that do no depend on the DispatcherServlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- non web spring beans will go here -->
<import resource="SpringSecurity.xml"/>
</beans>
Alternatively you can tell the ContextLoaderListener to load the file SpringSecurity.xml from the web.xml file:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/SpringSecurity.xml</param-value>
</context-param>

Spring security for just authorization, how to implement custom UserDetailsService and call it from login page

I have a system that already has a class to authenticate and control access to pages that require authentication, now I need include the spring security in the project to control access to pages in accordance with the permissions of each user and also control access to certain system resources, such as a user permission to list records and does not have permission to delete records.
I'm trying to implement a customUserDetails but I dont know how to do my login page calls it.
My web.xml:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<display-name>Ultracar Web</display-name>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<!--<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>-1</param-value>
</context-param>
-->
<welcome-file-list>
<welcome-file>Principal/index.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>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<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>
</web-app>
My spring-security:
<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="Principal/index*" access="permitAll" />
<intercept-url pattern="/Principal/*" access="permitAll"/>
<form-login login-page="/Principal/index.xhtml"
default-target-url="/"
authentication-failure-url="/"/>
<logout logout-success-url="/" />
</http>
<beans:bean id="customUserDetails" class="br.com.ultracar.ultracarweb.spring.security.UserDetailsServiceImpl" />
<authentication-manager>
<authentication-provider user-service-ref="customUserDetails" />
</authentication-manager>
</beans:beans>
My Login page:
<h:head>
<link rel="SHORTCUT ICON" href="../Images/logo_ultracar.png"/>
</h:head>
<h:body>
<ui:composition template="./../Principal/template_start.xhtml">
<ui:define name="content">
<div class="slider">
<div class="container" style="padding: 10px;">
<div class="col-lg-9 col-xs-9 col-sm-9">
<ui:include src="slider.xhtml"/>
</div>
<div class="row">
<div class="col-lg-12 col-xs-12 col-sm-12">
<p:inputText value="#{MBControl.login}" required="true"
style="width: 100%;-moz-box-shadow: none !important; -webkit-box-shadow: none !important;
box-shadow: none !important; -moz-border-radius: 0 !important;
-webkit-border-radius: 0 !important; border-radius: 0 !important;"
requiredMessage="#{Utils.getStrLanguage('User_required')}"/>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-xs-12 col-sm-12">
<h:outputLabel style="color: #303030;" value="#{Utils.getStrLanguage('Password')}:" />
</div>
</div>
<div class="row">
<div class="col-lg-12 col-xs-12 col-sm-12">
<p:password value="#{MBControl.senha}" required="true" id="txtSenha" styleClass="reset-style"
style="width: 100%;-moz-box-shadow: none !important; -webkit-box-shadow: none !important;
box-shadow: none !important; -moz-border-radius: 0 !important;
-webkit-border-radius: 0 !important; border-radius: 0 !important;"
requiredMessage="#{Utils.getStrLanguage('password_required')}"/>
</div>
</div>
<div class="row" style="margin-top: 15px;">
<div class="col-lg-4 col-xs-6 col-sm-12">
<p:commandLink id="btnLogin" styleClass="btn button-green" ajax="false" action="#{MBControl.login()}"
update="frmLogin" value="#{Utils.getStrLanguage('Login')}" style="border-radius: 0 !important;"/>
</div>
<p:growl autoUpdate="true"/>
</div>
</h:form>
</div>
</div>
</div>
</ui:define>
</ui:composition>
</h:body>
My login class:
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(false);
Session session = FacesContextUtil.getRequestSession();
Usuario user = null;
boolean passwordOk = false;
UserDetailsServiceImpl userDetails = new UserDetailsServiceImpl();
try
{
user = (user) session.createCriteria(User.class)
.add(Restrictions.eq("user",login))
.list().get(0);
senhaOk = (usuario.getPassword().equals(password));
}catch(Exception ex){
System.out.println(ex.toString());
}
if (user !=null && passwordOk){
if (!user.getActive()){
warning(null,Utils.getStrLanguage("User_not_active")+"!",FacesMessage.SEVERITY_FATAL);
return "exit";
}
sessao.setAttribute("login", login);
sessao.setAttribute("password", new Utils().SHA1(password));
MBControl.matriz = usuario.getIdMatrix();
userDetails.loadUserByUsername(login);
return "sucess";
}else{
warning(null,Utils.getStrLanguage("User_pass_invalid")+"!",FacesMessage.SEVERITY_FATAL);
return "exit";
}
}
Update, I am trying to implement (just for a test) UserDetailsServiceImpl this way:
#Service("userService")
public class UserDetailsServiceImpl implements UserDetailsService {
public UserDetails loadUserByUsername( String username ) throws UsernameNotFoundException{
FacesContext contexto = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) contexto.getExternalContext().getSession(false);
boolean enabled = false;
boolean credentialsNonExpired = false;
boolean accountNonExpired = false;
boolean accountNonLocked = false;
Authority autorizacao = new Authority("ROLE_ADMIN");
Set<Authority> roles = new HashSet<Authority>();
enabled = true;
credentialsNonExpired = true;
accountNonExpired = true;
accountNonLocked = true;
roles.add(autorizacao);
String senha = session.getAttribute("password").toString();
User springUser = new User(username, senha, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, roles);
return springUser;
}
}
How to implement CustomUserDetails and call it on the login page?

NullPointerException exception after submitting commandButton(JSF 2.1)

I am getting NullPointerException when I click on commonButton to submit the page:
SEVERE: javax.servlet.ServletException
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at ca.bc.gov.hlth.template.filter.ProcessFilter.doFilter(ProcessFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NullPointerException
at javax.faces.component.UIComponentBase.getRenderer(UIComponentBase.java:1402)
at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:785)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1181)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1176)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1176)
at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:933)
at com.sun.faces.extensions.avatar.components.PartialTraversalViewRootImpl.processDecodes(PartialTraversalViewRootImpl.java:147)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
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:593)
... 29 more
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">
<display-name>SSD</display-name>
<context-param>
<param-name>org.richfaces.skin</param-name>
<param-value>CUSTOM</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.enableControlSkinning</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>org.richfaces.push.jms.enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<servlet>
<servlet-name>ExceptionHandlerServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<init-param>
<param-name>errorHost</param-name>
<param-value>localhost</param-value>
</init-param>
<init-param>
<param-name>errorPort</param-name>
<param-value>24444</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>JsonSearch</servlet-name>
<servlet-class>ca.bc.gov.hlth.swt.map.JsonSearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JsonSearch</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<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>
<filter>
<filter-name>ProcessFilter</filter-name>
<filter-class>ca.bc.gov.hlth.template.filter.ProcessFilter</filter-class>
<init-param>
<param-name>error-page</param-name>
<param-value>/faces/Error.xhtml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ProcessFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<listener>
<listener-class>ca.bc.gov.hlth.swt.util.StartupListener</listener-class>
</listener>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/Home.xhtml</welcome-file>
</welcome-file-list>
<error-page>
<error-code>403</error-code>
<location>/faces/AccessDenied.xhtml</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/faces/Error.xhtml</location>
</error-page>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jspf</url-pattern>
</jsp-property-group>
</jsp-config>
</web-app>
This is my faces-config.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ================================== -->
<faces-config version="2.1"
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_1.xsd">
<faces-config-extension>
<facelets-processing>
<file-extension>.jspx</file-extension>
<process-as>jspx</process-as>
</facelets-processing>
</faces-config-extension>
<managed-bean>
<managed-bean-name>Map</managed-bean-name>
<managed-bean-class>swtwar.Map</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>Search</managed-bean-name>
<managed-bean-class>swtwar.Search</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>Home</managed-bean-name>
<managed-bean-class>swtwar.Home</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>LayoutWide</managed-bean-name>
<managed-bean-class>swtwar.LayoutWide</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>Tester</managed-bean-name>
<managed-bean-class>swtwar.Tester</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
Here is the code I use for CommondButton; #{Home.search} returns 'search':
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
<h:commandButton onclick="document.getElementById('form1:procedureFilter').value='';" action="#{Home.search}" value="Select Search Criteria" />
Both Home.xhtml and Search.xhtml(home.xhtml --> Search.xhtml) are in the same folder.
I also found that glassfish 3.1 is giving following error:
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
SEVERE: Application was not properly initialized at startup, could not find Factory: javax.faces.application.ApplicationFactory. Attempting to find backup.
Any Help?
Thanks
Harbinder
Update: After some work around I found that I'm actually getting NullPointerException from the ManagedBean:
WARNING: #{Home.search}: java.lang.NullPointerException
javax.faces.FacesException: #{Home.search}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
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:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at ca.bc.gov.hlth.template.filter.ProcessFilter.doFilter(ProcessFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: 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)
... 36 more
Caused by: java.lang.NullPointerException
at swtwar.Home.search(Home.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 37 more
INFO: HP_excptn:javax.servlet.ServletException: java.lang.NullPointerException: java.lang.NullPointerException
SEVERE: javax.servlet.ServletException: java.lang.NullPointerException
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at ca.bc.gov.hlth.template.filter.ProcessFilter.doFilter(ProcessFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: 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:593)
... 29 more
Caused by: java.lang.NullPointerException
at swtwar.Home.search(Home.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 37 more
Here Home.Search is pointing to:
#ManagedProperty(value = "#{Search}")
private Search search;
#ManagedProperty(value = "#{Tester}")
private Tester tester;
public Home() {
}
public Search getSearch(){
return this.search;
}
public void setSearch(Search search){
this.search = search;
}
public String search() {
if (siteId == null) {
init();
}
tester.testing();
return "tester";
}
And tester is pointing to Tester.xhtml and testing() is a testing procedure of its bean class:
#ManagedBean
public class Tester implements Serializable
{
public Tester(){
}
#PostConstruct
public void testing(){
System.out.println("HP_Tester_Testing.....");
}
}
For my case (TomEE plus 1.7.2, JSF 2.2, MyFaces 2.1.17 and Eclipse Luna) f:ajax needed a render kit to complete refreshing of the relevant component.
I had this error in my stackTrace:
java.lang.NullPointerException
javax.faces.component.UIComponentBase.getRenderer(UIComponentBase.java:1304)
...
similar to yours
Caused by: java.lang.NullPointerException
at javax.faces.component.UIComponentBase.getRenderer(UIComponentBase.java:1402)
...
I resolved the issue by adding render kit declaration in faces config and adding relevant libraries to the project. Of course, the libraries might be different for other implementations.
<application>
<default-render-kit-id>org.apache.myfaces.trinidad.core</default-render-kit-id>
</application>
trinidad libraries:
trinidad-api-2.0.1.jar
trinidad-impl-2.0.1.jar

Login form issue with spring security 2.0.7 and spring 2.5

Hi i am trying to put a login page on my application.
My login.jsp is
<form name='f' action="<c:url value='j_spring_security_check' />"
method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
Login controller
#Controller
public class LoginController {
#RequestMapping("/user/login.do")
public ModelAndView handleLoginForm(HttpServletRequest request) {
String errParam = request.getParameter("error");
ModelAndView mv = new ModelAndView("login");
if(errParam != null) {
mv.addObject("error", "Benutzer oder Kennwort unzulässig");
}
return mv;
}
}
spring secuirty xml
<http auto-config="true">
<intercept-url pattern="/login"
access="ROLE_USER" />
<intercept-url pattern="/j_spring_security_check"
access="ROLE_USER" />
<form-login login-page="/login"
login-processing-url="/j_spring_security_check" default-target-url="/userPage.do"
authentication-failure-url="/login?error=1" />
<logout logout-success-url="/login"
logout-url="/logout" />
<!-- <intercept-url pattern="/user/userPage.do" access="ROLE_USER" />
<form-login login-page="/user/login.do" default-target-url="/user/userPage.do"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" /> -->
</http>
<authentication-provider>
<user-service id="userDetailsService">
<user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="username" password="password" authorities="ROLE_USER" />
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</beans:beans>
spring xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="userFormValidator" class="com.validator.UserFormValidator"/>
<bean id="userProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="userManager" />
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="genderManager" class="com.service.impl.GenderManagerImpl">
</bean>
<bean id="userProxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.service.UserManager</value>
</property>
<property name="target">
<ref bean="userManager" />
</property>
<property name="interceptorNames">
<list>
<value>loggerAdviser</value>
</list>
</property>
</bean>
<bean id="genderProxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.service.GenderManager</value>
</property>
<property name="target">
<ref bean="genderManager" />
</property>
<property name="interceptorNames">
<list>
<value>loggerAdviser</value>
</list>
</property>
</bean>
<bean id="loggerAdviser" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref bean="loggingInterceptor"/>
</property>
<property name="patterns">
<value>.*</value>
</property>
</bean>
<bean id="loggingInterceptor" class="com.log.LoggingInterceptor"/>
<bean id="userDetailController" class="com.web.UserDetailController">
<property name="userManager"><ref bean="userProxyBean"/></property>
</bean>
<bean id="loginController" class="com.web.LoginController">
</bean>
<bean id="userController" class="com.web.UserController">
<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>userBean</value></property>
<property name="commandClass"><value>com.beans.UserBean</value></property>
<property name="validator"><ref bean="userFormValidator"/></property>
<property name="formView"><value>userForm</value></property>
<property name="successView"><value>userDetail.do</value></property>
<property name="userManager"><ref bean="userProxyBean"/></property>
<property name="genderManager"><ref bean="genderProxyBean"/></property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/user/userPage.do"><ref bean="userController"/></entry>
<entry key="/user/userDetail.do"><ref bean="userDetailController"/></entry>
<entry key="/user/login.do"><ref bean="loginController"/></entry>
</map>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
web.xml
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring context loading ends-->
<servlet>
<servlet-name>user</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
<!-- Spring Security -->
<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>
</web-app>
Now when ever i hit http://localhost:8080/springhibernate/user/login.do
it shows me login page but when click login it always gives me error
The requested resource (/springhibernate/user/j_spring_security_check) is not available.
The page is redirected to http://localhost:8080/springhibernate/user/j_spring_security_check
Please help me to solve this issue and suggest me how this login feature can be implimented in my app i am stuck with it
I have pretty much the same setup with a separate login form, but on login action the following method get's called:
(see edit)
Not too sure how it works but appearently it's neccessairy:
http://ocpsoft.com/java/jsf-java/spring-security-what-happens-after-you-log-in/
EDIT:
my form:
<h:form id="loginForm" prependId="false">
<label for="j_username"><h:outputText value="Username:" /><br />
</label>
<h:inputText id="j_username" required="true">
</h:inputText>
<br />
<br />
<label for="j_password"><h:outputText value="Password:" /><br />
</label>
<h:inputSecret id="j_password" required="true">
</h:inputSecret>
<br />
<br />
<label for="_spring_security_remember_me"> <h:outputText
value="Remember me" /> </label>
<h:selectBooleanCheckbox id="_spring_security_remember_me" />
<br />
<h:commandButton type="submit" id="login"
action="#{loginBean.doLogin}" value="Login" />
</h:form>
Login bean:
#SessionScope
public class LoginBean implements Serializable
{
private String j_username;
private String j_password;
private String _spring_security_remember_me;
public String getJ_username() {
return j_username;
}
public void setJ_username(String j_username) {
this.j_username = j_username;
}
public String getJ_password() {
return j_password;
}
public void setJ_password(String j_password) {
this.j_password = j_password;
}
public String get_spring_security_remember_me() {
return _spring_security_remember_me;
}
public void set_spring_security_remember_me(String _spring_security_remember_me) {
this._spring_security_remember_me = _spring_security_remember_me;
}
// This is the action method called when the user clicks the "login" button
public String doLogin() throws IOException, ServletException
{
ExternalContext context = FacesContext.getCurrentInstance().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;
}
}
Here are my working configs for your reference . They seem to be quite the same . These are for Spring 3.0 . Haven't tried with 2.x but thought this may help you .
<!-- Spring-security -->
<http auto-config="false" access-denied-page="/login.jsp?error=Access%20Denied">
<intercept-url pattern="/login.jsp*" filters="none" />
<intercept-url pattern="/manager/**" access="${manager.roles}" />
<form-login login-page="/login.jsp"
default-target-url="/welcome.jsp"
always-use-default-target="true"
authentication-failure-url="/login.jsp?error=true" />
<logout logout-success-url="/login.jsp"/>
<anonymous/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="a" password="a" authorities="ROLE_MANAGER" />
</user-service>
</authentication-provider>
</authentication-manager>
<!--Jsp -->
<form name="login" action="<c:url value="j_spring_security_check"/>" method="POST">
<table width="40%" border="4" align="center" cellpadding="0" cellspacing="0" bordercolor="#E3DBB8">
<tr><td bgcolor="#FFF4C3"><br>
<table width="100%" border="0" align="center" cellpadding="10" cellspacing="0" frame="box">
<tr>
<td align="right" nowrap><font face="Tahoma" size="+1">User Name:</font></td>
<td align="left" width="300"><input id="username" tabindex="1"
type="text" name="j_username" maxlength="20" border="1" style="width: 150px"/ ></td>
</tr>
<tr>
<td align="right" nowrap><font face="Tahoma" size="+1">Password:</font></td>
<td align="left"><input id="password" tabindex="2" type="password" name="j_password" maxlength="20" style="width: 150px"/></td>
</tr>
<tr>
<td align="right"><input type="submit" tabindex="3" name="login" value=" Login " class="Button" /></td>
<td align="left">
<input type="reset" tabindex="3" name="reset" value=" Reset " class="Button" />
</td>
</tr>
</table><br>
</td></tr>
</table>
</form >
<!--Web.xml -->
<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>

Resources