Who implemente the spring BindingResult? - spring-mvc

I'm new to Spring MVC and I'm trying to understand the following code
package com.companyname.springapp.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.companyname.springapp.service.PriceIncrease;
import com.companyname.springapp.service.ProductManager;
#Controller
#RequestMapping(value="/priceincrease.htm")
public class PriceIncreaseFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private ProductManager productManager;
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#Valid PriceIncrease priceIncrease, BindingResult result)
{
if (result.hasErrors()) {
return "priceincrease";
}
int increase = priceIncrease.getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
return "redirect:/hello.htm";
}
#RequestMapping(method = RequestMethod.GET)
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
As far as I know the BindingResult is an interface and the onSubmit method receives a BindingResult object. What I don't understand is: Who implemented this interface to create the object and where is that implementation?
Here is the 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: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.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">
<bean id="productManager" class="com.companyname.springapp.service.SimpleProductManager">
<property name="products">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
<bean id="product1" class="com.companyname.springapp.domain.Product">
<property name="description" value="Lamp"/>
<property name="price" value="5.75"/>
</bean>
<bean id="product2" class="com.companyname.springapp.domain.Product">
<property name="description" value="Table"/>
<property name="price" value="75.25"/>
</bean>
<bean id="product3" class="com.companyname.springapp.domain.Product">
<property name="description" value="Chair"/>
<property name="price" value="22.79"/>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.companyname.springapp.web" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<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/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
I don't if this helps but I'm using Tomcat 7.0 and whole code is in here: http://docs.spring.io/docs/Spring-MVC-step-by-step/

Who implemented this interface to create the object and where is that implementation?
Implemented in the Spring framework and instantiated by your context.
In the above example BeanPropertyBindingResult.class is exact implementation of BindingResult instantiated
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/BeanPropertyBindingResult.html

Related

How to configure the spring-servlet.xml to correct the Injection failure on the Spring-MVC 3.0 project?

I am working on a Spring MVC 3.0 project and have just used #Autowired in my code, but I got the below error message on the Console window:
严重: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.maskkk.service.UserService com.maskkk.controller.LoginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.maskkk.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The logincontroller is to check people to login into the website.
Below is its code:
package com.maskkk.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.maskkk.model.Login;
import com.maskkk.model.User;
import com.maskkk.service.UserService;
#Controller
public class LoginController {
#Autowired
UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLogin(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mav = new ModelAndView("login");
mav.addObject("login", new Login());
return mav;
}
#RequestMapping(value = "/loginProcess", method = RequestMethod.POST)
public ModelAndView loginProcess(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute("login") Login login) {
ModelAndView mav = null;
User user = userService.validateUser(login);
if (null != user) {
mav = new ModelAndView("welcome");
mav.addObject("firstname", user.getFirstname());
} else {
mav = new ModelAndView("login");
mav.addObject("message", "Username or Password is wrong!!");
}
return mav;
}
}
Since:
#Autowired
UserService userService;
The userservice is below:
package com.maskkk.service;
import com.maskkk.model.Login;
import com.maskkk.model.User;
public interface UserService {
void register(User user);
User validateUser(Login login);
}
My project structure is like above:
And my spring-servlet.xml is below:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 下面是配置扫描包的位置,包名为com.maskkk,也就是说,我们的试图解析器应该放在
com.maskkk包下. -->
<!-- import resource="classpath:com/config/user-beans.xml" /> -->
<context:component-scan base-package="com.maskkk.*" />
<context:annotation-config />
<!-- <context:component-scan base-package="com.maskkk.*" /> -->
<!-- 自动扫描(自动注入) -->
<!-- <context:component-scan base-
package="com.maskkk.controller.LoginController" />
<context:component-scan base-package="com.maskkk.service.UserService" /> -->
<mvc:resources mapping="/image/**" location="/image/" />
<bean class="org.springframework.web.servlet.mvc.annotation
.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation
.DefaultAnnotationHandlerMapping" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀,我们的视图文件应该放到/WEB-INF/view/目录下,这里我们需要在WEB-INF下面
创建view文件夹 -->
<property name="prefix" value="/" />
<!-- 设置后缀为.jsp -->
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="multipartResolver"class="org.springframework.web
.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
</bean>
<bean class="org.springframework.beans.factory
.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.web.servlet.mvc
.method.annotation.RequestMappingHandlerMapping">
</bean>
<bean class="org.springframework.web.servlet.mvc
.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json
.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- 加入json支持 -->
<mvc:annotation-driven />
<!-- 处理请求response返回值,如下配置能正确返回字符串型返回值,如返回值为对
象,则自动转为json -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter
.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>text/html; charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="mappingStringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean id="handleAdapter"
class="org.springframework.web.servlet.mvc
.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器
-->
</list>
</property>
</bean>
<!-- 设置返回字符串编码 -->
<bean class="org.springframework.web
.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--json视图拦截器,读取到#ResponseBody的时候去配置它-->
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
</beans>
So, What is wrong with my spring-servlet.xml file?
Any sugestions would be very helpful!

