Spring and JSF - Dependency Injection fails ServiceBean can not be loaded - spring

i currently hang up in the Spring and JSF Integration. I think i misconfigured something and i can not see what exactly. I get a NULL Pointer Exception because of the Service Tier is not going to be loaded by the JSF Bean. My configuration is the following:
Stacktrace
java.lang.NullPointerException
at com.speterit.auftragssystem.beans.MitarbeiterBean.getMitarbeiterList(MitarbeiterBean.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:484)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:159)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:553)
at javax.faces.component.UIData.getDataModel(UIData.java:1293)
at javax.faces.component.UIData.setRowIndex(UIData.java:446)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:77)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:824)
at javax.faces.component.UIData.encodeBegin(UIData.java:936)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:335)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
default.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"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:head>
</h:head>
</head>
<h:body>
#{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br />
<h:dataTable value="#{mitarbeiterBean.getMitarbeiterList()}" var="m">
<h:column>
<f:facet name="header">Vorname</f:facet>
#{m.vorname}
</h:column>
<h:column>
<f:facet name="header">Nachname</f:facet>
#{m.nachname}
</h:column>
<h:column>
<f:facet name="header">Geburtsdatum</f:facet>
#{m.geburtsdatum}
</h:column>
</h:dataTable>
</h:body>
The evaluation #{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br /> is giving false when I execute the code without the datatable part.
MitarbeiterBean.java
package com.speterit.auftragssystem.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
import com.speterit.auftragssystem.data.service.IServiceMitarbeiter;
#ManagedBean(name = "mitarbeiterBean")
#RequestScoped
public class MitarbeiterBean implements Serializable
{
private static final long serialVersionUID = 1L;
public IServiceMitarbeiter serviceMitarbeiter;
public String vorname;
public String nachname;
public Date geburtsdatum;
public List<Mitarbeiter> getMitarbeiterList()
{
return getServiceMitarbeiter().retrieveAllMitarbeiter();
}
public void addMitarbeiter()
{
Mitarbeiter mitarbeiter = new Mitarbeiter(getVorname(), getNachname(),
getGeburtsdatum());
getServiceMitarbeiter().createMitarbeiter(mitarbeiter);
clearForm();
}
public void clearForm()
{
setVorname("");
setNachname("");
setGeburtsdatum(null);
}
public String getVorname()
{
return vorname;
}
public void setVorname(String vorname)
{
this.vorname = vorname;
}
public String getNachname()
{
return nachname;
}
public void setNachname(String nachname)
{
this.nachname = nachname;
}
public Date getGeburtsdatum()
{
return geburtsdatum;
}
public void setGeburtsdatum(Date geburtsdatum)
{
this.geburtsdatum = geburtsdatum;
}
public IServiceMitarbeiter getServiceMitarbeiter()
{
return serviceMitarbeiter;
}
public void setServiceMitarbeiter(IServiceMitarbeiter serviceMitarbeiter)
{
this.serviceMitarbeiter = serviceMitarbeiter;
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Hibernate -->
<beans:bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
<beans:property name="configurationClass"
value="org.hibernate.cfg.AnnotationConfiguration" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</beans:prop>
<beans:prop key="hibernate.c3p0.min_size">5</beans:prop>
<beans:prop key="hibernate.c3p0.max_size">20</beans:prop>
<beans:prop key="hibernate.c3p0.timeout">1800</beans:prop>
<beans:prop key="hibernate.c3p0.max_statements">50</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernateSessionFactory" />
</beans:bean>
<!-- Model Declaration -->
<beans:bean id="Mitarbeiter" class="com.speterit.auftragssystem.data.model.Mitarbeiter"/>
<!-- DAO Declaration -->
<beans:bean id="DaoMitarbeiter" class="com.speterit.auftragssystem.data.dao.DaoMitarbeiter">
<beans:property name="sessionFactory" ref="SessionFactory" />
</beans:bean>
<!-- Service Declaration -->
<beans:bean id="ServiceMitarbeiter" class="com.speterit.auftragssystem.data.service.ServiceMitarbeiter">
<beans:property name="daoMitarbeiter" ref="DaoMitarbeiter" />
</beans:bean>
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">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
<managed-bean>
<managed-bean-name>mitarbeiterBean</managed-bean-name>
<managed-bean-class>com.speterit.auftragssystem.beans.MitarbeiterBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>serviceMitarbeiter</property-name>
<value>#{ServiceMitarbeiter}</value>
</managed-property>
</managed-bean>
</faces-config>
IServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
public interface IServiceMitarbeiter
{
public List<Mitarbeiter> retrieveAllMitarbeiter();
public Mitarbeiter retrieveMitarbeiter(long personalnummer);
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter);
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter);
public IDaoMitarbeiter getDaoMitarbeiter();
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter);
}
ServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
#Transactional(readOnly = true)
public class ServiceMitarbeiter implements IServiceMitarbeiter
{
IDaoMitarbeiter daoMitarbeiter;
#Transactional(readOnly = true)
public List<Mitarbeiter> retrieveAllMitarbeiter()
{
return daoMitarbeiter.getAll();
}
#Transactional(readOnly = true)
public Mitarbeiter retrieveMitarbeiter(long personalnummer)
{
return daoMitarbeiter.getByPersonalnummer(personalnummer);
}
#Transactional(readOnly = false)
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.create(mitarbeiter);
}
#Transactional(readOnly = false)
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.persistOrMerge(mitarbeiter);
}
public IDaoMitarbeiter getDaoMitarbeiter()
{
return daoMitarbeiter;
}
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter)
{
this.daoMitarbeiter = daoMitarbeiter;
}
}
I'm happy for every fast clue :) Because i got no idea anymore

