JSF 2.1 Spring 3.0 Integration - java

I'm trying to make very simple Spring 3 + JSF2.1 integration according to examples I googled in the web.
So here is my code:
My HTML submitted to actionController.actionSubmitted() method:
<h:form>
<h:message for="textPanel" style="color:red;" />
<h:panelGrid columns="3" rows="5" id="textPanel">
//all my bean prperties mapped to HTML code.
</h:panelGrid>
<h:commandButton value="Submit" action="#{actionController.actionSubmitted}" />
</h:form>
now the Action Controller itself:
#ManagedBean(name="actionController")
#SessionScoped
public class ActionController implements Serializable{
#ManagedProperty(value="#{user}")
User user;
#ManagedProperty(value="#{mailService}")
MailService mailService;
public void setMailService(MailService mailService) {
this.mailService = mailService;
}
public void setUser(User user) {
this.user = user;
}
private static final long serialVersionUID = 1L;
public ActionController() {}
public String actionSubmitted(){
System.out.println(user.getEmail());
mailService.sendUserMail(user);
return "success";
}
}
Now my bean Spring:
public interface MailService {
void sendUserMail(User user);
}
public class MailServiceImpl implements MailService{
#Override
public void sendUserMail(User user) {
System.out.println("Mail to "+user.getEmail()+" sent." );
}
}
This is my web.xml
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
my applicationContext.xml
<beans xmlns="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">
<bean id="mailService" class="com.vanilla.jsf.services.MailServiceImpl">
</bean>
</beans>
my faces-config.xml is the following:
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
<message-bundle>
com.vanilla.jsf.validators.MyMessages
</message-bundle>
</application>
<managed-bean>
<managed-bean-name>actionController</managed-bean-name>
<managed-bean-class>com.vanilla.jsf.controllers.ActionController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>mailService</property-name>
<value>#{mailService}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<from-view-id>index.xhtml</from-view-id>
<navigation-case>
<from-action>#{actionController.actionSubmitted}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>submitted.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
My Problem is that I'm getting NullPointerException because my mailService Spring bean is null.
public String actionSubmitted(){
System.out.println(user.getEmail());
//mailService is null Getting NullPointerException
mailService.sendUserMail(user);
return "success";
}

I added getter for mail servie and the problem was solved. I do't know why this getter is required, but it works.

Related

WebSphere Liberty JSR-250 implementation (RolesAllowed)

