I am developing small student app, based on Spring MVC which should implement simple CRUD students operations via rest web services onto mysql database.
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_2_5.xsd"
version="2.5">
<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/mvc-dispatcher-servlet.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>
mvc-dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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-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:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.training.dao" />
<context:component-scan base-package="com.training.service" />
<context:component-scan base-package="com.training.controller" />
<context:component-scan base-package="com.training.bean" />
<context:component-scan base-package="com.training.dto" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.training.bean.StudentBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
StudentsController.java:
package com.training.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.training.bean.StudentBean;
import com.training.dto.ResponseDTO;
import com.training.service.StudentService;
#RestController
#RequestMapping(value = "/student")
#EnableWebMvc
public class StudentController {
#Autowired
StudentService studentService;
ResponseDTO responseDTO;
#RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getStudent(#PathVariable("id") int studentId) {
try {
StudentBean student = studentService.getStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", student, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody ResponseDTO createStudent(#RequestBody StudentBean student) {
try {
studentService.addStudent(student);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO deleteStudent(#PathVariable("id") int studentId) {
try {
studentService.deleteStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getAllStudents() {
try {
java.util.List<StudentBean> students = studentService.getAllStudents();
responseDTO = studentService.converToDTO(true,"success", null, students);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false,e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/about")
public String aboutPage() {
return "about";
}
}
Now when I call for example
localhost:8080/student/getAll
or any of the mapped methods the reponse is
HTTP Status 404 - /student/getAll
The requested resource is not available.
Here is catalina.out, no errors there:
Oct 22, 2016 10:23:17 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
INFO: Mapped "{[/about/app]}" onto public java.lang.String com.training.controller.AboutController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/delete/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.deleteStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/get/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/getAll],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getAllStudents()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/about]}" onto public java.lang.String com.training.controller.StudentController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/add],methods=[POST]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.createStudent(com.training.bean.StudentBean)
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sat Oct 22 10:23:17 EEST 2016]; root of context hierarchy
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 3912 ms
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 22, 2016 10:23:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7653 ms
#EnableWebMvc applies to Spring configuration classes (i.e. classes annotated with #Configuration). It's not having any effect on your controller. From the first line of the #EnableWebMvc Javadoc page (emphasis mine):
Adding this annotation to an #Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport...
Since you're using XML configuration instead of Java Annotation driven configuration, simply add this to your mvc-dispatcher-servlet.xml: file:
<mvc:annotation-driven/>
As is, without this configuration active, Spring is trying to route to a view with the same name as your request mapping. Since it doesn't exist, you're getting the 404 Not Found error.
Related
I started with spring ORM + Hibernate tutorials. While running the main.java, getting bellow exception and since exception does not have more details about the error. I am not able to figure out the issue. Could please someone can help where is an issue in my code.
config.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<context:component-scan base-package="demo.spring.orm.userService.userEntity" />
<context:component-scan base-package="demo.spring.orm.userService.UserService" />
<context:annotation-config />
<tx:annotation-driven/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=pathDB_New" />
<property name="username" value="sa" />
<property name="password" value="arst#dm1n" />
</bean>
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" name="lsfb">
<property name="dataSource" ref="ds"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>demo.spring.orm.userEntity.User</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" name="ht">
<property name="sessionFactory" ref="lsfb"></property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" name="transactionManager">
<property name="sessionFactory" ref="lsfb"></property>
</bean>
<bean class="demo.spring.orm.userService.UserService" name="userService">
<property name="hibernateTemplate" ref="ht"></property>
</bean>
</beans>
UserService.java
package demo.spring.orm.userService;
import javax.transaction.Transactional;
import org.springframework.orm.hibernate5.HibernateTemplate;
import demo.spring.orm.userDao.UserDao;
import demo.spring.orm.userEntity.User;
public class UserService implements UserDao{
public HibernateTemplate hibernateTemplate;
#Transactional
public void add(User user) {
hibernateTemplate.save(user);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
User.java
package demo.spring.orm.userEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int userId;
private String userName;
private String email;
private String title;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int userId, String userName, String email, String title) {
super();
this.userId = userId;
this.userName = userName;
this.email = email;
this.title = title;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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 getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
main.java
package demo.spring.orm;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import demo.spring.orm.userEntity.User;
import demo.spring.orm.userService.UserService;
public class main {
public static void main(String args[])
{
ApplicationContext context= new ClassPathXmlApplicationContext("config.xml");
UserService userService=context.getBean("userService",UserService.class);
User user=new User(2,"Arunendra","mail#mail.com","Software Engineer");
userService.add(user);
}
}
Exception:
Jul 27, 2021 8:48:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.30.Final
Jul 27, 2021 8:48:40 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 27, 2021 8:48:44 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Hibernate: create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))
Jul 27, 2021 8:48:46 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:318)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:616)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at demo.spring.orm.main.main(main.java:11)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'User'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1632)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:872)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:767)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7225)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:3053)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:247)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:222)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.execute(SQLServerStatement.java:743)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 28 more
Jul 27, 2021 8:48:46 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'demo.spring.orm.userService.UserService' but was actually of type 'com.sun.proxy.$Proxy20'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:395)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1114)
at demo.spring.orm.main.main(main.java:12)
You can solve that problem by enabling CGLIB proxy, add proxy-target-class attribute in your spring context :
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
Based on this tutorial, I was trying to manage Hibernate 5 transactions with Spring 4. It seems that the transaction has not been started when session.get() method is reached. How does Spring knows when to start and end a transaction? Shouldn't the #Transactional annotation do precisely this?
Entity
package coproject.cpweb.utils.db.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import coproject.cpweb.utils.db.entities.Project;
import coproject.cpweb.utils.db.entities.User;
#Entity
#Table( name = "users" )
public class Cbtion {
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
private Integer id;
#ManyToOne
private Project project;
#ManyToOne
private User creator;
private Date creationDate;
private String title;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DAO
package coproject.cpweb.utils.db.daos;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import coproject.cpweb.utils.db.entities.User;
#Service
public class CbtionDAO {
#Autowired
SessionFactory sessionFactory;
public void saveUser(User user) {
Session session = sessionFactory.getCurrentSession();
User user_indb = session.get(User.class,user.getId());
if(user_indb == null) {
session.save(user);
}
else {
user = user_indb;
}
}
public User getUser(Integer id) {
Session session = sessionFactory.getCurrentSession();
User user = session.get(User.class,id);
return user;
}
}
Service
package coproject.cpweb.utils.db.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import coproject.cpweb.utils.DbServicesIf;
import coproject.cpweb.utils.db.daos.CbtionDAO;
import coproject.cpweb.utils.db.entities.User;
#Service
public class DbServicesImp implements DbServicesIf{
#Autowired
private CbtionDAO cbtionDAO;
#Transactional
public void saveUser(User user) {
cbtionDAO.saveUser(user);
}
#Transactional
public User getUser(Integer id) {
return cbtionDAO.getUser(id);
}
}
context beans.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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" >
<tx:annotation-driven />
<context:component-scan base-package="coproject.cpweb.utils.db.entities" />
<context:component-scan base-package="coproject.cpweb.utils.db.daos" />
<context:component-scan base-package="coproject.cpweb.utils.db.services" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="jaof" />
<property name="password" value="iris" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>coproject.cpweb.utils.db.entities</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
Main
package coproject.cploc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import coproject.cpweb.utils.db.entities.User;
import coproject.cpweb.utils.db.services.DbServicesImp;
public class FillRandomDb {
public static void main(String[] args) throws Exception {
#SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// TEST String[] bean_names = context.getBeanDefinitionNames();
DbServicesImp dbServices = (DbServicesImp) context.getBean("dbServicesImp");
User user = new User();
user.setUsername("johndoe");
user.setFirstname("John");
user.setLastname("Doe");
dbServices.saveUser(user);
User user_ret = dbServices.getUser(user.getId());
System.out.println(user_ret.getFirstname());
}
}
Stack
nov 29, 2015 1:45:37 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#506e6d5e: startup date [Sun Nov 29 13:45:37 CE
T 2015]; root of context hierarchy
nov 29, 2015 1:45:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
nov 29, 2015 1:45:38 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
nov 29, 2015 1:45:38 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
nov 29, 2015 1:45:38 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
nov 29, 2015 1:45:39 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
nov 29, 2015 1:45:45 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
nov 29, 2015 1:45:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
nov 29, 2015 1:45:46 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#5e1d03d7] of Hibernate SessionFactory for HibernateTransactionMana
ger
Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:33
4)
at com.sun.proxy.$Proxy23.get(Unknown Source)
at coproject.cpweb.utils.db.daos.CbtionDAO.saveUser(CbtionDAO.java:19)
at coproject.cpweb.utils.db.services.DbServicesImp.saveUser(DbServicesImp.java:20)
at coproject.cpweb.utils.db.services.DbServicesImp$$FastClassBySpringCGLIB$$cd649fcb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281
)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at coproject.cpweb.utils.db.services.DbServicesImp$$EnhancerBySpringCGLIB$$75288f15.saveUser(<generated>)
at coproject.cploc.FillRandomDb.main(FillRandomDb.java:24)
Try to change this line in your file context beans.xml:
<prop key="hibernate.current_session_context_class">thread</prop>
With this line:
<prop key="current_session_context_class">thread</prop >
And for annotation support, in your spring config bean, add this:
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true" />
DAO class should be annotated as #Repository.
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 6 years ago.
I´m getting a mapping error on my application, any help would be greatly appreciated! =)
Error message: No mapping found for HTTP request with URI [/springapp/priceincrease.htm] in DispatcherServlet with name 'springapp'
You can find some code below:
PriceIncreaseFormController.java
#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;
}
}
app-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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>
web.xml
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<display-name>Springapp</display-name>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
You forgot to add handler mapping in your application context:
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
There problem in your GET method : formBackingObject.
Depends upon your requirement it should return to view or make it REST method.
Case 1 : return to view (JSP,HTML,XSLT...)
#RequestMapping(value="/priceincrease.htm",method = RequestMethod.GET)
protected String formBackingObject(HttpServletRequest request,Model model) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
model.addAttribute("priceIncrease",priceIncrease);
return "view_name";
}
Case 2 : REST method using #ResponseBody (jackson.core Jar is necessary)
#RequestMapping(value="/priceincrease.htm",method = RequestMethod.GET)
#ResponseBody
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
Here you have modify controller's parent mapping (simply remove it) for both cases
#Controller
public class PriceIncreaseFormController {
}
I'm trying to find out what have I done wrong. It would be great if anyone could help me. I keep getting this in an infinite loop:
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#799f7e29: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#548a9f61: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
UsersDAOImp :
public class UsersDAOImp extends GenericEntityDAO implements UsersDAO {
private SessionFactory sessionFactory = (SessionFactory) BeanManager.getBean("sessionFactory");
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Users> selectAll() {
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Users.class);
List<Users> users = (List<Users>) criteria.list();
session.getTransaction().commit();
return users;
}
}
UsersService
public class UsersService {
UsersDAOImp usersDAO = new UsersDAOImp();
public void setUsersDAO(UsersDAOImp usersDAO) {
this.usersDAO = usersDAO;
}
public UsersDAOImp getUsersDAO() {
return usersDAO;
}
public List<Users> getAllUsers() {
return getUsersDAO().selectAll();
}
}
Bean manager used to get context
public class BeanManager {
/* BeanManager is used to parse Beans.xml file */
private static ApplicationContext context;
private BeanManager() {
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
BeanManager.context = context;
}
public static Object getBean(String beanId) {
if (context == null) {
context = new ClassPathXmlApplicationContext("Beans.xml");
}
Object result = context.getBean(beanId);
return result;
}
}
This is my Beans.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: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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="usersDAO" class="com.survey.persistance.DAO.UsersDAOImp" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</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/app" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>
I am tiring to to build a small application with spring+hibernate+maven+postgreSQL but when i am tiring to inject dependency in my controller and service class it creates problem for injecting the dependency here is the code and logs please give your suggestion to solve this wiring problem?
mvc-dispature-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.bms" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/bms" />
<property name="username" value="postgres" />
<property name="password" value="*******" />
</bean>
<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">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.bms.Domain.Book</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Controller class BooksEntryController.java
#Controller
#RequestMapping(value = "/dashboard/*")
public class BooksEntryController {
#Resource
private BookFormService bookFormServiceImp;
#RequestMapping(value = "/booksentryform", method = RequestMethod.GET)
public ModelAndView viewBooksEntryForm(Model model) {
model.addAttribute("test", new Book());
return new ModelAndView("bookregistrationform");
}
#RequestMapping(value = "/addbookdetails", method = RequestMethod.POST)
public String addBook(#ModelAttribute("test") Book book, Model model) {
if (book != null) {
bookFormServiceImp.addBooks(book);
return "bookaddsuccessfully";
} else {
throw new NullPointerException();
}
}
}
Service interface BookFormService.java
public interface BookFormService {
void addBooks(Book book);
}
ServiceImp class BookFormServiceImp.java
#Service("bookFormServiceImp")
public class BookFormServiceImp implements BookFormService {
#Resource
private BookFormDao bookFormDaoImp ;
public void addBooks(Book book) {
bookFormDaoImp.addBook(book);
// TODO Auto-generated method stub
}
}
Dao interface BookFormDao .java
public interface BookFormDao {
public void addBook(Book book); }
DaoImp class BookFormDaoImp.java
#Repository("bookFormDaoImp")
public class BookFormDaoImp implements BookFormDao {
#Resource
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addBook(Book book) {
// TODO Auto-generated method stub
getCurrentSession().save(book);
}
}
Here is the log :
2013-06-20 00:35:51.528:INFO:/bms:Initializing Spring root WebApplicationContext
Jun 20, 2013 12:35:51 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jun 20, 2013 12:35:51 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Thu Jun 20 00:35:51 IST 2013]; root of context hierarchy
Jun 20, 2013 12:35:51 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,sessionFactory,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2df8f8: defining beans [booksEntryController,bookFormDaoImp,bookFormServiceImp,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,dataSource,sessionFactory,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Jun 20, 2013 12:35:52 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'booksEntryController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormServiceImp': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookFormDaoImp': Injection of resource dependencies failed; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
...................................
....................................
You are probably not using the right sessionFactory class. If you are using Hibernate 4, use LocalSessionFactoryBean instead of AnnotationSessionFactoryBean.
Replace
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
by
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">