Spring-MVC - Error creating bean with name 'productsController': Injection of autowired dependencies failed

Im having a problem with a spring-mvc project. The #autowiring is not creating the beans required. Ive worked on this for over 4 days and followed all the search results. But nothing has worked. Can someone please take a look. Thank You
The error stack is this:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.davis.ty.service.ProductsService com.davis.ty.controller.ProductsController.productsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.davis.ty.service.ProductsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
My servlet.xml is:
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<context:annotation-config />
<context:component-scan base-package="com.davis.ty" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp2.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 is:
package com.davis.ty.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.davis.ty.domain.Products;
import com.davis.ty.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";
}
}
My service program is:
package com.davis.ty.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.davis.ty.dao.ProductsDAO;
import com.davis.ty.domain.Products;
#Service
public class ProductsServiceImpl {
#Autowired
private ProductsDAO productsDAO;
#Transactional
public void addProducts(Products products){
productsDAO.addProduct(products);
}
#Transactional
public List<Products> listProducts() {
return productsDAO.listProducts();
}
#Transactional
public void removeProducts(Integer id) {
productsDAO.removeProducts(id);
}
}
Well, your ProductsServiceImpl class doesn't implement ProductsService... so there's no way that bean is injected in a field of type ProductsService.
From my experience, I just add #Repository at my DAO, maybe you can try to use it too
#Repository
public class ProductsDAO
{
}
How Spring autowire works is, Spring application context scans for all the classes inside the package and sub packages, specified by the component scan and internally creates a map by Type and Name. Incase of Type, value can be List of implementing classes, and by name its one.
Then whenever a #Autowire if encounter,
first it check by Type, so if you autowire using interface, it checks for all the implementation of that interface, and if only 1 if found then inject the same. (In case more then 1 is found, then you need to qaulify using the Qualifier and give proper name.
If above fails, if check by name, and injects.
If both fails, if gives NoSuchBeanDefinitionException,
So in your case, you have set the component scan, which is correct. Then while autowiring, you are giving Interface class name and the implementation class does not implements interface. So type check is failing, and also the by name is also failing, and hence you are getting NoSuchBeanDefinitionException.
To fix this, you will need to do what #JB Nizet is suggesting, so that #1 works and bean gets injected properly.
Add implements ProductService after public class ProductsServiceImpl
create a service interface and implement the interface method in service Impl class with #Overrride annotation.
public interface ProductService{
List<Product> getProducts();
}
And then
#Service
public class ProductsServiceImpl implements ProductService{
#Override
public List<Product> getProducts() {
return productRepository.findAll();
}

Getting "no transaction is in progress" when calling em.flush();

Hi i am trying to integrate jpa with spring mvc and getting "no transaction is in progress" when trying to call flush() method.
I can make out that something is wrong with transactions even though i have used #Transactional the method is not running in a transaction.
Spring.xml
`<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config />
<context:component-scan base-package="com.sushant.mvc" />
<bean class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/mvc" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="validationQuery" value="SELECT 1" />
<property name="maxActive" value="-1" />
<property name="maxIdle" value="-1" />
<!-- This property should be set to a value so as to support minimum 500
BC concurrent connections. For test, set this value to 5 -->
<property name="initialSize" value="5" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<!-- <property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property> -->
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="persistenceUnit" />
</bean>
<!-- <bean id="user" class="com.sushant.mvc.entities.User"/> -->
</beans>
`
User.java
'
package com.sushant.mvc.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
#Entity
#Component
#Configurable
public class User {
#PersistenceContext(name = "persistenceUnit")
transient public EntityManager em;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String userName;
#Column
private String email;
#Column
private String firstName;
#Column
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static final EntityManager entityManager() {
EntityManager em = new User().em;
if (em == null)
throw new IllegalStateException(
"Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
#Transactional
public void save(User user) {
em.persist(user);
em.flush();
}
}
'
HomeController.java
'
package com.sushant.mvc;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.sushant.mvc.entities.User;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
User user;
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#Transactional
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! the client locale is " + locale.toString());
//user.em.getTransaction().begin();
// User user=new User();
user.setEmail("sushantmahajan05#gmail.com");
user.setFirstName("Sushant");
user.setLastName("Mahajan");
user.setUserName("sushantmahajan05");
user.save(user);
User u=user.em.find(User.class, new Integer(1).longValue());
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home/home";
}
}
'
servlet-context.xml
'
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.sushant.mvc" />
</beans:beans>
'
You may try creating a persistence.xml file .
You can take a look at te following example : JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()

Bootstrap with Spring MVC

I am trying to use bootstrap to style my app but I won't apply the styles. This is what is in my JSP
<c:url value="css/bootstrap.min.css" var="cssBoostrap" />
<link href="${cssBootstrap}" rel="stylesheet">
This css folder is on the same level as WEB-INF not inside of it but it won't work if it is inside of it or even if the files are inside of the view dir. What could the problem possibly be? I no longer get the no mapping error when adding the mapping to my servlet.xml but yet it still doesn't see the file or I can assume it doesn't because no styling is applied, then I change it to link to the online hosted version and all my styles are applied correctly.
Servlet XML
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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.1.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.eaglecrk.recognition" />
<mvc:annotation-driven />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/system.properties</value>
</list>
</property>
</bean>
<!-- messageSource -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:${external.property.directory}PMS.EOTM.SendEmail</value>
</list>
</property>
</bean>
<!-- dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
</props>
</property>
<property name="packagesToScan" value="com.eaglecrk.recognition.persistence" />
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value = "${email.host}" />
<property name="port" value="${email.port}" />
<property name="username" value="${email.username}" />
<property name="password" value="${email.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.ssl.trust">${email.mail.smtp.ssl.trust}</prop>
<prop key="mail.smtp.starttls.enable">${email.mail.smtp.starttls.enable}</prop>
<prop key="mail.smtp.auth">${email.mail.smtp.auth}</prop>
</props>
</property>
</bean>
</beans>
Controller
package com.eaglecrk.recognition.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.eaglecrk.recognition.dao.award.AwardDao;
import com.eaglecrk.recognition.dao.award.AwardDaoInterface;
import com.eaglecrk.recognition.dao.employee.EmployeeDaoInterface;
import com.eaglecrk.recognition.model.AwardTypeModel;
import com.eaglecrk.recognition.model.EmployeeModel;
import com.eaglecrk.recognition.persistence.AwardNomination;
import com.eaglecrk.recognition.persistence.AwardType;
import com.eaglecrk.recognition.persistence.Employee;
import com.eaglecrk.recognition.util.Functions;
import com.eaglecrk.recognition.util.SpringMailSender;
#Controller
public class TestController extends BaseController implements MessageSourceAware {
private static final Logger LOG = LogManager
.getLogger(TestController.class);
#Autowired
private EmployeeDaoInterface employeeDao;
#Autowired
private AwardDaoInterface awardDao;
#Autowired
private SpringMailSender springMailSender;
/**
* #param request
* #return (ModelAndView) object
*/
#RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() {
try {
LOG.info("Entered the controller");
springMailSender.sendMail();
} catch (Exception e) {
e.printStackTrace();
}
ModelAndView mav = new ModelAndView();
ArrayList<String> names = new ArrayList<String>();
List<Employee> employees = employeeDao.findAll();
Collections.sort(employees, Functions.lastNameOrder);
for (Employee employee : employees) {
EmployeeModel model = new EmployeeModel(employee);
names.add(model.getLocation().getLocationId() + " " +
model.getFirstName() + " " + model.getLastName());
}
mav.addObject("names", names);
mav.setViewName("test");
return mav;
}
#RequestMapping(value = "/test", method = RequestMethod.POST)
public void addNomination(
#ModelAttribute("SpringWeb") AwardNomination nomination,
ModelMap model) {
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
return mav;
}
#RequestMapping(value="/newAwardType", method=RequestMethod.GET)
public ModelAndView addAward() {
ModelAndView mav = new ModelAndView();
ArrayList<AwardTypeModel> models = new ArrayList<AwardTypeModel>();
try{
AwardTypeModel newAwardTypeModel = new AwardTypeModel();
newAwardTypeModel.setActive(false);
newAwardTypeModel.setName("AwardTypeModel.name");
newAwardTypeModel.setDescription("AwardTypeModel.description");
// newAwardTypeModel.setId(123456);
newAwardTypeModel.setCreated(new Date());
newAwardTypeModel.setModified(new Date());
models.add(newAwardTypeModel);
} catch (Exception e){
e.printStackTrace();
}
mav.addObject("awardTypes", models);
mav.addObject("model", new AwardTypeModel());
mav.setViewName("addAward");
return mav;
}
#RequestMapping(value="/addAward", method=RequestMethod.POST)
public String addAwardForm(#ModelAttribute("model") AwardTypeModel model, BindingResult result){
model.setCreated(new Date());
model.setModified(new Date());
AwardType dbo = (AwardType) model.convertToDb();
awardDao.save(dbo);
return "redirect:/test";
}
#Override
public void setMessageSource(MessageSource messageSource) {
// TODO Auto-generated method stub
}
}
Create one folder by name resources at same level as WEB-INF as shown below:
WebApp-|
| - resources -|
| |-styles-|
| | |-bootstrap.min.css
| |
| |-javascript-|
| |-example.js
|
| - WEB-INF
Include the following line in your servlet xml:
<mvc:resources mapping="/resources/**" location="/resources/"/>
Access these resources in your jsp as:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<link href="<c:url value="/resources/styles/bootstrap.min.css" />" rel="stylesheet">
<script src="<c:url value="/resources/javascript/example.js" />"></script>
....
You should declare in your dispatcher servlet config the location of you resources (e.g js, css, img etc.) :
<mvc:resources mapping="/public/**" location="/public/" />
location contains the path to your resources folder. mapping is how you call your resources in your jsp.
Don't forget to declare your mvc namespace in dispatcher config.
Following Prasads Answer above if you need Java based configuration for the same use -
#Configuration
#ComponentScan("com.eaglecrk.recognition")
#EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Also if you are using xml based configuration don't forget <mvc:default-servlet-handler/>

No thread-bound request found in Spring MVC

I m building an app using Spring mvc and I am trying to access an http request from a bean outside the scope of the DispatcherServlet. I read similar posts and figured out that I need to add the RequestContextListener. However I keep getting the same error .Below you can see the controller and the bean I m injecting to the controller:
#Controller
public class ChargeController {
// Injected bean
#Autowired
public StripeCharger stripeCharger;
#RequestMapping(value = "/stripecharge", method = RequestMethod.POST)
public String chargeStripe(ModelMap model) {
// user`s custom code
String response = stripeCharger.charge();
}
}
part of the web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
The injected bean
package com.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
public class StripeCharger {
public String token;
public StripeCharger()
{
HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
this.token = curRequest.getParameter("stripeToken");
}
}
-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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<context:component-scan base-package="com.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- This bean is auto-generated -->
<!-- define the bean to inject the Stripe charger -->
<bean id="StripeCharger" class="com.controller.StripeCharger" scope="request">
<aop:scoped-proxy/>
</bean>
</beans>
Anybody could help me with this issue? Thank you

Resources