spring cannot find my bean - java

I am new to spring, in my application I need to connect to Mysql, all my database's configuration are in a bean, when I try to get it,the server gives me this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
this is my servlet-context where I define my bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.metmi.mmasgis" />
<beans:bean id="dataSource" name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
autowire-candidate="true">
<beans:property name="driverClassName"
value="com.mysql.jdbc.Driver">
</beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="password"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/springschema">
</beans:property>
</beans:bean>
</beans:beans>
this is my controller:
package com.metmi.mmasgis;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;
import com.metmi.mmasgis.dao.DbImpl;
import com.metmi.mmasgis.model.Db;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Inject
DbImpl dbs;
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
/**
* get the database list in Mysql
*/
#RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbs(Locale locale, Model model) {
ApplicationContext ctx = ContextLoader
.getCurrentWebApplicationContext();
DataSource ds = (DataSource) ctx.getBean("dataSource");
dbs = new DbImpl();
dbs.setDataSource(ds);
ArrayList<Db> dbList = dbs.getDatabases();
model.addAttribute("dbList", dbList);
return "dbs";
}
/**
* Simply shows ciao.
*/
#RequestMapping(value = "/ciao", method = RequestMethod.GET)
public String ciao(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "ciao";
}
}

Move your bean declaration to your main application context, not the one where you have DispatcherServlet.

Related

Java controller giving 404 error on live server