In order to use the security annotations of JSR-250 (RolesAllowed, PermitAll, DenyAll):
In Jersey, you would register the RolesAllowedDynamicFeature class.
In RESTeasy, you would use the web.xml config:
<context-param>
<param-name>resteasy.role.based.security</param-name>
<param-value>true</param-value>
</context-param>
Both of these rely on the implementation of SecurityContext.isUserInRole(), but it seems that WebSphere Liberty Profile does not.
How do we get this to work in WebSphere Liberty Profile (WLP)?
I used a minimal example:
Create a resource class/method with #RolesAllowed:
#Path("/rest")
public class HelloWorld {
#GET
#RolesAllowed("ANYTHING")
public Response hello() {
return Response.ok("Hello World").build();
}
}
Set your SecurityContextImpl in a filter, overriding isUserInRole() to always returns true;
Enable "role-based security" for the JAX-RS implementation. (Jersey or RESTeasy, etc as above. For WLP, I had to add the appSecurity-2.0 feature)
And you should have a working example.
However, it appears that WebSphere Liberty Profile returns 403 Forbidden even though isUserInRole returns true.
Does anyone know how to properly use the #RolesAllowed annotation in Liberty and what I might be missing?
Code
#ApplicationPath("/")
public class MyApplication extends Application {
public MyApplication() {}
}
#Provider
#Priority(Priorities.AUTHENTICATION)
public class AuthFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext ctx) throws IOException {
System.out.println("Setting SecurityContext..");
ctx.setSecurityContext(new MySecurityContext("someuser", "anyrole"));
}
}
public class MySecurityContext implements SecurityContext {
private String user;
private String role;
public static class MyPrincipal implements Principal {
private String name;
public MyPrincipal(String name) { this.name = name; }
#Override public String getName() { return name; }
}
public MySecurityContext(String user, String role) {
this.user = user;
this.role = role;
}
#Override public String getAuthenticationScheme() { return "BASIC"; }
#Override public Principal getUserPrincipal() { return new MyPrincipal(user); }
#Override public boolean isSecure() { return true; }
#Override
public boolean isUserInRole(String role) {
return true;
}
}
#Path("/test")
public class HelloWorld {
#GET
#RolesAllowed("doesntmatter")
public Response hello() {
return Response.ok("Hello World").build();
}
}
pom.xml (dependencies only)
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
server.xml
Code works with the appSecurity feature disabled. Does not work with it enabled.
<server description="test">
<featureManager>
<feature>jaxrs-2.0</feature>
<feature>localConnector-1.0</feature>
<!-- <feature>appSecurity-2.0</feature> -->
</featureManager>
<webApplication id="RoleTest" location="RoleTest.war" name="RoleTest"/>
<httpEndpoint httpPort="9081" httpsPort="9444" id="defaultHttpEndpoint"/>
<!-- below lines are required when appSecurity feature is loaded -->
<!--
<keyStore id="defaultKeyStore" password="{xor}Lz4sLCgwLTtu"/>
<basicRegistry id="basic" realm="BasicRegistry">
<user name="username" password="password" />
</basicRegistry>
-->
</server>
May be you can try this:
1 server.xml
<server description="test">
<featureManager>
<feature>jaxrs-2.0</feature>
<feature>appSecurity-2.0</feature>
</featureManager>
<webApplication id="RoleTest" location="RoleTest.war" name="RoleTest">
<application-bnd>
<security-role name="ANYTHING">
<user name="username" />
</security-role>
<security-role name="AuthenticationRole">
<user name="username" />
</security-role>
<security-role name="AllAuthenticated">
<special-subject type="ALL_AUTHENTICATED_USERS" />
</security-role>
</application-bnd>
</webApplication>
<httpEndpoint httpPort="9081" httpsPort="9444" id="defaultHttpEndpoint" />
<basicRegistry id="basic" realm="BasicRegistry">
<user name="username" password="password" />
</basicRegistry>
</server>
2 Java Code
Create a MyApplication class and a resource class/method with #RolesAllowed:
#ApplicationPath("/")
public class MyApplication extends Application {
public MyApplication() {}
public Set<Class<?>> getClasses(){
Set<Class<?>> classes = new HashSet();
classes.add(HelloWorld.class);
return classes;
}
}
#Path("/rest")
public class HelloWorld {
#GET
#RolesAllowed("ANYTHING")
public Response hello() {
return Response.ok("Hello World").build();
}
}
3 web.xml
<web-app 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 web-app_3_0.xsd"
version="3.0">
<display-name>Test Application</display-name>
<description>blablabla</description>
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
<init-param>
<param-name>requestProcessorAttribute</param-name>
<param-value>requestProcessorAttribute_webcontainer</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>com.xxx.MyApplication</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SecurityContextApp</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>com.xxx.MyApplication</servlet-name>
<url-pattern>/xxx/*</url-pattern>
</servlet-mapping>
<security-constraint id="SecurityConstraint_2">
<web-resource-collection id="WebResourceCollection_2">
<web-resource-name>com.xxx.MyApplication
</web-resource-name>
<description>Protection area for Rest Servlet</description>
<url-pattern>/xxx/rest</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<user-data-constraint id="UserDataConstraint_2">
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
<auth-constraint id="AuthConstraint_2">
<role-name>AuthenticationRole</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>
<security-role id="SecurityRole_1">
<description>blabla</description>
<role-name>ANYTHING</role-name>
</security-role>
<security-role id="SecurityRole_2">
<role-name>AuthenticationRole</role-name>
</security-role>
</web-app>
Any other issues, leave me a message.

Spring don't see controller

I have a problem with my spring MVC app. My app don't see my controller when i try to pass data between spring controller and angular controller.
Spring configuration:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>PiManager</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
dispatcher-servlet.xml
<?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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
<mvc:annotation-driven />
<context:component-scan base-package="org.inz.controller" />
<jpa:repositories base-package="org.inz.repositories"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
My services.js
PiManager.services.main = [ '$http', '$rootScope', '$state', function($http, $rootScope, $state) {
var self = this;
self.getTestEntity = function(id) {
return $http.get("/PiManager/index/"+id);
}
} ];
app.service('mainService', PiManager.services.main);
My controller.js
"use strict"
PiManager.controllers = {};
PiManager.controllers.main =
['mainService', '$scope', '$state', '$http', function(mainService, $scope, $state, $http) {
$scope.getTest = function(id) {
mainService.getTestEntity(id).then(function(response) {
$scope.testEntityPart = response;
});
}
}];
app.controller('mainController', PiManager.controllers.main);
My spring MainController
#Controller
#RequestMapping("/PiManager/")
public class MainController {
#Autowired
private TestEntityRepository testEntityRepository;
#RequestMapping(value = "/main")
public String index() {
return "/index.jsp";
}
#ResponseBody
#RequestMapping(value = "/index/{id}", method = RequestMethod.GET)
public List<TestEntity> getTestEntity(#PathVariable("id") Long id) {
return testEntityRepository.findById(id);
}
}
So when i type http://localhost:8080/PiManager/index/1 I got
GET http://localhost:8080/PiManager/index/1 404 (Not Found)
And i don't realy know what to do to make it work.
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

No bean named 'CustomAuthenticationProvider' is defined

I am trying to switch from a working jdbc-user-service to a customAuthenticationProvider which implements AuthenticationProvider, however spring is not finding it. I'm not sure if it has to do with something about having my configurations in xml or what is wrong. I started out with one in my dispatcher servlet however on advice from things that I read I added one to my spring-security.xml as well which didn't make any difference. Any ideas what is wrong with my configuration?
Thanks!
mvc-dispatch-servlet.xml
<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/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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mkyong.*" />
<!-- Currently not working. Made a work around by having resources at /resources and pages at /pages -->
<mvc:resources location="/resources/" mapping="/resources/" />
<!-- also add the following beans to get rid of some exceptions -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"><value>/WEB-INF/pages/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
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>
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<!-- login page must be available to all. The order matters, if this is after something which secures the page this will fail. -->
<intercept-url pattern="/pages/login" access="permitAll" />
<intercept-url pattern="/pages/admin/**" access="hasRole('_admin')" />
<intercept-url pattern="/pages/trade/**" access="hasRole('_trader')" />
<intercept-url pattern="/pages/discover/**" access="hasRole('_users')" />
<!-- access denied page -->
<access-denied-handler error-page="/pages/403" />
<form-login
login-page="/pages/login"
default-target-url="/pages/trade/index"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-url="/pages/logout" logout-success-url="/pages/login?logout" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Select users and user_roles from database -->
<authentication-manager>
<authentication-provider ref="CustomAuthenticationProvider"/>
<!--<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select email,pwhash, enabled from users where email=?"
authorities-by-username-query=
"select email, groupname from usergroups where email =? " />
</authentication-provider> -->
</authentication-manager>
</beans:beans>
CustomAuthenticationProvider.java
package com.mkyong.web.controller;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user = new User();
user.name = authentication.getName();
user.password = authentication.getCredentials().toString();
try {
user.id = Instance.users.getUserByEmail(user.name).getUserID();
} catch (Exception e) {
Instance.debug("CustomAuthenticationProvider authenticate","Error getting user" + e);
}
// use the credentials to try to authenticate against the third party system
if (passVerify(user)) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
try {
UserRoles roles = Instance.users.getUser(user.id).roles;
userRolesToDatabaseRoles(roles, grantedAuths);
} catch (Exception e) {
Instance.debug("CustomAuthenticationProvider authenticate","Error getting user" + e);
}
return new UsernamePasswordAuthenticationToken(user.name, user.password, grantedAuths);
} else {
Instance.debug("CustomAuthenticationProvider authenticate","Unable to authenticate");
return null;
}
}
private void userRolesToDatabaseRoles(UserRoles roles, List<GrantedAuthority> grantedAuths) {
if(roles.admin){
grantedAuths.add(new SimpleGrantedAuthority("_admin"));
}
if(roles.trader){
grantedAuths.add(new SimpleGrantedAuthority("_trader"));
}
if(roles.analyst){
grantedAuths.add(new SimpleGrantedAuthority("_users"));
}
}
private boolean passVerify(User user) {
StringBuffer MD5 = getMD5(user);
try {
//User still has an MD5 password, so change them over to bcrypt
if(MD5.toString().equals(Instance.users.getPasswordHash(user.name))){
String hashedPassword = getBcrypt(user).toString();
instance.users.changePassword(user.id, hashedPassword);
return true;
}
} catch (Exception e) {
instance.debug("CustomAuthenticationProvider passVerify","Error getting userpassword" + e);
}
StringBuffer bcrypt = getBcrypt(user);
if(bcrypt.toString().equals(user.password)){
return true;
}
return false;
}
public StringBuffer getBcrypt(User user) {
//This sets how many rounds bcrypt will run. The high the number the longer it takes which will slow down user login, however it also slows
//down a would be attacker. This is a key advantage of bcrypt over other algorithms. *IMPORTANT* changing the strength will result in needing to
//rehash all passwords. This is very doable but requires more work.
//See http://crypto.stackexchange.com/questions/3003/do-i-have-to-recompute-all-hashes-if-i-change-the-work-factor-in-bcrypt
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);
StringBuffer hashedPassword = new StringBuffer();
hashedPassword.append(passwordEncoder.encode(user.password));
return hashedPassword;
}
public StringBuffer getMD5(User user) {
StringBuffer sb = null;
MessageDigest md;
String original = "a";
try {
md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
} catch (NoSuchAlgorithmException e) {
instance.debug("CustomAuthenticationProvider hashMD5","Error getting MD5 instance" + e);
}
return sb;
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public class User{
public long id;
protected String name, password;
}
}
Not sure if web.xml is necessary to post but here it is:
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>servletInitServlet</servlet-class>
<init-param>
<param-name>configfile</param-name>
<param-value>C:/transmetric/dev/java/WebContent/WEB-INF/config.properties</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>servlet.admin</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>servlet.user</servlet-class>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet>
<servlet-name>SignupUserServlet</servlet-name>
<servlet-class>servlet.user.SignupUserServlet</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet>
<servlet-name>ReceiveFile</servlet-name>
<servlet-class>servlet.user</servlet-class>
<load-on-startup>6</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/pages/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/AdminServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SignupUserServlet</servlet-name>
<url-pattern>/SignupUserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ReceiveFile</servlet-name>
<url-pattern>/ReceiveFile</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,
/WEB-INF/spring-database.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>
Try defining your CustomAuthenticationProvider bean in spring-security xml instead of using #Component annotation.
Or you can also try to put <context:component-scan base-package="com.mkyong.*" /> in your security xml
Change
<authentication-provider ref="CustomAuthenticationProvider"/>
to (not the uncapitalized bean name)
<authentication-provider ref="customAuthenticationProvider"/>
By default, the bean names for autodetected components annotated with #Component is the uncapitalized non-qualified class name. In your case this will be customAuthenticationProvider.
In my case an exception was caused by actually missing .class files due to bad Maven build:
(YourApp)/target/classes
(YourApp)/target/(YourApp).war/WEB-INF/classes/
(YourApp)/target/(YourApp).war/WEB-INF/lib/
The root cause was Eclipse problem: it switched to use embedded Maven while I always use external one. To fix it I had to:
Preferences > Maven > Installations, setup external Maven
Delete project from workspace
Delete all derived files/folders in project folder (target/, bin/, .settings/, .classpath & .project), leave only pom.xml and src/.
File > Import... > Existing Maven Projects, select my project.
Once rebuilt, all required classes were there.

managed bean field is null when invoke bean method primefaces jsf

I am developing a primefaces - spring framework application but i have a big problem with my beans
i'm using spring annotations in java code to discover my beans, services, or component
but the problem is when i start jboss 7.1 AS and the beans are created i can see that my bean ListUsersBean
is created succesfully and the autowired setters are set successfully, but after when i try to invoke a test() method
from jsf page the autowired attributes are null.
I dont know what is happening
thanks a lot if anyone may help me
i'm using
spring-framework 3.2.2
JBOSS AS 7.1
primefaces 3.5
this is my bean
package edu.unbosque.beans;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedProperty;
import edu.unbosque.model.User;
import edu.unbosque.services.IUserService;
import edu.unbosque.services.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#ManagedBean
#SessionScoped
public class ListUsersBean implements Serializable{
/**
* Acceso A Datos De Usuario
*/
private IUserService userService;
private TestService testService;
/**
* Listado De Usuarios
*/
private List<User> usersList;
/**
* Usuario Seleccionado
*/
private User selectedUser;
/**
* Carga Los Usuarios
*/
private void populateUsers(){
this.usersList = this.userService.getUsers();
}
public IUserService getUserService() {
return userService;
}
#Autowired(required = true)
#Qualifier("userServiceImpl")
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public TestService getTestService() {
return testService;
}
#Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
public void test(){
this.testService = this.getTestService();
int i = 1;
i = i + 2;
}
}
this is my service
package edu.unbosque.services;
import java.util.List;
import javax.faces.bean.ManagedProperty;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import edu.unbosque.*;
import edu.unbosque.dao.UserDao;
import edu.unbosque.model.User;
import javax.inject.Named;
#Named("userServiceImpl")
public class UserServiceImpl implements IUserService{
#Autowired
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return (UserDetails) userDao.getUserByUserName(username);
}
#Override
public List<User> getUsers() {
return getUserDao().getUsers();
}
}
config files
faces-config.xml
*
<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>
<lifecycle>
<phase-listener>edu.unbosque.listeners.LoginPhaseListener</phase-listener>
</lifecycle>
</faces-config>
*
spring-database.xml
<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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="edu.unbosque.model" />
<context:component-scan base-package="edu.unbosque.dao" />
<context:component-scan base-package="edu.unbosque.services" />
<context:component-scan base-package="edu.unbosque.beans" />
<context:property-placeholder location="classpath:jdbc.properties" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>edu.unbosque.model.User</value>
<value>edu.unbosque.model.Authority</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<display-name>Semilleros Universidad El Bosque</display-name>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<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>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
The problem is you are mixing up jsf, CDI and spring annotations. Use #Component in your class UserServiceImpl. Because if you use #Named, the created bean's life cycle will be managed by CDI, because its a CDi annotation. So as you are using #Autowired annotation to inject the bean, which is unknown to Spring, will get null. So as you are using #Autowired while injecting the bean, the injecting bean must be in spring managed context and to do that you should have use #Component. For further reading you can see this nice tutorial.

