How to get JSON response using RESTful webservice in spring 3.1 - json

I want to generate a JSON response of my object I write code for that but not getting success it is giving error 406 I am not using maven I am using ant
This is my controller
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public Employee checklogin(){
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
return e;
}
}
This is my configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
I am calling as http://localhost:8080/SpringMVC/test but getting error 406

You can try following to produce JSON Rsponse. You would require Gson library, and the controller would look as follows:
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public String checklogin(){
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
Gson gson=new Gson();
String jsonResponse=gson.toJson(e);
return jsonResponse;
}
}
Json response looks as following:
{"emailId":"sdosi#cur.com","id":1,"password":"a"}

I suggest to put jackson dependencies in your pom.xml if they are not already there.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
If they are already there can you update your RequestMapping with
#RequestMapping(value = "/test", method=RequestMethod.GET, produces = "application/json;charset=utf-8")
This will ensure that we return a response with a json header.

add the following dependencies in your pom.xml file
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
with in your spring configuration xml files add the following beans
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
now you can use your controller as it is
#Controller
public class LoginRestCtrl {
#RequestMapping(value = "/test", method=RequestMethod.GET)
#ResponseBody
public Employee checklogin() {
Employee e=new Employee();
e.setEmailId("sdosi#cur.com");
e.setId(1);
e.setPassword("a");
return e;
}
}

Related

debug "org.springframework.beans.factory.BeanCreationExcpetion" error in Spring

I am trying to create my own eshop. I have problem on the creation of beans.
My packages are the following:
Controller
package com.emusicstore.controller;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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 com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
#Controller
public class HomeController {
#Autowired
private ProductDao productDao;
#RequestMapping("/")
public String home(){
return "home";
}
#RequestMapping("/productList")
public String getProducts(Model model) {
List<Product> products = productDao.getAllProducts();
model.addAttribute("products", products);
return "productList";
}
ProductDao
package com.emusicstore.dao;
import java.util.List;
import com.emusicstore.model.Product;
public interface ProductDao
{
void addProduct(Product product);
Product getProductById (String id);
List<Product> getAllProducts();
void deleteProduct (String id);
}
ProductDaoImpl
package com.emusicstore.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
#Component
#Transactional
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public void addProduct(Product product) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public Product getProductById(String id) {
Session session = sessionFactory.getCurrentSession();
Product product = (Product) session.get(Product.class, id);
session.flush();
return product;
}
public List<Product> getAllProducts() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Product");
List<Product> products = query.list();
session.flush();
return products;
}
public void deleteProduct(String id) {
Session session = sessionFactory.getCurrentSession();
session.delete(getProductById(id));
session.flush();
}
}
Product
package com.emusicstore.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacture;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacture() {
return productManufacture;
}
public void setProductManufacture(String productManufacture) {
this.productManufacture = productManufacture;
}
}
Also I have a jdbc.properties file with info about username, password etc to connect wit MySQL.
I think that the above files are correct.
applicationContext.xml (part of my code)
<beans profile="dev">
<context:property-placeholder location="jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.emusicstore.*</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Is <tx:annotation-driven /> is necessary in this file?? -->
</beans>
dispatcher-servlet.xml (part of my code)
<context:annotation-config></context:annotation-config>
<context:annotation-config />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<tx:annotation-driven />
web.xml (part of my code)
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
When I try to run my project all the errors associated with:
org.springframework.beans.factory.BeanCreationException
org.springframework.beans.factory.NoSuchBeanCreationDefinitionException
The first error is on the creation of bean 'homeController'.
Could not autowire field: private com.emusicstore.dao.ProductDao com.emusicstore.controller.HomeController.productDao;
My questions.
1) applicationContext.xml
On the which file (or files) I have to put? Is the existing path right or I have to modify it specifically (e.g com.emusicstore.dao)? At this list, I have to put the whole path for my dao, model ?
2) dispatcher-servlet.xml
Same question for the right path of context:component-scan. On the base-package may I specify the package only to my controller (com.emusicstore.controller)?
I searched to older posts but I do not solve my problem.
Thank you in advance, Mike
EDIT
Summary of (our) changes
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns: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.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<beans profile="dev">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.emusicstore.dao, com.emusicstore.impl"></context:component-scan>
<context:property-placeholder location="jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<!-- MY CHANGES -->
<!-- LocalSessionFactoryBean for hibernate4 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!-- CHANGE HERE FOR MySQL -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- To know where is ProductDao -->
<property name="packagesToScan">
<list>
<value>com.emusicstore.dao</value>
<value>com.emusicstore.impl</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
</beans>
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:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd">
<context:component-scan base-package="com.emusicstore." />
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<tx:annotation-driven />
</beans>
Web.xml Exactly the same code as you wrote
The same errors continues to exist but the "homepage" on Eclipse has changed to this
HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception
type Exception report
message Servlet.init() for servlet dispatcher threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
And then the previous errors again...
EDIT
web.xml (first lines)
<?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"
version="3.1">
pom.xml (all my file)
<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.mywebsite</groupId>
<artifactId>eMusicStore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- To work with Hibernate -->
<!-- All Hibernate in single dependency -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- MySql -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- To connect with the jdbc.properties file -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Traditionnaly we have 2 contexts in a Spring MVC application. The root context (here your applicationContext.xml) where we define all beans not dedicated to web stuff like DAO, Securtity, etc... And the DispatcherServlet context (dispatcher-servlet.xml) where we define all beans related to web operations like controllers.
So, put your DAO bean in applicationContext.xml like this : <context:component-scan base-package="com.emusicstore.dao"/> and your transaction manager <tx:annotation-driven transaction-manager="transactionManager"/>
For your 2nd question, you can just put the super package like this : <context:component-scan base-package="com.emusicstore."/>
EDIT
Here how your web.xml should look like :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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/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>
I your configuration you mixed the 2 contexts.

