#RequestParam annotation at class level not working as expected - spring

This is the controller:
package com.spring.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.jboss.logging.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.spring.DAO.CountryDAO;
import com.spring.DAO.HospitalDAO;
import com.spring.DAO.HospitalSpecialityDAO;
import com.spring.DAO.SpecialityDAO;
import com.spring.VO.HospitalSpecialityVO;
import com.spring.VO.HospitalVO;
import com.spring.VO.SpecialityVO;
#Controller
#RequestMapping("/admin")
public class HospitalController {
#Autowired
CountryDAO country;
#Autowired
HospitalDAO hospital;
#Autowired
SpecialityDAO Speciality;
#Autowired
HospitalSpecialityDAO hospitalSpeciality;
#RequestMapping("/addHospital.html")
public ModelAndView addHospital(HttpSession session) throws Exception {
List<Object> list = this.country.getCountry();
session.setAttribute("list", list);
List<Object> slist = this.Speciality.getSpeciality();
session.setAttribute("slist", slist);
return new ModelAndView("admin/addHospital",
"insertHospitalSpeciality", new HospitalSpecialityVO());
}
}
And this is the URL which I want to map:
/projectname/admin/addHospital.html
This is the web.xml file:
<?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_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
spring-servlet.xml file:
<?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"
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" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="100000" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/healthanalytics"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean> -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.spring.VO.CityVO</value>
<value>com.spring.VO.ComplainVO</value>
<value>com.spring.VO.CountryVO</value>
<value>com.spring.VO.DiseaseVO</value>
<value>com.spring.VO.DoctorVO</value>
<value>com.spring.VO.FeedbackVO</value>
<value>com.spring.VO.HospitalVO</value>
<value>com.spring.VO.MedicineVO</value>
<value>com.spring.VO.PatientVO</value>
<value>com.spring.VO.StateVO</value>
<value>com.spring.VO.SpecialityVO</value>
<value>com.spring.VO.SymptomVO</value>
<value>com.spring.VO.HospitalSpecialityVO</value>
<value>com.spring.VO.DoctorSpecialityVO</value>
<value>com.spring.VO.DoctorHospitalVO</value>
<value>com.spring.VO.RegistrationVO</value>
<value>com.spring.VO.LoginVO</value>
<!-- <value>com.malhar.model.Login</value> -->
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.enable_lazy_load_load_trans">true</prop>
</props>
</property>
</bean>
</beans>
But when I call the following url:
http://localhost:8080/health/admin/addHospital.html
I get:
HTTP Status 404 - /health/admin/WEB-INF/view/admin/addHospital.jsp
Here health is the project name.
I am not able to figure out that while getting the result why it is trying to put admin before WEB-INF as shown in error.
Why can't it just get result from /health/WEB-INF/view/admin/addHospital.jsp?
Also if anyone can provide any alternate solution to this it would be much helpful.

In your view resolver configuration, put / before WEB-INF/view/ and for CSS and JavaScript resources use mvc:resources tag to configure resource location and in JSP import them using c:url.

Related

Why does POST method not work spring mvc?

Error:
HTTP Status 405 – Method Not Allowed
Type Status Report
Message Request method 'POST' not supported
Description The method received in the request-line is known by the origin server but not supported by the target resource.
Apache Tomcat/8.5.82
When I access the site through the post method I get this error(With RequestMapping does not work either), with the get method everything works fine(when I use GetMapping).What should I do to solve this problem? I'm using Apache Tomcat/8.5.82
controller class:
package com.example.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
#Controller
public class MainController {
#PostMapping("testpot")
public String rootPost() {
return "static/html/main.html";
}
}
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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.example.demo" />
<mvc:annotation-driven/>
<!-- <bean-->
<!-- class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!-- <property name="prefix" value="/WEB-INF/view/" />-->
<!-- <property name="suffix" value=".jsp" />-->
<!-- </bean>-->
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:default-servlet-handler/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="org.postgresql.Driver" />
<property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/hau" />
<property name="user" value="postgres" />
<property name="password" value="admin3243" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.demo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>spring-cource-mvc-hibernate-aop</display-name>
<absolute-ordering />
<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/applicationContext.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>
</web-app>
hierarchy:
enter image description here

