I'm using spring-5.0.3
http://localhost:8080/firstapp_spring/greeting
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: No adapter for handler [com.actions.GreetingController#4275cbe5]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
There is no error during building project.
pom.xml =>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
class=>
package com.actions;
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.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class GreetingController {
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.GET)
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.POST)
public String greetingSubmit(#ModelAttribute Greeting greeting) {
return "result";
}
}
app-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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.ftl</value>
</property>
</bean>
<bean name="/hello" class="com.actions.HelloController"></bean>
<bean name="/greeting" class="com.actions.GreetingController"></bean>
</beans>
The request mapping that you've defined in your Controller class is:
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.GET)
and the URL you're trying to access is:
http://localhost:8080/myproject/greeting
You're missing the "/firstapp_spring" part.
Since you're using Spring > 4.3 you can take advantage of the new HTTP mapping annotations: #GetMapping and #PostMapping
Your request mapping can become, the much shorter equivalent:
#GetMapping("/firstapp_spring/greeting")
Related
I want to set session factory in DAO class but after execution I got this issue. In my class i am setting sessionFactory variable through #Autowired annotation but it is not able to set the session Factory.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field sessionFactory in com.springboot.webcrud.dao.ClienteDao required a bean of type 'org.hibernate.SessionFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
Process finished with exit code 1
WHEN I REMOVE THE #Autowired ANNOTATION THEN THE SESSION FACTORY IS ALWAYS NULL WHEN I TRY TO GET THE CURRENT SESSION
This is my project structure: project structure
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>webcrud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mvc</name>
<packaging>war</packaging>
<description>WEB CRUD</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--Dependencias de desarrollo -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<!--Dependencias base de datos -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties file
I'm not able to serve the jsp files without declaring this in the properties file. I fear the hibernate configuration is not properly set since the servlet.xml file seems not to be enough. I don't get why the servlet.xml file is not enough
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>MVC APP</display-name>
<absolute-ordering />
<!-- Configuracion del dispatcher servlet -->
<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/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Ubicacion URL del servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Paquete de escaneo de componentes -->
<context:component-scan base-package="com.springboot.webcrud"/>
<!-- Conversión formateo y validación-->
<mvc:annotation-driven/>
<!-- Configuración Spring MVC directorio view -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Origen BBDD y connection pool -->
<bean id="dataSource" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/tienda?useSSL=false&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="BaseDeDatos2022"/>
<!-- Propiedades connection pool para C3P0 -->
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="maxIdleTime" value="30000"/>
</bean>
<!-- Configuración Hibernate session factory -->
<bean id="sessionFactory" name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.springboot.webcrud.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="ClienteDao" name="ClienteDao" class="com.springboot.webcrud.dao.ClienteDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configuración Hibernate transaction manager -->
<bean id="txManager" name="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Habilitar configuración de transacciones basadas en anotaciones -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Entity class
package com.springboot.webcrud.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
#Setter
#Getter
#ToString
#Entity
#Table(name = "clientes")
public class Cliente {
public Cliente() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
String id;
#Column(name = "nombre")
String nombre;
#Column(name = "apellido")
String apellido;
#Column(name = "email")
String email;
}
DAO Class
When I remove the #Autowired annotation then the sessionFactory is always null when I try to get the current session
package com.springboot.webcrud.dao;
import com.springboot.webcrud.entity.Cliente;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
public class ClienteDao implements IClienteDao {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Cliente> listarClientes() {
if (sessionFactory == null) {
System.out.println("SESION NULA");
return null;
}
Session session = sessionFactory.getCurrentSession();
System.out.println("SESION OK");
Query<Cliente> query = session.createQuery("from Cliente", Cliente.class);
return query.getResultList();
}
}
Controller class
package com.springboot.webcrud.controller;
import com.springboot.webcrud.dao.IClienteDao;
import com.springboot.webcrud.entity.Cliente;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
#Controller
#RequestMapping("/tienda")
public class TiendaController {
#Autowired
IClienteDao servicioCliente;
#RequestMapping("/clientes")
public String listarClientes(Model model) {
System.out.println("Página de clientes");
List<Cliente> clientes = servicioCliente.listarClientes();
model.addAttribute("clientes", clientes);
for (Cliente cliente : clientes
) {
System.out.println(cliente.toString());
}
return "listaClientes";
}
}
Please I appreciate your help I've been stuck here for several days.
When I run the main class then this error pop up. I have checked most of the links for this issue but couldn't solve the problem. Please check the following files to get some idea about the problem Thanks in advance.
# bean.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"
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-3.2.xsd">
<context:property-placeholder
location="com/springproject/test/springtest01/props jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<context:component-scan
base-package="com.springproject.test.springtest01">
</context:component-scan>
</beans>
#pom.xml#
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springproject.test</groupId>
<artifactId>springtest01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springtest01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
</dependencies>
</project>
#NoticesDao#
package com.springproject.test.springtest01;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("noticeDao")
public class NoticesDAO {
private JdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
this.jdbc = new JdbcTemplate(jdbc);
}
public List<Notice> getNotices() {
return jdbc.query("select * form notices", new RowMapper<Notice>() {
public Notice mapRow(ResultSet rs, int rowNum) throws SQLException {
Notice notice = new Notice();
notice.setId(rs.getInt("id"));
notice.setName(rs.getString("name"));
notice.setEmail(rs.getString("email"));
notice.setText(rs.getString("text"));
return notice;
}
});
}
}
#jdbc.properties#
jdbc.username = root
jdbc.password = 123456
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springtutorial
#Main#
public class App
{
public static void main( String[] args )
{
try{
ApplicationContext context = new ClassPathXmlApplicationContext("com/springproject/test/springtest01/beans/beans.xml");
NoticesDAO noticesDAO = (NoticesDAO) context.getBean("noticeDao");
List<Notice> notices = noticesDAO.getNotices();
for(Notice notice: notices){
System.out.println(notice);
}
((ClassPathXmlApplicationContext)context).close();
}catch(Exception e){
System.out.println("==========="+e);
}
}
}
First, your SQL request is invalid, it should be select * FROM notices not FORM.
Second, I didn't manage to get the same error as you. In fact, I could not even make the application context to find the bean.xml and jdbc.properties files with your current configuration. I changed some configuration as follows:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
and
<context:property-placeholder location="jdbc.properties" />
put the files in a main/resources directory, then built and successfully ran the project with
mvn clean compile
mvn mvn exec:java -Dexec.mainClass="com.springproject.test.springtest01.App"
I've been fighting with the Spring framework for few weeks now, and I got
a normal MVC page to show up, and I got JDBC to print onto the console.
But I can't seem to get these to work together...
I've been through countless tutorials at this point and every one of them
seem to have some type of error or problem.
I think I've finally managed to get together a pretty decent and working build, but nope, still getting only 404's.
I think the problem might be in the spring-servlet.xml file:
<context:component-scan base-package="src" />
And I'm not sure if you can even load project like that, but it's the only thing I can think of here.
I include all the other files too, though.
Console Errors
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:spring-mvc' did not find a matching property.
and
SEVERE: Servlet [spring] in web application [/spring-mvc] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1050)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
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)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<spring.version>3.1.0.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.gatein.common</groupId>
<artifactId>common-logging</artifactId>
<version>2.2.2.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.8.1</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- Telling container to take care of annotations stuff -->
<context:annotation-config />
<!-- Declaring base package -->
<context:component-scan base-package="controller" />
<!-- Adding view resolver to show jsp's on browser -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Declare beans -->
<bean id="userDao" class="dao.UserDaoImpl" />
<bean id="userService" class="services.UserServiceImpl" />
<!-- Declare 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/userdb" />
<property name="username" value="root" />
<property name="password" value="38613861" />
</bean>
</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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SpringJDBCTemplate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
homePageController
package controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import domain.*;
import services.*;
#Controller
public class HomePageController {
#Autowired
UserService userService;
#RequestMapping("/register")
public ModelAndView registerUser(#ModelAttribute User user) {
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, List> map = new HashMap<String, List>();
map.put("genderList", genderList);
map.put("cityList", cityList);
return new ModelAndView("register", "map", map);
}
#RequestMapping("/insert")
public String inserData(#ModelAttribute User user) {
if (user != null)
userService.insertData(user);
return "redirect:/getList";
}
#RequestMapping("/getList")
public ModelAndView getUserLIst() {
List<User> userList = userService.getUserList();
return new ModelAndView("userList", "userList", userList);
}
#RequestMapping("/edit")
public ModelAndView editUser(#RequestParam String id,
#ModelAttribute User user) {
user = userService.getUser(id);
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, Object> map = new HashMap<String, Object>();
map.put("genderList", genderList);
map.put("cityList", cityList);
map.put("user", user);
return new ModelAndView("edit", "map", map);
}
#RequestMapping("/update")
public String updateUser(#ModelAttribute User user) {
userService.updateData(user);
return "redirect:/getList";
}
#RequestMapping("/delete")
public String deleteUser(#RequestParam String id) {
System.out.println("id = " + id);
userService.deleteData(id);
return "redirect:/getList";
}
}
Project tree
Project tree from Eclipse Neon2
Not my answer but the one which solved the case, posting as answers since it's buried deep in comments.
Sorry for the delay.... It still not right. I know that because
Eclipse should not show the package as main.java.controller.... Maven
ignores that folder and start right under the java folder as it was
the src folder itself. Something must be wrong on your project. Try
cleaning everything, remove the project from eclipse, delete
(physically) the folder .settings and the file .classpath and the file
.project. Go on your folder project on the console and run mvn clean
eclipse:clean then open all folders of if (like the image I showed to
you) and paste it here so I can see what it is wrong
– Jorge Campos
I created a Java Spring MVC web app which offers simple restful services.
And I have the object class like this..
public class CreateEventWrapper {
private String Topic;
private String SubscriptionReference;
private Date UtcTime;
private List<Message> Messages;
...
}
public class Message {
private List<Source> Source;
...
}
public class Source {
private String Name;
private String Value;
...
}
The controller:
...
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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;
#Controller
#RequestMapping(produces = "application/json")
class EventController {
#RequestMapping(value = "/event", method = RequestMethod.POST)
public ResponseEntity<CreateEventWrapper> CreateEvent(#RequestBody CreateEventWrapper eventWrapper) {
return new ResponseEntity<CreateEventWrapper>(eventWrapper, HttpStatus.OK);
}
}
And I have the json format file using Postman to upload to the server.
The upload function works fine.
{
"topic":"Face",
"subscriptionReference":"http:\\abc",
"utcTime":"2016-10-20T19:00:00Z",
"messages":[{
"source":[{"name":"VideoSource","value":"[1]123.avi"},
{"name":"AnalyticEngine","value":"FacialRecognition"}]
}]
}
I expect the format will be the same with the object order in the class
something like topic, subscriptionReference, utcTime, orderm, message..
but I got the output with message, subscriptionReference, utcTime, topic..
{
"messages": [
{
"source": [
{
"name": "VideoSource",
"value": "[1]123.avi"
},
{
"name": "AnalyticEngine",
"value": "FacialRecognition"
}
]
}
],
"subscriptionReference": "http:\abc",
"utcTime": 1476990000000,
"topic": "Face"
}
Can I have the specific order just like the class object order?
Attach with my spring config and porm.xml for reference.
rest.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:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" 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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- Activates annotation-based bean configuration -->
<context:annotation-config />
<!-- Scans for application #Components to deploy -->
<context:component-scan base-package="org.itri.ccma.paas.service.event.webservice" />
</beans>
porm.xml
...
<!-- Json lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.1</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.4.2</version>
</dependency>
<!-- Springframework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
...
You shall try this
//lower cases since it affects the json output not the class field names
#JsonPropertyOrder({ "topic", "subscriptionReference", "utcTime", "messages" })
public class CreateEventWrapper {
private String Topic;
private String SubscriptionReference;
private Date UtcTime;
private List<Message> Messages;
...
}
And I suggest you to use lowerCamelCase naming variables convention in your code since its most popular
I am trying to integrate spring with hibernate this morning. I want to use spring transaction manager. But getting the below error. The error has something to do with #Trasactional Annotation. If i remove the annotation,im able to get the bean from the spring container.
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to com.hibernate.dao.EvntDAOImpl
at com.hibernate.action.HibernateAction.main(HibernateAction.java:17)
Im pasting below my source code.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hibernate-tutorials</groupId>
<artifactId>hibernate-tutorials</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring ORM support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
Hibernate Configuration
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.hibernate.model.Evnt</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernatey.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
EvntDAOImpl.java
package com.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hibernate.model.Evnt;
#Repository(value="evntDAO")
#Transactional
public class EvntDAOImpl implements EvntDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void storeEvnt(Evnt evnt) {
sessionFactory.getCurrentSession().save(evnt);
}
}
HibernateAction.java
package com.hibernate.action;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hibernate.dao.EvntDAO;
import com.hibernate.dao.EvntDAOImpl;
import com.hibernate.model.Evnt;
public class HibernateAction {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EvntDAOImpl evntDAO = (EvntDAOImpl) context.getBean("evntDAO");
Evnt evnt = new Evnt();
evnt.setTitle("first Event");
evnt.setDate(new Date());
evntDAO.storeEvnt(evnt);
}
}
Thanks in advance...
The problem is in the place where you are injecting EventDaoImpl.
Just replace
#Autowired EventDaoImpl eventDaoImpl
with
#Autowired EventDao eventDao
wherever you need Spring to autowire the dao.
Or if you are getting the bean from the applicationContext use:
EvntDAO evntDAO = (EvntDAO) context.getBean("evntDAO");
The problem is caused by the fact that the use of #Transactional annotation on the dao's implementation code means that Spring will create a JDK dynamic proxy for it, which cannot be cast to the implementation class. Here is the complete documentation of Spring's AOP capabilities (where the creation of JDK dynamic proxies and CGLib class proxies is fully explained).
What that essentially means is that because of #Transactional, when you call context.getBean("evntDAO") you don't get back your EventDaoImpl (as one would expect), but you actually get back an object whose class is java.lang.reflect.Proxy which has been created by Spring. That proxy object implements EventDao (and therefor can be cast to it) but it's signature has nothing to do with EventDaoImpl (and hence the ClassCastException since it does not extend EventDaoImpl). When a method is called on the proxy various things happen before and/or after the call is actually delegated to EventDaoImpl (what happens before/and or after the actual call to EventDaoImpl is controlled by Spring though the implementation of InvocationHandler).