With org.springframework.web.jsf.el.SpringBeanFacesELResolver your class needs to be a
simple Spring component. Remove #ManagedBean and add #Component annotations.
You've created another instance of MitarbeiterBean managed by JSF via #ManagedBean annotation and it is not the same bean that is managed by Spring so the serviceMitarbeiter field is not injected. Just forget about JSF managed beans and use Spring components in JSF.
Also replace javax.faces.bean sope annotations with Spring #Scope.
e.g. #RequestScoped -> #Scope("request")

Related

Problem with spring security and custom login

My problem is quite similar to this one (How can I do Spring Security authentication from within a JSF form), but I've tried that solution and the problem still occurs.
index.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>Info</title>
</h:head>
<h:body>
<h:form prependId="false">
<p>Usuario <h:inputText id="j_username" value="#{control.idUsuario}"/></p>
<p>Password <h:inputSecret id="j_password" value="#{control.password}"/></p>
<h:commandButton value="Entrar" action="#{control.login}" />
</h:form>
</h:body>
</html>
Control.java
#ManagedBean
#SessionScoped
public class Control implements Serializable {
private static final long serialVersionUID = 1L;
private String idUsuario;
private String password;
private UsuarioDAO usuarios;
private Usuario usuario;
public Control() {}
public String login() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext extenalContext = facesContext.getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check");
try {
dispatcher.forward((ServletRequest)
extenalContext.getRequest(), (ServletResponse)extenalContext.getResponse());
} catch (ServletException | IOException e) {
e.printStackTrace();
}
facesContext.responseComplete();
return null;
}
public String getIdUsuario() {return idUsuario;}
public void setIdUsuario(String idUsuario) {this.idUsuario = idUsuario;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
public Usuario getUsuario() {return usuario;}
public void setUsuario(Usuario usuario) {this.usuario = usuario;}
public UsuarioDAO getUsuarios() {return usuarios;}
public void setUsuarios(UsuarioDAO usuarios) {this.usuarios = usuarios;}
}
applicationContext-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http>
<intercept-url pattern="/faces/ok.xhtml" access="ROLE_ADMIN"/>
<intercept-url pattern="/faces/ko.xhtml" access="ROLE_USER"/>
<form-login
login-page="/faces/index.xhtml"
default-target-url="/login_success"
authentication-failure-url="/faces/failLogin.xhtml"
username-parameter="j_username"
password-parameter="j_password" />
<port-mappings>
<port-mapping http="8080" https="8443" /> <!-- Tomcat -->
</port-mappings>
</http>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/BUsuariosSecurity" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<authentication-manager>
<authentication-provider>
<password-encoder hash="bcrypt" />
<jdbc-user-service data-source-ref="dataSource"
authorities-by-username-query="SELECT IdUsuario, Rol FROM TUsuarios WHERE IdUsuario = ?"
users-by-username-query="SELECT IdUsuario, PwUsuario, Habilitado FROM TUsuarios WHERE IdUsuario = ?" />
</authentication-provider>
</authentication-manager>
</beans:beans>
When I try to login with a valid user, it sends me to failLogin.xhtml
My DataBase: https://gyazo.com/3997921c1c9bc2787a25c9b0ff904f4b
What's my mistake?
Any help please?
The problem was that the passwords in the DB were not well encrypted, I tried to encrypt them with another website and I went all.