spring mvc 404 error in my project [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 5 years ago.
Im new to MVC. Ive been able to do the tutorial of a couple examples with no problem. Im going to send this project .war file to a potential employer. And he's impatiently waiting.
Im getting a 404 error when trying to run http://localhost:8080/ProductStore/index
My project dir structure is as follows:
ProductStore
src/java/main
com.productstore.dao
ProductsDoa.java
com.productstore.controller
Productscontroler.java
com.productstore.domain
Products.java
com.productstore.service
ProductsService.java
WEB-INF
jsp
index.jsp
spring-servlet.xml
web.xml
Im at a complete loss.
My config files are 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"
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.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.productstore" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My controller class is as follows:
package com.productstore.controller;
package com.productstore.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.productstore.domain.Products;
import com.productstore.service.ProductsService;
#Controller
public class ProductsController {
#Autowired
private ProductsService productsService;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String listProducts (Map<String, Object> map) {
System.out.println("index");
map.put("products", new Products());
map.put("productsList", productsService.listProducts());
return "index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addProducts(#ModelAttribute("products")
Products products, BindingResult result) {
productsService.addProducts(products);
return "redirect:/index";
}
#RequestMapping("/delete/{Id}")
public String deleteProducts(#PathVariable("Id")
Integer Id) {
productsService.removeProducts(Id);
return "redirect:/index";
}
}
If your application starts without errors the problem could be in your servlet mapping.
You map it as:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
which means mapping to root context. Try to change it to following
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Just insure whether you have entry of component scan in servlet-context.xml file.
<context:component-scan base-package="com.productstore.service.*" />
let me know if you still face the issue.

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

Why Service not injected in Controller with Spring?

I have a problem with a controller and a service injection. In Junit test, it is working all data are added in database and no errors return by my test junit. But when I inject the Service in the Controller, the system return a null object instead instantiation :
My service :
package mypackage.services
public interface ExampleService {
public abstract String helloWorld();
}
package mypackage.services;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
#Service("exampleService")
#Scope("singleton")
public class ExampleServiceImpl implements ExampleService {
#Override
public String helloWorld(){
return "Hello World !";
}
}
My Controller:
package mypackage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/planning")
public class PlanningController {
#Autowired
public ExampleService exampleService;
#RequestMapping(method = RequestMethod.GET)
public final ModelAndView planning(final HttpServletRequest request) {
exampleService.helloWorld();
final ModelAndView mav = new ModelAndView("planning", "tasks", "tasks");
return mav;
}
}
Spring-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Use #Component annotations for bean definitions -->
<context:component-scan base-package="mypackage.services" />
<context:component-scan base-package="mypackage.controller" />
<!-- Use #Controller annotations for MVC controller definitions -->
<mvc:annotation-driven />
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- View resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- Renders JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<mvc:interceptors>
<!-- Resolve the device that originated the web request -->
<bean
class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
</mvc:interceptors>
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDatasource" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="database" value="ORACLE" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.c3p0.maxSize">1</prop>
<prop key="hibernate.c3p0.minSize">1</prop>
<prop key="hibernate.c3p0.acquireIncrement">1</prop>
<prop key="hibernate.c3p0.idleTestPeriod">300</prop>
<prop key="hibernate.c3p0.maxStatements">0</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.checkoutTimeout">0</prop>
<prop key="hibernate.c3p0.preferredTestQuery">SELECT * FROM dual</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
and my 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">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<resource-ref>
<description>My DataSource Reference</description>
<res-ref-name>jdbc/myDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
My test :
...
#Autowired
private ApplicationContext applicationContext;
#Test
public void testPlanning() {
LOGGER.debug("Start testPlanning");
boolean c = applicationContext.containsBean("exampleService");
System.out.println(c);
final PlanningController avc = new PlanningController();
final Object mav = avc.planning(request);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(mav instanceof ModelAndView);
ModelAndViewAssert.assertViewName((ModelAndView) mav, "planning");
final BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
LOGGER.debug("End testPlanning");
}
I inherit from a class for my test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-servlet.xml"})
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
public abstract class N2WIAppConfigTest {
private static final Logger LOGGER = LoggerFactory
.getLogger(PlanningControllerTest.class);
#BeforeClass
public static void setUpClass() throws Exception {
// rcarver - setup the jndi context and the datasource
LOGGER.debug("CALL setUpClass");
try {
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder
.emptyActivatedContextBuilder();
// Construct DataSource
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("oracle.jdbc.driver.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:#localhost:1521:xe");
ds.setUser("nemo2");
ds.setPassword("nemo2");
builder.bind("java:comp/env/jdbc/myDatasource", ds);
builder.activate();
} catch (NamingException ex) {
System.out.println("###################################");
ex.printStackTrace();
}
}
}
I tried in my test load the ApplicationContext and if the service is loaded and it is the case. But in the PlanningController, the service is not injected.
The problem occurs in PlanningController. ExampleService is not injected and don't understand why. Do you have any idea ?
Thanks a lot
For #Autowire to work there are set of things that we need to configure
<context:annotation-config /> in context.xml, You are missing this.
xmlns:context="http://www.springframework.org/schema/context in <beans .. tag
Spring Sterio type annotations like #Controller, #Component, #Service etc.
That's because in this line:
final PlanningController avc = new PlanningController();
you are manually creating a bean instance instead of leaving it to spring, so spring has no means to autowire dependencies.
You should either leave bean creation to the container (spring in this case) or set bean properties yourself.
In your case, you can access spring-managed PlanningController instance using
applicationContext.getBean(PlanningController.class);

Resources