Unable to enable logging using CustomizableTraceInterceptor in Spring 3.0.6 - spring

I have a very simple setup
I have an applicationContext.xml file like this :
<context:component-scan base-package="com.mkyong.common.controller" />
<bean id="customizableTraceInterceptor"
class="org.springframework.aop.interceptor.CustomizableTraceInterceptor">
<property name="enterMessage" value="Entering $[methodName]($[arguments])" />
<property name="exitMessage" value="Leaving $[methodName](): $[returnValue]" />
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<!-- <property name="proxyTargetClass" value="true" /> -->
<property name="interceptorNames">
<list>
<value>customizableTraceInterceptor</value>
</list>
</property>
</bean>
<mvc:annotation-driven />
<bean id="wowService" class="org.daud.WowService" scope="prototype" />
</beans>
The controller class is also very simple :
#Controller
#RequestMapping("/welcome")
public class HelloController {
#Autowired
private WowService wowService;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
getWowService().printIt();
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
public WowService getWowService() {
return wowService;
}
public void setWowService(WowService wowService) {
this.wowService = wowService;
}
}
The web.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>simple-form</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>simple-form</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>simple-form</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
WowService is also very simple
public class WowService {
public String printIt() {
return "daud";
}
}
I have the spring jars of version 3.0.6, aopalliance-1.0.jar and commons-logging-1.1.1.jar in my lib folder and nothing else. But there is no trace being recorded.. i.e there is no logging being done when we enter the method of WowService, or when we leave it. I can't figure out why.

The following line:
new WowService().printIt();
does not create object managed by container (Spring) and definition of your bean is not taken into consideration.
The bean definition:
<bean id="wowService" class="org.daud.WowService" scope="prototype" />
looks fine, but you're not using it.
Change your controller to:
#Controller
#RequestMapping("/welcome")
public class HelloController {
#Autowired
WowService wowService;
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
wowService.printIt();
model.addAttribute("message", "Spring 3 MVC Hello World");
return "hello";
}
}

Related

Correct way for declaring beans in spring MVC?