Spring service not injected via #ManagedProperty

Please can you help me with this exception ? I looked in forums but I didn't find any solution.
I could not find the reason of the nullPointer !
I am working on spring, hibernate and jsf. I could neither insert the bean into database nor get the lines and print them into a dataTable.
Error :
Avertissement: #{beanMateriel.insert()}: java.lang.NullPointerException
javax.faces.FacesException: #{beanMateriel.insert()}: 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:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 35 more
Caused by: java.lang.NullPointerException
at jsf.bean.BeanMateriel.insert(BeanMateriel.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
Grave: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
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:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at jsf.bean.BeanMateriel.insert(BeanMateriel.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
faces-config.xml :
<?xml version='1.0' encoding='UTF-8'?>
<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>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<managed-bean>
<managed-bean-name>beanMateriel</managed-bean-name>
<managed-bean-class>jsf.bean.BeanMateriel</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>materielBO</property-name>
<value>#{materielBO}</value>
</managed-property>
</managed-bean>
</faces-config>
applicationContext.xml :
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"></property>
<property name="url" value="jdbc:derby://localhost:1527/InterventionsDB;create=true"></property>
<property name="username" value="omar"/>
<property name="password" value="omar"/>
</bean>
<aop:config proxy-target-class='true'/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref = "dataSource"/>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="connection.autoReconnect">true</prop>
<prop key="connection.autoReconnectForPools">true</prop>
<prop key="connection.is-connection-validation-required">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id ="materielDAO" class = "dao.ImplMateriel">
<property name ="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id ="materielBO" class = "bo.MaterielImplBO">
<property name ="materielDAO" ref="materielDAO"></property>
</bean>
</beans>
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<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>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/login.xhtml</welcome-file>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
materiel.xhtml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Fiche Materiel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
<h:body>
<h:form>
<h1 style="FONT-SIZE: xx-large; color:#8080C0;font-family:Times New Roman;"></h1>
<h:panelGrid>
<table>
<tr>
<TD>
<p:outputLabel for="codem" value="Code Matériel" />
</TD>
<td>
<p:inputText id="codem" value="#{beanMateriel.codem}" label="CodeM" required="true"></p:inputText>
</td>
</tr>
<tr><td> <p:outputLabel for="libelle" value="Libellé" /></td>
<td><p:inputText id="libelle" value="#{beanMateriel.libelle}" required="true" label="Libelle"></p:inputText></td></tr>
<tr><td> <p:outputLabel for="datemiseenservice" value="Date Mise en Service" /></td>
<td> <p:calendar id="datemiseenservice" value="#{calendarView.date2}" required="true" label="datemiseenservice"/></td></tr>
<tr><td> <p:outputLabel for="marque" value="Marque" /></td>
<td><p:inputText id="marque" value="#{beanMateriel.marque}" required="true" label="marque"></p:inputText></td></tr>
<tr><td> <p:outputLabel for="departement" value="Département" /></td>
<td> <p:inputText id="departement" value="#{beanMateriel.departement}" required="true" label="departement"></p:inputText></td></tr>
<tr>
<td></td>
<td><p:commandButton value="Valider" type="submit" icon="ui-icon-check" action="#{beanMateriel.insert()}" readonly="false"/></td>
</tr>
</table>
</h:panelGrid>
<p:dataTable id="table" value="#{beanMateriel.liste}" var="obj">
<p:column headerText="Code">
<h:outputText value="#{obj.codem}"></h:outputText>
</p:column>
<p:column headerText="Libelle">
<h:outputText value="#{obj.libelle}"></h:outputText>
</p:column>
<p:column headerText="Marque">
<h:outputText value="#{obj.marque}"></h:outputText>
</p:column>
<p:column headerText="Date mise en service">
<h:outputText value="#{obj.datemiseenservice}"></h:outputText>
</p:column>
<p:column headerText="Département">
<h:outputText value="#{obj.departement}"></h:outputText>
</p:column>
<p:column headerText="modifier">
<p:commandButton icon="ui-icon-star" title="Icon Only" action="#{beanMateriel.update()}" immediate="true">
</p:commandButton>
</p:column>
<p:column headerText="supprimer">
<p:commandButton icon="ui-icon-star" title="Icon Only" action="#{beanMateriel.delete()}" immediate="true">
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
BeanMateriel.java:
#ManagedBean(name="beanMateriel")
public class BeanMateriel implements Serializable{
private int codem;
private String libelle;
private String marque;
private String datemiseenservice;
private String departement;
private List<BeanMateriel> liste;
#ManagedProperty(value = "#{materielBO}")
private MaterielImplBO materielBO;
public BeanMateriel() {
}
/**
* #return the materielBO
*/
public MaterielImplBO getMaterielBO() {
return materielBO;
}
/**
* #param materielBO the materielBO to set
*/
public void setMaterielBO(MaterielImplBO materielBO) {
this.materielBO = materielBO;
}
public List<BeanMateriel> getListe() {
return liste;
}
public void setListe(List<BeanMateriel> liste) {
this.liste = liste;
}
public BeanMateriel(int codem, String libelle, String marque, String datemiseenservice, String departement, MaterielImplBO materielBO, List<BeanMateriel> liste) {
this.codem = codem;
this.libelle = libelle;
this.marque = marque;
this.datemiseenservice = datemiseenservice;
this.departement = departement;
this.materielBO = materielBO;
this.liste = liste;
}
public int getCodem() {
return codem;
}
public void setCodem(int codem) {
this.codem = codem;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getMarque() {
return marque;
}
public void setMarque(String marque) {
this.marque = marque;
}
public String getDatemiseenservice() {
return datemiseenservice;
}
public void setDatemiseenservice(String datemiseenservice) {
this.datemiseenservice = datemiseenservice;
}
public String getDepartement() {
return departement;
}
public void setDepartement(String departement) {
this.departement = departement;
}
public String insert() {
materielBO.insert(this);
getAll();
return "";
}
public String delete() {
materielBO.delete(this);
getAll();
return "";
}
public String update() {
materielBO.update(this);
getAll();
return "";
}
public void getAll() {
setListe(materielBO.getAll());
}
}
ImplMateriel.java :
public class ImplMateriel extends HibernateDaoSupport implements IfaceMateriel {
#Autowired
public SessionFactory sessionFactory;
#Override
#Transactional
public void insert(Materiel obj) {
getHibernateTemplate().save(obj);
}
#Override
public void delete(Materiel obj) {
getHibernateTemplate().delete(obj);}
#Override
public void update(Materiel obj) {
getHibernateTemplate().merge(obj);
}
#Override
#Transactional
public List<Materiel> getAll() {
return (List<Materiel>) (Object)getHibernateTemplate().find("from Materiel"); }
}
MaterielImplBO.java :
public class MaterielImplBO implements MaterielBO {
private ImplMateriel materielDAO;
public ImplMateriel getMaterielDAO() {
return materielDAO;
}
public void setMaterielDAO(ImplMateriel materielDAO) {
this.materielDAO = materielDAO;
}
#Override
public void insert(BeanMateriel obj) {
Materiel materiel = new Materiel();
materiel.setCodem(obj.getCodem());
materiel.setDatemiseenservice(obj.getDatemiseenservice());
materiel.setDepartement(obj.getDepartement());
materiel.setLibelle(obj.getLibelle());
materiel.setMarque(obj.getMarque());
materielDAO.insert(materiel);
}
#Override
public void delete(BeanMateriel obj) {
Materiel materiel = new Materiel();
materiel.setCodem(obj.getCodem());
materielDAO.delete(materiel);
}
#Override
public void update(BeanMateriel obj) {
Materiel materiel = new Materiel();
materiel.setCodem(obj.getCodem());
materiel.setDatemiseenservice(obj.getDatemiseenservice());
materiel.setDepartement(obj.getDepartement());
materiel.setLibelle(obj.getLibelle());
materiel.setMarque(obj.getMarque());
materielDAO.update(materiel);
}
#Override
public List<BeanMateriel> getAll() {
List<BeanMateriel> liste = new ArrayList<BeanMateriel>();
for (Materiel obj: materielDAO.getAll())
{
BeanMateriel bean = new BeanMateriel();
bean.setCodem(obj.getCodem());
bean.setDatemiseenservice(obj.getDatemiseenservice());
bean.setDepartement(obj.getDepartement());
bean.setLibelle(obj.getLibelle());
bean.setMarque(obj.getMarque());
liste.add(bean);
}
return liste;
}
}

java.lang.ClassCastException: while typecasting the command object in onSubmit method

I am beginner in spring3 so i am creating a simple login application. In my loginController i am getting "java.lang.ClassCastException: org.springframework.web.bind.support.SimpleSessionStatus cannot be cast to com.forms.LoginForm" on the following line
LoginForm login = (LoginForm)command;
For the reference code is as follows:
LoginController.java:-
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.Dao.LoginDaoUtil;
import com.forms.LoginForm;
#SuppressWarnings("deprecation")
#Controller
public class LoginController extends SimpleFormController {
public LoginController() {
setCommandClass(LoginForm.class);
}
#RequestMapping("/LoginAction")
protected ModelAndView onSubmit(Object command) {
try {
LoginForm login = (LoginForm) command;
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"SpringBlogger-servlet.xml");
LoginDaoUtil daoUtil = ctx.getBean("LoginDaoUtil",
LoginDaoUtil.class);
boolean isUserValid = daoUtil.isValidUser(login.getUsername(),
login.getPassword());
if (isUserValid)
return new ModelAndView("success").addObject("name",
login.getUsername());
else
return new ModelAndView("login", "loginForm", new LoginForm());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ModelAndView("login", "loginForm", new LoginForm());
}
}
}
login.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${message}</h1>
<form:form action="LoginAction" method="post" commandName="loginForm">
Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>
Password:<form:password path="password"/>
<font color="red"><form:errors path="password"/></font><br/><br/>
<input type="submit" value="submit">
</form:form>
</body>
</html>
LoginForm.java:-
package com.forms;
public class LoginForm {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HomeController.java:-
package com.beans;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.forms.LoginForm;
#Controller
public class HomeController {
#RequestMapping({"/","/home"})
public String showHomePage(ModelMap map){
map.addAttribute("message", "Welcome to Spring Blogger");
map.addAttribute("loginForm", new LoginForm());
return "login";
}
}
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>SpringBlogger</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringBlogger</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringBlogger</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringBlogger-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.beans" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/springblogger"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
Please help.
Thanks,
Manish
You cannot use Object type to bind your form, use its type instead decoreated with #ModelAttribute1
#RequestMapping("/LoginAction")
public ModelAndView onSubmit(#ModelAttribute("loginForm") LoginForm command) {
Also I saw you're trying to create a new application context inside the controller which seem unecessary, use dependency injection / autowiring instead to your controller class

Spring security login controller methods

I searched some examples but i couldn't found any example. What I must do in loginController.login() method. How can I pass username and password text to spring-security?
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.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/pages/login.xhtml*" access="permitAll"/>
<intercept-url pattern="/**" access="hasRole('admin')" />
<form-login login-page='/pages/login.xhtml' default-target-url="/pages/index.xhtml"
authentication-failure-url="/pages/login.xhtml"/>
<logout logout-success-url="/pages/logout.xhtml" />
</http>
<!--Authentication Manager Details -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
My view login.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"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>User Login</title>
</h:head>
<h:body>
<h:form id="loginFormId">
<p:outputPanel id="loginOutputPanelId">
<p:panelGrid id="loginInformationPanel" columns="2">
<h:outputText value="Username: "/>
<p:inputText value="#{loginController.userName}"/>
<h:outputText value="Password: "/>
<p:inputText value="#{loginController.password}"/>
</p:panelGrid>
<p:commandButton value="Login" actionListener="#{loginController.login()}"/>
</p:outputPanel>
</h:form>
</h:body>
Personally I use this way to set Spring-Security context values:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
//....
//In your login method:
List<Authority> auths = new ArrayList<Authority>();
auths.add(new Authority("ROLE_USER")); //Role here, like "admin"
Authentication authentication = new UsernamePasswordAuthenticationToken(token, null, auths);
SecurityContextHolder.getContext().setAuthentication(authentication);
The Authority class is as follow:
import org.springframework.security.core.GrantedAuthority;
public class Authority implements GrantedAuthority{
private static final long serialVersionUID = 9170140593525051237L;
private String authority;
public Authority(String authority) {
super();
this.authority = authority;
}
#Override
public String getAuthority() {
return authority;
}
#Override
public String toString() {
return "Authority [authority=" + authority + "]";
}
}
I hope this helps
You can you Pricipal object to get the user details as shown below.
login(Principal principal){
if (principal instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken userDetails = (UsernamePasswordAuthenticationToken) principal;
userDetails.getName();
}

Request processing failed; nested exception is java.lang.NullPointerException

i created a form and on post i want to save those values to the database and show the saved values on the page.
i am new to spring mvc and hence i am not understanding where i am going wrong.
Here is the StackTrace -
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.projects.data.HomeController.addCustomer(HomeController.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the VMware vFabric tc Runtime 2.7.2.RELEASE/7.0.30.A.RELEASE logs.
Model class
package com.projects.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
int custid;
String name;
int age;
public Customer()
{}
public Customer(int custid,String name,int age)
{
this.custid=custid;
this.name=name;
this.age=age;
}
//Getters And Setters
public int getCustid() {
return custid;
}
public void setCustid(int custid) {
this.custid = custid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Dao Class
package com.projects.model;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.projects.model.Customer;
#Repository
public class CustomerDao {
#Autowired
private SessionFactory sessionfactory;
public SessionFactory getSessionfactory() {
return sessionfactory;
}
public void setSessionfactory(SessionFactory sessionfactory) {
this.sessionfactory = sessionfactory;
}
public int save(Customer customer)
{
return (Integer) sessionfactory.getCurrentSession().save(customer);
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.projects.model" />
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/customerdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="com.projects.model" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
</beans:beans>
Controller class
package com.projects.model;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.projects.model.CustomerDao;
import com.projects.model.Customer;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
private CustomerDao dao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Customer customer=new Customer();
model.addAttribute(customer);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer, ModelMap model) {
model.addAttribute("custid", customer.getCustid());
model.addAttribute("name",customer.getName());
model.addAttribute("age", customer.getAge());
dao.save(customer);
return "customer/customer";
}
}
View Files
//home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
//customer.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Cust id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
After i click the save button i get the above mentioned error.Please help me resolve this.
Seems to be a problem in your form. At least, the inputs must be given the name attributes:
<form method="post" action="<c:url value='/customer/'/>">
Cust_Id :
<input type="text" name="custid">
<br>
Name :
<input type="text" name="name">
<br>
Age :
<input type="text" name="age">
<input type="submit" value="Save">
</form>
But since you are using Spring, it is preferable to use the Spring forms (and spring url's also):
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer">
<form:label path="custid">Id:</form:label>
<form:input path="custId"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
Edit
And you should initialize dao!
#Autowired
private CustomerDao dao;
The attribute of your model has annotated with #ModelAttribute to be nulleable. This is so that when an exception occurs in times of bind there is something to return.
Note the difference between the model attribute and the model attribute parameter.
An exception during bind and validation times could be passing text in an integer field.
Exception:
org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is java.lang.NullPointerException:
Parameter specified as non-null is null: method yourMethod, parameter yourParam
In Kotlin
Going from student: Student to student: Student? exception is avoided.
#RequestMapping("/processFormRegister")
fun processFormRegister(
#Valid #ModelAttribute("firstStudent") student: Student?,
validationResult: BindingResult
): String {
return if (validationResult.hasErrors()) {
"StudentFormRegister"
} else {
"ResultFormRegister"
}
}
And also to see the exception transformed into a validation you could use #Valid and Binding Result of Hibernate Validator obtaining:
failed to convert value of type java.lang.string[] to required type java.lang.integer; nested exception is java.lang.numberformatexception: for input string: "a"
GL

Resources