I m setting up my java web application on the server but the rest controller is giving 404 error.
All is working fine on my local system.
This is my 1st project in java hibernate spring.
Below is my code:
UserLoginController.java
package org.jasyatra.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.jasyatra.model.User;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.service.UserLoginService;
import org.jasyatra.service.LoginAuthTokenService;
#RestController
public class UserLoginController {
#Autowired
UserLoginService userLoginService;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#RequestMapping(value = "/user/login", method = RequestMethod.POST, headers = "Accept=application/json")
public Map login(#RequestBody User parameters) {
List<User> loginResponse = userLoginService.login(parameters);
Map<String, String> response = new HashMap<>();
if (loginResponse.size() > 0) {
response.put("result", "true");
response.put("id", Integer.toString(loginResponse.get(0).getId()));
response.put("type", loginResponse.get(0).getType());
response.put("firstName", loginResponse.get(0).getFirstName());
response.put("lastName", loginResponse.get(0).getLastName());
response.put("permissions", loginResponse.get(0).getPermissions());
List<LoginAuthToken> responseToken = loginAuthTokenService.getLatestToken(loginResponse.get(0).getId(),loginResponse.get(0).getType());
response.put("token", responseToken.get(0).getToken());
} else {
response.put("result", "false");
response.put("message", "Invalid mobile no or password!");
}
return response;
}
}
UserLoginDAO.java
package org.jasyatra.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jasyatra.service.HashService;
#Repository
public class UserLoginDAO {
#Autowired
private SessionFactory sessionFactory;
public List<User> login(User parameters) {
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where mobileNo=:mobileNo and password=:password and status=:status");
query.setParameter("mobileNo", parameters.getMobileNo());
query.setParameter("password", HashService.getHash(parameters.getPassword(), "SHA1"));
query.setParameter("status", "active");
List<User> response = query.list();
return response;
}
}
UserLoginService.java
package org.jasyatra.service;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.jasyatra.dao.UserLoginDAO;
import org.jasyatra.dao.LoginAuthTokenDAO;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class UserLoginService {
#Autowired
UserLoginDAO userLoginDao;
#Autowired
LoginAuthTokenDAO loginAuthTokenDAO;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#Transactional
public List<User> login(User parameters) {
List<User> login = userLoginDao.login(parameters);
LoginAuthToken loginAuthToken = new LoginAuthToken();
if (login.size() > 0 && login.get(0).getId() > 0) {
try {
loginAuthToken.setLoginId(login.get(0).getId());
loginAuthToken.setLoginType(login.get(0).getType());
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
String token = HashService.getHash(generatedString, "SHA1");
loginAuthToken.setDateCreated(new Date());
loginAuthToken.setToken(token);
loginAuthTokenService.save(loginAuthToken);
} catch (Exception e) {
e.printStackTrace();
}
}
return login;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/"/>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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-4.0.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/jasyatra" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.jasyatra.model.User</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="268435456"/>
</beans:bean>
<context:component-scan base-package="org.jasyatra" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<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>/</url-pattern>
</servlet-mapping>
</web-app>
The main issue i have is, it is able to run index.jsp but not the controller. What can be the issue?
Please guide me in right direction.
Thanks
you can not open that url in browser because it is POST service, you can only open GET url in browser. you need to add a body while hitting that url to test
your service you can use postman.
no need to send "Accept" header this way, you can use however following attribute instead if you expect a json body with the post request :
#RequestMapping(value = "/user/login", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE);
if you want to get "Accept" header value of your request you can get it like :
public Map login(#RequestBody User parameters,#RequestHeader(value="Accept") String accept){
....

Spring Bean wrong path

I am getting this error and I can't figure out why. I believe its the path. Tried to change it several times but no success.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field loginDelegate in com.codeEvaluator.controller.LoginController required a bean of type 'com.codeEvaluator.delegate.LoginDelegate' that could not be found.
Action:
Consider defining a bean of type 'com.codeEvaluator.delegate.LoginDelegate' in your configuration.
Process finished with exit code 1
This is my sprinBeanConfiguration.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">
<bean id="loginDelegate" class="com.codeEvaluator.delegate.LoginDelegate">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="com.codeEvaluator.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="userDao" class="com.codeEvaluator.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/codeevaluator" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
My springWeb.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.jcg" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
<import resource="springBeanConfiguration.xml"/>
Controller class
package com.codeEvaluator.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.codeEvaluator.delegate.LoginDelegate;
import com.codeEvaluator.viewBean.LoginBean;
#Controller
public class LoginController
{
#Autowired
private LoginDelegate loginDelegate;
#RequestMapping(value="/login",method=RequestMethod.GET)
public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response, LoginBean loginBean)
{
ModelAndView model = new ModelAndView("login");
//LoginBean loginBean = new LoginBean();
model.addObject("loginBean", loginBean);
return model;
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("loginBean")LoginBean loginBean)
{
ModelAndView model= null;
try
{
boolean isValidUser = loginDelegate.isValidUser(loginBean.getUsername(), loginBean.getPassword());
if(isValidUser)
{
System.out.println("User Login Successful");
request.setAttribute("loggedInUser", loginBean.getUsername());
model = new ModelAndView("welcome");
}
else
{
model = new ModelAndView("login");
request.setAttribute("message", "Invalid credentials!!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return model;
}
}
This is a project view.
The login.jsp is inside de jsp package.
change to
<context:component-scan base-package="com.jcg, com.codeEvaluator" />
and your import should be something like this
<import resource="classpath:springBeanConfiguration.xml"/>
or
<import resource="classpath*:springBeanConfiguration.xml"/>
In your "sprinBeanConfiguration.xml" file add those annotations <context:component-scan base-package="com.codeEvaluator" /> and<context:annotation-config> to enable annotation "#Autowired"

how to convert xml notation to annotation based notation : Spring - Java

I have following xml configuration in my spring context xml, I have used annotation based approach very less and unable to figure out how to represent following using annotation, need help.
<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg>
<bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
<property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
<property name="clientId" value="${clientId}" />
<property name="clientSecret" value="${clientSecret}" />
<property name="username" value="${policyAdminUserName}" />
<property name="password" value="${policyAdminUserPassword}" />
</bean>
</constructor-arg>
</bean>
In my java class(Policy manager) it is referred as following, I am actually referring a sample and trying to convert it all annotation baesed.
#Autowired
#Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;
EDIT:
I tried creating a bean for org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails but not sure how to set its properties and how to access it as constructor args to myPolicyAdminTemplate
You can configure the same beans using JavaConfig as follows:
#Component
#Configuration
public class AppConfig
{
#Value("${accessTokenEndpointUrl}") String accessTokenUri;
#Value("${clientId}") String clientId;
#Value("${clientSecret}") String clientSecret;
#Value("${policyAdminUserName}") String username;
#Value("${policyAdminUserPassword}") String password;
#Bean
public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
{
return new OAuth2RestTemplate(details);
}
#Bean
public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
{
ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
bean.setAccessTokenUri(accessTokenUri);
bean.setClientId(clientId);
bean.setClientSecret(clientSecret);
bean.setUsername(username);
bean.setPassword(password);
return bean;
}
}
To set the props of a bean you can either use #Value during construction:
How to inject a value to bean constructor using annotations
and this one:
Spring: constructor injection of primitive values (properties) with annotation based configuration
Or #Value in the variables. You could also actually use #Resource, but I wouldn't recommend it.
In your case, the constructor for the
org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails
Would be kinda like
#Autowired
public ResourceOwnerPasswordResourceDetails(
#Value("${accessTokenEndpointUrl}") String accessTokenUri,
#Value("${clientId}") String clientId,
#Value("${clientSecret}") String clientSecret,
#Value("${policyAdminUserName}") String username,
#Value("${policyAdminUserPassword}") String password
)
I shall give you a XML configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
<mvc:annotation-driven />
<bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/>
<bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>
<!-- couche de persistance JPA -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:bd.properties"/>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="${bd.driver}" />
<property name="url" value="${bd.url}" />
<property name="username" value="${bd.username}" />
<property name="password" value="${bd.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- annotations de persistance -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml
<web-app>
<display-name>Gescable</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
the two files should be place in the folder "WEB-INF".
Now the equivalent with anotation based config
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.backendhibernatejpaannotation.configuration;
import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* #author vivien saa
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
public class RestConfiguration {
#Bean
public IAbonneDao iAbonneDao() {
return new AbonneDaoImpl();
}
#Bean
public IAbonneService iAbonneService() {
return new AbonneServiceImpl();
}
// #Bean
// public PropertyPlaceholderConfigurer placeholderConfigurer() {
// PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
// placeholderConfigurer.setLocations("classpath:bd.properties");
// return placeholderConfigurer;
// }
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
return entityManagerFactory;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}
this file must be accompanied by this one
package com.mycompany.backendhibernatejpaannotation.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author vivien saa
*/
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RestConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

Issue with Spring Framework static resource set up

I have configured my spring project to cater to static resources using below settings in XML file:
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
But when I try to access the static content directly, say using below URL:
http://localhost:8080/main/resources/css/app.css
Instead of showing up the static CSS content in the browser, the request is going to the following method in Controller:
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
Once the request leads to this method instead of showing up the staic CSS file, I see the JSP page returned by return call "home".
I have checked and rechecked but dont really sight any issue with set up.
Please have a look and let me what might be going wrong here.
Below is the Main Controller that my application is using.
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/")
public class MainController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String country(Locale locale, Model model) {
System.out.println("nothing but home page");
return "home";
}
#RequestMapping(value = "/{countryID}", method = RequestMethod.GET)
public String country(#PathVariable("countryID") String countryID, Locale locale, Model model) {
System.out.println("input country "+countryID);
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}", method = RequestMethod.GET)
public String state(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}", method = RequestMethod.GET)
public String city(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
model.addAttribute("serverTime", "");
return "home";
}
#RequestMapping(value = "/{countryID}/{stateId}/{cityId}/{destId}", method = RequestMethod.GET)
public String dest(#PathVariable("countryID") String countryID, #PathVariable("stateId") String stateId, #PathVariable("cityId") String cityId, #PathVariable("destId") String destId, Locale locale, Model model) {
System.out.println("input "+stateId);
System.out.println("input "+countryID);
System.out.println("input "+cityId);
System.out.println("input "+destId);
model.addAttribute("serverTime", "");
return "home";
}
}
And below is the application XML file :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- <beans:bean class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/views.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean> -->
<!-- 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.travel.main" />
</beans:beans>
The problem is, your #RequestMapping in the controler has precedence over the resource-mapping. To change this, you have to do two things:
Add the attribute order="0" to your resources-tag.
Change the order of your tags to:
<resources mapping="/resources/**" location="/resources/" order="0" />
<annotation-driven />
Then it should work.
It seems http://localhost:8080/main/resources/css/app.css is mapped to /{countryID}/{stateId}/{cityId}:
countryId=resources
stateId=css
cityId=app.css
It seems the resources are only mapped when there is no Controller that matches the URL, so you can try to add to that controller a different path: You can change #RequestMapping("/") to #RequestMapping("/mainController") or add something like /city/ in the matcher of the city method: city/{countryID}/{stateId}/{cityId}.
Give a try the following options:
Remove #RequestMapping("/") from the MainController.
Add a View Resolver to your Spring configuration. For instance, InternalResourceViewResolver.
Take a look at the Spring doc.
Move the resources directory to the same level as views. That is,/WEB-INF/views and /WEB-INF/resources.
I hope that helps!

hibernate, spring - transaction

I have a project in Spring, where I have 2 connections to the database. Two because one is for read-only connections and the other is for read-write connections.
My problem is, when I try to invoke method to read only, I get:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
Now I don't know, how to exactly configure my connections.
Below I've inserted my SERVICE CLASS file. The problem is when I'm trying to invoke method with sessionFactoryr , when I'm using sessionFactory - everything is OK.
My configuration is:
hibernate-context.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: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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:property-placeholder location="/WEB-INF/spring.properties" />
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManagerr" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<!-- First Connection -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${app.jdbc.username}"
p:password="${app.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- Second connection (read only) -->
<bean id="sessionFactoryr" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSourcer"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.esb.scs"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSourcer" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${appr.jdbc.username}"
p:password="${appr.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManagerr" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactoryr" />
</beans>
Service Class:
package com.esb.scs.service;
import static java.lang.System.out;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.esb.scs.domain.User;
import com.esb.scs.domain.UserReference;
#Service("userService")
#Transactional
public class UserService {
protected static Logger logger = Logger.getLogger("service");
// #Resource(name="sessionFactoryr")
// private SessionFactory sessionFactoryr;
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
#Resource(name="sessionFactoryr")
private SessionFactory sessionFactoryr;
public void addUser(HttpServletRequest request){
logger.info("test");
Session session = sessionFactory.getCurrentSession();
PasswordEncoder encoder = new Md5PasswordEncoder();
String hashedPassword = encoder.encodePassword(request.getParameter("password"), null);
String login = request.getParameter("login");
String password = hashedPassword;
//String role = request.getParameter("role");
String role = "normal";
String ip = request.getParameter("ip");
int active = 1;
String referenceAddress = request.getParameter("referer");
String sex = request.getParameter("sex");
int age = Integer.parseInt(request.getParameter("age"));
String country = request.getParameter("country");
String city = request.getParameter("city");
String education = request.getParameter("education");
String profession = request.getParameter("profession");
String branch = request.getParameter("branch");
Transaction transaction = session.beginTransaction();
User user = new User();
UserReference userReference = new UserReference();
Date dateCreate = new Date();
user.setEmail(login);
user.setPassword(password);
user.setRole(role);
user.setIp(ip);
user.setDateCreate(dateCreate);
user.setLastLoginDate(dateCreate);
user.setActive(active);
user.setToken("");
userReference.setReferenceAddress(referenceAddress);
userReference.setSex(sex);
userReference.setAge(age);
userReference.setCountry(country);
userReference.setCity(city);
userReference.setEducation(education);
userReference.setProfession(profession);
userReference.setBranch(branch);
userReference.setSite(referenceAddress);
userReference.setUser(user);
userReference.setUser(user);
user.getUserReferences().add(userReference);
session.save(user);
session.save(userReference);
transaction.commit();
}
public List<User> getUser(String name, String password){
Session session = sessionFactoryr.getCurrentSession();
String sqlQuery = "FROM User WHERE email='"+name+"' AND password = '" +password+ "'" ;
Query query = session.createQuery(sqlQuery).setMaxResults(1);
return query.list();
}
public void updateUUID(String uuid, String login, String password){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "update User set token = :token where email = :login and password = :password";
Query query = session.createQuery(hql);
query.setString("token", uuid);
query.setString("login", login);
query.setString("password", password);
query.executeUpdate();
transaction.commit();
}
}
In addition, I have
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
in my web.xml.
According to your advice, if I add #Transactional("transactionManagerr") to my methods - it doesn't change anything, I still get the error.
I think you have to specify transaction manager name in #Transactional (e.g. #Transactional("transactionManagerr")) annotation. Read
Documentation and Jira
If you are using transactional annotations you do not need to manually create a transaction in your service class.
You have specifed the class is transactional this means each method will have its own transaction created by spring.
You can also specifiy transactional on each method and further specifiy read only as and when required.
If you are using two different datasources you also need to specify which transaction manager is to be used.
<bean id="transactionManagerr" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactoryr">
<qualifier value="transactionManagerr"/>
</bean>
And in yr service class you do this :
#Transactional(value = "transactionManagerr")
Also I would think about renaming everything, just appending "r" to everything is not really descriptive.

Categories