Spring 4 Controller not converting JSON to Java class

I'm tryng to convert JSON into a java class using Spring.
When I execute the code I get 400 bad request.
If I replace User java object (#RequestBody final **User** user) with generic java Oject (#RequestBody final **Object** user), I get the json string as parameter.
Here's my code.
Javascript:
register : function(usr,pwd) {
var user = {username : usr, password: pwd}
return $http({
method: 'POST',
url: '/SpringSecurityRememberMeAnnotationExample/newuser',
contentType: "application/json",
data:user
});
/*
return $http.post('/SpringSecurityRememberMeAnnotationExample/newuser', user).then(function(response) {
return response.data;
});
*/
},
Controller:
#Controller
#Scope("request")
public class HomeController {
#RequestMapping(value = "/newuser", method = RequestMethod.POST)
#ResponseBody public User SaveUser(#RequestBody final User user){
System.out.println("username: ");// + user.username);
System.out.println("password: ");// + user.password);
return null;
}
spring-mvc.xml
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!-- Login Interceptor -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.websystique.springsecurity.interceptor.LoginInterceptor"/>
</mvc:interceptor>
<!-- workaround to fix IE8 problem -->
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptors>
<!-- i18n -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="useCodeAsDefaultMessage" value="true"/>
<property name="basename" value="WEB-INF/i18n"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="fileEncodings" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="it"/>
<property name="useCodeAsDefaultMessage" value="true"/>
</bean>
<!-- Exception handler -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="LoginRequiredException">
public/loginRequired
</prop>
<prop key="ResourceNotFoundException">
public/notFound
</prop>
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
<!-- View Handler -->
<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/views/" />
<property name="suffix" value=".jsp" />
<property name="order" value="0" />
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
Thank you!
Adding POM.XML config, json part
<!-- JSon -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Recheck the setters/getters for the fields and make sure there is a no-argument constructor. (If you have no constructor, Java will generate a default no-arg one, but if you have added a constructor with arguments yourself, you must take care to implement a no-arg one as well).
Main Problem was on the User class embedded on the controller code. Once I created User.java file on it's own package all goes smoothly.
You are passing malformed json object i guess. you should pass user json data like below.
var user = {"username" : "<username>", "password": "<password>"};
And makes sure User.java has setters/getters for the fields and default constructor.
Please make sure following two jars are present in your application
1. Jackson - core
2. Jackson - mapper
Both Java API are used by spring for XML/JSON processing.
put var user = {"username" : usr, "password": pwd}; in java script,
and do confirm that your User class is right having proper setter getter and proper access to your calling class.

Hibernate, JPA, No Persistence provider for EntityManager named

I'm working on a Swing application with JPA and Hibernate. But every time I try to call following code to get EntityManager
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("abcd");
EntityManager em = emf.createEntityManager();
I get following exceptions:
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named abcd: Provider named org.hibernate.jpa.HibernatePersistenceProvider threw unexpected exception at create EntityManagerFactory:
javax.persistence.PersistenceException
javax.persistence.PersistenceException: Unable to build entity manager factory
and
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Path to persistence.xml is my.jar/meta-inf/persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="abcd" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="xxx"/>
<property name="hibernate.connection.password" value="xxx"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.user" value="xxx"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Dependencies:
All dependencies except junit are in a classpath
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
<scope>compile</scope>
</dependency>
It seems, it cannot find your persistence.xml file. The correct folder for the persistence.xml file is META-INF and not meta-inf.

Spring MVC - problems while returning an object as #ResponseBody (famous Error 406, unsolved)

I've gone through absolutely every single post here related to the subject, trying all suggested here options... and after a couple of days, it still doesn't work for me.
In short, what I want to do is:
Send data from html form to the Spring MVC controller using jquery and $.post function with JSON type.
On the controller side I have a method which should return an object with one file of String type.
1st point works properly, I manage to send a POST request and receive it properly on the controller side. What doesn't work is the answer from controller back to jsp and the function defined for $.post(). I debugged it on web browser side and I can see that the Content-Type of response is not "application/json" (hence the Error 406, I believe).
Here's what I've got:
JSP:
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css"/>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<springForm:form method="POST" commandName="signInDto"
action="/EquipmentManager/signIn.do" id="add-user-form">
<p>
Login:
<springForm:input path="login" />
<springForm:errors path="login" cssClass="error" />
</p>
<p>
Password:
<springForm:password path="password" />
<springForm:errors path="password" cssClass="error" />
</p>
<p>${errorMessage}
<p />
<input type="submit" value="Sign In" />
</springForm:form>
<script type="text/javascript">
function collectFormData(fields) {
var data = {};
for (var i = 0; i < fields.length; i++) {
var $item = $(fields[i]);
data[$item.attr('name')] = $item.val();
}
return data;
}
$(document).ready(
function() {
var $form = $('#add-user-form');
$form.bind('submit', function(e) {
// Ajax validation
var $inputs = $form.find('input');
var data = collectFormData($inputs);
$.post('/EquipmentManager/signInValidate', data,
function(response) {
$form.find('.control-group').removeClass(
'error');
$form.find('.help-inline').empty();
$form.find('.alert').remove();
if (response.value == 'FAIL') {
alarm(response.value);
} else {
$form.unbind('submit');
$form.submit();
}
}, 'json');
e.preventDefault();
return false;
});
});
</script>
</body>
</html>
Controller:
#RequestMapping(value = "/signInValidate", method = RequestMethod.POST)
public #ResponseBody TestObject signInValidate(#Valid SignInDto signInDto,
BindingResult bindingResult) {
TestObject testObject = new TestObject();
if (bindingResult.hasErrors()) {
testObject.setValue("FAIL");
logger.info("FAIL");
} else {
testObject.setValue("SUCCESS");
logger.info("SUCCESS");
}
return testObject;
}
Bean:
public class TestObject {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Dispatcher Servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<context:component-scan base-package="com.equipment.controller" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.esocphotoclub</groupId>
<artifactId>EquipmentManager</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>EquipmentManager Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>EquipmentManager</finalName>
</build>
</project>
I've already tried different versions of jackson-*, explicit defining of ContentNegotiatingViewResolver, explicit specification of produces="application/json" in #RequestMapping, TestObject serialisation, and few other things I've found here. None of them work for me.
To give you as much info as possible, all works fine if I don't request 'json' type in $.post and in the controller I return a simple string. That's not what I want to do though. What I want is to submit a request for validation purpose and receive an object, not a simple string.
Any hint I'll very much appreciate, perhaps there's something I still haven't try.
Many thanks in advance!
I hope you have all jackson mapping and if that is the case you are missing jsonview. Can you try the below. All we are doing is setting multiple view resolvers.
<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="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
Create a file called views.xml in you WEB-INF folder and add the below entry.
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
It took me a few days, but I finally managed to sort this out by trial and error method.
What I did was simply add another jackson dependency in the POM file: jackson-databind and now it works just fine.

Spring tests - problems with rollback

I have created Spring integration test in my application.
The problem is, one test doesn't rollback properly, leaves some stuff in database and causes subsequent tests to fail.
I have noticed, that tests works good if persisted entity is simple entity.
The test fails, when entity is part of inheritance hierarchy and inheritance type is of type InheritanceType.JOINED.
When I change it to InheritanceType.SINGLE_TABLE it desn't fail.
Below is the code:
Test class:
#RunWith(SpringJUnit4ClassRunner.class)
#Transactional
#ContextConfiguration(locations = {"classpath:beans/repository-beans.xml"})
public class OnlyParentRollbackProblemSpringTest {
#PersistenceContext
private EntityManager entityManager;
#Test
//PASSES
public void isDBEmptyTest_1() throws Exception {
Query countQuery = entityManager.createQuery("select count(qi) from " + ParentEntity.class.getSimpleName() + " qi");
int elementsCount = ((Long)countQuery.getSingleResult()).intValue();
assertThat(elementsCount).isEqualTo(0);
}
#Test
//PASSES
public void testThatInfluencesOtherTests() {
ParentEntity queueItem = new ParentEntity();
entityManager.persist(queueItem);
ParentEntity queueItem1 = new ParentEntity();
entityManager.persist(queueItem1);
// given
flush();
// when
Query deleteQuery = entityManager.createQuery("delete from " + ParentEntity.class.getSimpleName());
deleteQuery.executeUpdate();
flush();
// then
Query countQuery = entityManager.createQuery("select count(qi) from " + ParentEntity.class.getSimpleName() + " qi");
int elementsCount = ((Long)countQuery.getSingleResult()).intValue();
assertThat(elementsCount).isEqualTo(0);
}
#Test
//FAILS
public void isDBEmptyTest_2() throws Exception {
Query countQuery = entityManager.createQuery("select count(qi) from " + ParentEntity.class.getSimpleName() + " qi");
int elementsCount = ((Long)countQuery.getSingleResult()).intValue();
assertThat(elementsCount).isEqualTo(0);
}
private void flush() {
entityManager.flush();
entityManager.clear();
}
}
spring configuration:
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/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:component-scan base-package="no.mintra.offlinetrainingportal.infrastructure.persistence" />
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="H2DataSource" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="dataSource" ref="H2DataSource" />
<property name="jpaVendorAdapter" ref="H2JpaVendorAdaptor" />
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.hbm2ddl.auto" value="create-drop" />
</map>
</property>
</bean>
<bean id="H2DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MYSQL;LOCK_MODE=3"/>
</bean>
<bean id="H2JpaVendorAdaptor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />
</bean>
Entities:
#javax.persistence.Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class ParentEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
public ParentEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
public class SecondChildEntity extends ParentEntity {
#Column(unique = true)
#NotNull
private Integer userId;
public SecondChildEntity(Integer userId) {
this.userId = userId;
}
public Integer getUserId() {
return userId;
}
}
And pom.xml file:
<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>test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.8.1</junit.version>
<org.springframework.version>3.1.0.RELEASE</org.springframework.version>
<log4j.version>1.2.15</log4j.version>
<org.slf4j.version>1.5.8</org.slf4j.version>
<hibernate-core.version>3.6.8.Final</hibernate-core.version>
<hibernate-validator.version>4.1.0.Final</hibernate-validator.version>
<commons-dbcp.version>1.2.2</commons-dbcp.version>
<h2database.version>1.3.163</h2database.version>
<commons-collections.version>3.2.1</commons-collections.version>
<javax.servlet.version>2.5</javax.servlet.version>
<javax.validation.version>1.0.0.GA</javax.validation.version>
<fest.version>1.2</fest.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>${fest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<exclusions>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>ejb3-persistence</artifactId>
</exclusion>
</exclusions>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
</dependencies>
This issue is specific to H2 DBMS.
H2Dialect contains the following warning:
if ( !( majorVersion > 1 || minorVersion > 2 || buildId >= 139 ) ) {
log.warn(
"The {} version of H2 implements temporary table creation such that it commits " +
"current transaction; multi-table, bulk hql/jpaql will not work properly",
( majorVersion + "." + minorVersion + "." + buildId )
);
}
You face this issue because executing bulk delete against entity with JOINED inheritance involves creation of temporary table (see generated SQL), so that the first part of transaction gets committed.
As a workaround you can use native SQL queries instead of bulk HQL delete query. Or just use another in-memory database such as HSQLDB.