Spring with FreeMarker: Could not resolve view with name 'Home' in servlet with name 'MyServlet'

I am trying to create a very simple integration of FreeMarker and Spring. However, when I run my example, I get an exception:
GRAVE: Servlet.service() for servlet MyServlet threw exception
javax.servlet.ServletException: Could not resolve view with name 'Home' in servlet with name 'MyServlet'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1162)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
I don't know what's wrong with my configuration:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.jverstry.Configuration</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
</web-app>
Web Configuration
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".ftl");
return resolver;
}
#Bean
public FreeMarkerConfigurer getFreemarkerConfig() {
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
result.setTemplateLoaderPath("WEB-INF/pages/");
return result;
}
}
Controller
#Controller
public class MyController {
#RequestMapping(value = "/")
public String home(#ModelAttribute("model") ModelMap model) {
model.addAttribute("MsTime", System.currentTimeMillis());
return "Home";
}
}
P.S.: Of course, there is a Home.ftl file in WEB-INF/pages/.
After searching a lot, not setting a prefix solved the issue:
#Bean
public ViewResolver getViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(false);
// resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
configuration for the freemaker (found in the spring reference documentation)
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/#view-velocity
<!-- freemarker config -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
</bean>
<!--
View resolvers can also be configured with ResourceBundles or XML files. If you need
different view resolving based on Locale, you have to use the resource bundle resolver.
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".ftl"/>
</bean>
and java config version would be :
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
#Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
result.setTemplateLoaderPath("/WEB-INF/pages/");
return result;
}
}

Categories

Resources