I created a project named "Testing" using maven in eclipse j2ee. I created a web.xml file in WEB-INF folder as follows :
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</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>
And this is my dispatcher servlet that i placed withing WEB-INF folder.
dispatcher-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"
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">
<context:component-scan base-package="com.spring.trial" />
<context:property-placeholder location="classpath:jdbc.properties" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Employee DB data source. -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.employee_db_url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
<property name="idleConnectionTestPeriod" value="200" />
<property name="loginTimeout" value="300" />
<property name="maxIdleTime" value="2700"></property>
<property name="testConnectionOnCheckin" value="true" />
<property name="maxIdleTimeExcessConnections" value="60"></property>
</bean>
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
scope="singleton">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="categories" class="com.spring.trial.access.Categories"></bean>
I have a controller called helloworldcontroller as follows
package com.spring.trial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.spring.trial.access.Categories;
#Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
#Autowired
Categories categories;
#RequestMapping("/hello")
public ModelAndView showMessage(
#RequestParam(value = "name", required = false, defaultValue = "World") String name) {
System.out.println("in controller");
ModelAndView mv = new ModelAndView("helloworld");
mv.addObject("message", message);
mv.addObject("name", name);
return mv;
}
}
Okay now for the triky part....
1)i went through various tutorials online and in some sites the web.xml file has context params that pass the dispatcher-servlet to the context loader class. Does this mean that all the beans in the dispatcher servlet be initialised and autowired . And does it mean that the dispatcher servlet context is now the root application context??
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<!-- this class is responsible for auto-wiring all the beans together in
spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In some sites the web.xml file is intialised as follows:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
</param-value>
</context-param>
<!-- Configurations for the DispatcherServlet application context (child context) -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-mvc-servlet.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/admin/*</url-pattern>
</servlet-mapping>
2) so again what is happening in this web.xml file?? is it loading 2 different contexts one for root and the other for dispatcher servlet??
and in case 2 they hace application-context.xml so on a jsp page i can easily retrieve a bean using
applicationContext context = new classpathxmlapplicationcontext("application-context.xml);
myclass mclass = (myclass)context.getbean("mclassname");
but in case I(first web.xml file that i posted on top) i dont have any application context so how am i supposed to retrive bean on my jsp page?? I just have the dispatcher and all the beans are declared in the dispatcher. please help me i am so confused ryt now.....

Transaction control in a JSF Spring 3 project

i got a problem in my project using JSF 2.0 with Primefaces, Spring 3 and Hibernate.
I was able to configure the whole project correctly and been able to use springĀ“s dependency injection and transaction control just fine along with JSF views, service(interface and impl), DAO(interface and impl).
But whenever I try to list or delete objects of a certain model it duplicates the current objects that is in the model table.
Anyone had this problem before?
PS: Im annotating my controller class with #Component("myBeanName"), so my jsf view can understand the bean name to call methods and use objects.
Here is the applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="br.com.dentrio" />
<context:annotation-config />
<context:spring-configured />
<!-- Data Source Declaration -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/dentriodb" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="packagesToScan"> <list> <value>net.javabeat.spring.model</value>
</list> </property> -->
<property name="packagesToScan" value="br.com.dentrio.model"></property>
<!-- <property name="annotatedClasses"> -->
<!-- <list> -->
<!-- <value>net.javabeat.spring.model.*</value> -->
<!-- </list> -->
<!-- </property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- Transaction Manager is defined -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
My faces-config.xml file
<?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>
<locale-config>
<default-locale>pt_BR</default-locale>
</locale-config>
</application>
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<application>
<message-bundle>
messages
</message-bundle>
</application>
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>PrimeFaces Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</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>
<!-- 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>home.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>
<!-- Map these files with JSF -->
<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>*.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>
</web-app>
My Bean controller
package br.com.managedController;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.view.ViewScoped;
import org.springframework.dao.DataAccessException;
import br.com.dentrio.comum.BaseBean;
import br.com.dentrio.model.Dentista;
import br.com.dentrio.service.DentistaServiceImpl;
#Component("dentistaBean")
public class DentistaBean extends BaseBean implements Serializable {
private static final long serialVersionUID = 1L;
#Autowired
DentistaService dentistaService;
private Date data;
private Dentista dentista = new Dentista();
private Dentista dentistaSelecionado;
List<Dentista> listaDentistas = new ArrayList<Dentista>();
public void prepararPedidos() {
carregarListaDentistas();
}
#PostConstruct
private void carregarListaDentistas() {
listaDentistas = new ArrayList<Dentista>();
listaDentistas.addAll(dentistaService.listDentistas());
}
public String adicionarDentista() {
try {
dentistaService.addDentista(dentista);
carregarListaDentistas();
addMessage("Sucesso", "Dentista adicionado com Sucesso!");
return "listarDentistas?faces-redirect=true";
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
public void deletarDentista(Integer dentistaId) {
try {
Dentista dentista = dentistaService.getDentista(dentistaId);
dentistaService.deletarDentista(dentista);
addMessage("Sucesso", "Dentista deletado com Sucesso!");
carregarListaDentistas();
} catch (Exception e) {
e.printStackTrace();
}
}
public void resetForm() {
dentista = new Dentista();
}
public Dentista getDentista() {
return dentista;
}
public void setDentista(Dentista dentista) {
this.dentista = dentista;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public List<Dentista> getListaDentistas() {
return listaDentistas;
}
public void setListaDentistas(List<Dentista> listaDentistas) {
this.listaDentistas = listaDentistas;
}
public Dentista getDentistaSelecionado() {
return dentistaSelecionado;
}
public void setDentistaSelecionado(Dentista dentistaSelecionado) {
this.dentistaSelecionado = dentistaSelecionado;
}
public DentistaService getDentistaService() {
return dentistaService;
}
public void setDentistaService(DentistaService dentistaService) {
this.dentistaService = dentistaService;
}
}
What i do is inject the Spring service as a managed property in JSF bean. You can use #ViewScoped without problems.
#ViewScoped
public class bean{
#ManagedProperty(value="#{springService}")
private SpringService springService;
//getter and setter

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

What is the correct way to use the two contexts: dispatcher-servlet.xml and applicationContext.xml? What goes where?
I want to write a fairly typical app deployed in a servlet container. It has some controllers with JSP views. It also has some nontrivial logic on the back-end. Do I really need both contexts? How are they related to each other? How can I decide what to put in which?
Also, I want to use Spring-security for my application. I may want to use its features (like declarative security with annotations) in web controllers as well as in deeper layers. How should I configure security to work in this case? Should it be in one of those files (which?), or both?
The dispatcher-servlet.xml file contains all of your configuration for Spring MVC. So in it you will find beans such as ViewHandlerResolvers, ConverterFactories, Interceptors and so forth. All of these beans are part of Spring MVC which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.
The application-context.xml can optionally be included when using Spring MVC or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.
These configuration files are configured in the web.xml file as shown:
Dispatcher Config
<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/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Application Config
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
To configure controllers, annotate them with #Controller then include the following in the dispatcher-context.xml file:
<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />
To add to Kevin's answer, I find that in practice nearly all of your non-trivial Spring MVC applications will require an application context (as opposed to only the spring MVC dispatcher servlet context). It is in the application context that you should configure all non-web related concerns such as:
Security
Persistence
Scheduled Tasks
Others?
To make this a bit more concrete, here's an example of the Spring configuration I've used when setting up a modern (Spring version 4.1.2) Spring MVC application. Personally, I prefer to still use a WEB-INF/web.xml file but that's really the only xml configuration in sight.
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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" version="3.1">
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<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>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.company.config.WebConfig</param-value>
</init-param>
</servlet>
<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.company.config.AppConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
</web-app>
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.company.controller")
public class WebConfig {
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
AppConfig.java
#Configuration
#ComponentScan(basePackages = "com.company")
#Import(value = {SecurityConfig.class, PersistenceConfig.class, ScheduleConfig.class})
public class AppConfig {
// application domain #Beans here...
}
Security.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private LdapUserDetailsMapper ldapUserDetailsMapper;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/js/**").permitAll()
.antMatchers("/**/images/**").permitAll()
.antMatchers("/**").access("hasRole('ROLE_ADMIN')")
.and().formLogin();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchBase("OU=App Users")
.userSearchFilter("sAMAccountName={0}")
.groupSearchBase("OU=Development")
.groupSearchFilter("member={0}")
.userDetailsContextMapper(ldapUserDetailsMapper)
.contextSource(getLdapContextSource());
}
private LdapContextSource getLdapContextSource() {
LdapContextSource cs = new LdapContextSource();
cs.setUrl("ldaps://ldapServer:636");
cs.setBase("DC=COMPANY,DC=COM");
cs.setUserDn("CN=administrator,CN=Users,DC=COMPANY,DC=COM");
cs.setPassword("password");
cs.afterPropertiesSet();
return cs;
}
}
PersistenceConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(transactionManagerRef = "getTransactionManager", entityManagerFactoryRef = "getEntityManagerFactory", basePackages = "com.company")
public class PersistenceConfig {
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
lef.setPackagesToScan("com.company");
return lef;
}
private HibernateJpaVendorAdapter getHibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabase(Database.ORACLE);
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");
hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(false);
return hibernateJpaVendorAdapter;
}
#Bean
public JndiObjectFactoryBean getDataSource() {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("java:comp/env/jdbc/AppDS");
return jndiFactoryBean;
}
#Bean
public JpaTransactionManager getTransactionManager(DataSource dataSource) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(getEntityManagerFactory(dataSource).getObject());
jpaTransactionManager.setDataSource(dataSource);
return jpaTransactionManager;
}
}
ScheduleConfig.java
#Configuration
#EnableScheduling
public class ScheduleConfig {
#Autowired
private EmployeeSynchronizer employeeSynchronizer;
// cron pattern: sec, min, hr, day-of-month, month, day-of-week, year (optional)
#Scheduled(cron="0 0 0 * * *")
public void employeeSync() {
employeeSynchronizer.syncEmployees();
}
}
As you can see, the web configuration is only a small part of the overall spring web application configuration. Most web applications I've worked with have many concerns that lie outside of the dispatcher servlet configuration that require a full-blown application context bootstrapped via the org.springframework.web.context.ContextLoaderListener in the web.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
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 http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.testpoc.controller"/>
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.tridenthyundai.ains" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<?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:context="http://www.springframework.org/schema/context"
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 ">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.sapta.hr" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="viewResolver"
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>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestPOC</display-name>
<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-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Error integration jsf +spring +hibernate +managedbean

I have web application wich uses jsf 2.0 and spring 3.0 +hibernate 4 The problem is that: jsf managed beans can't use spring beans using dependency injection There are my config files:
Rq When I change Mybean like that #ManagedBean(name="userMB")
#RequestScoped
and I put #ManagedProperty(value="#{Service}") it is recognized on jsf page but there is error
package com.ardia.service;
import java.util.List;
import com.ardia.model.Composant;
public interface ComposantService {
void inserComposant(Composant comp);
Composant getComposantById(int compId);
Composant getComposant(String compname);
List<Composant> getComposants();
}
this is my service
package com.ardia.service;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ardia.model.Composant;
#Service("compService")
#Transactional
public class ComposantImp implements ComposantService {
#Autowired
SessionFactory sessionFactory;
#Override
public void inserComposant(Composant comp) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().saveOrUpdate(comp);
}
#Override
public Composant getComposantById(int compId) {
// TODO Auto-generated method stub
return (Composant) sessionFactory.
getCurrentSession().
get(Composant.class, compId);
}
#Override
public Composant getComposant(String compname) {
// TODO Auto-generated method stub
return null;
}
#Override
#SuppressWarnings("unchecked")
public List<Composant> getComposants() {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.
getCurrentSession().
createCriteria(Composant.class);
return criteria.list();
}
}
This is My Managed Bean
package ardia.beans;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.ardia.model.Composant;
import com.ardia.service.ComposantService;
#Component("compBean")
#Scope("session")
public class CoposantBean implements Serializable{
#Autowired
private ComposantService service;
private List<Composant> list;
#PostConstruct
public void init()
{
list=service.getComposants();
}
public List<Composant> getList() {
return list;
}
public void setList(List<Composant> list) {
this.list = list;
}
}
this is My application context spring
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan
base-package="ardia.beans" />
<context:component-scan
base-package="com.ardia.service" />
<!-- Data Source Declaration -->
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql:PFE" />
<property name="username" value="postgres" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="packagesToScan" value="com.ardia.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
</beans>
this web.xml and facec.conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
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">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
faces config
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>default</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
and When I try to have a list with datatable .the managedbean it is not recognized
<p:dataTable id="cars" var="fab" value=***"#{here is not figure*** paginator="true" rows="10" >
The classes which hold spring stereo typed beans (here your backing beans are holding them) should be instanciated via Spring Factories, but backing beans are created by JSF framework. Just use Spring EL Resolvers for JSF to overcome this. He is a relevant discussion and documentation
Also, make sure you have the spring bootstrap configured in the web application context loading via web.xml
<!-- Spring Bootstrap -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
package1.where.springbeans.exist
package2.where.springbeans.exist
</param-value>
</context-param>

Spring MVC 3.0 , 404 Error , Controller used to serve Home page

I want to route my application(Spring running on Apache Tomcat 7.0) on Startup/Launch to a Controller that serves a Home view
Therefore:
1) I defined a index.htm in the welcome file tag in web.xml
2) I annotated HomeController with
#Controller
#RequestMapping("/index.htm")
3) I also mapped HomeController in xml bean
My web.xml:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>yourmarketnet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>yourmarketnet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>
Snippet of my spring-servlet.xml:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" p:viewClass="org.springframework.web.servlet.view.JstlView" />
<!-- Controller beab mappinh -->
<bean class="com.yourmarketnet.controller.spring.HomeController"
name="HomeController"/>
<bean id="unAuthenticatedUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.htm">HomeController</prop>
</props>
</property>
</bean>
snippet from applicationContext.xml:
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example #Controller and #Service. Make sure to set the correct base-package-->
<context:component-scan base-package="com.yourmarketnet.mvc.controller.spring" />
<!-- Configures the annotation-driven Spring MVC Controller programming model. Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven />
<!-- mapping of static resources-->
<mvc:resources mapping="/resources/**" location="/resources/" />
<import resource="hibernate-context.xml" />
My HomeController:
package com.yourmarketnet.controller.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value={"/","/index.htm"})
//If have also tried RequestMapping("/index.htm") OR //If have also tried RequestMapping("index.htm")
public class HomeController {
#RequestMapping(method = RequestMethod.GET)
public String requestHandler()
{
return "Home";
}
}
This is also my project structure:
However
Im getting 404 Error on application launch "The requested resource () is not available."
Try doing context-component scan of your controller .
Add the following line in your ..-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.yourmarketnet.controller.spring"/>
Where exactly is your index.htm in the project structure??
And you can not define the index.htm both as a welcome-file and map it with the controller.
You have two solutions.
If you have no use of index.htm then remove it completely from the welcome-file-list and then map your controller only with "/" value.
Or you can make index.htm as only the mapping in your controller without using "/" mapping also. And don't use any welcome-file-list.
Hope this helps you.
Cheers.
Do this
#Controller
public class HomeController {
#RequestMapping({"/"})
public String requestHandler()
{
return "Home";
}
}
You're all set.
You don't need the
<bean id="unAuthenticatedUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.htm">HomeController</prop>
</props>
</property>
</bean>
If you're using annotations.

Resources