I am stuck with the transaction in Spring.
I don't know why never do a rollback.
Does anybody know what it is happening?
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Security Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-database.xml, /WEB-INF/spring-security.xml</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
FileCabServiceImpl.java
#Service("FileCabService")
public class FileCabServiceImpl implements FileCabService
{
#Autowired
private FileCabMapper fileCabMapper;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertFileCab(FileCab fileCab)
{
fileCabMapper.insertFileCab(fileCab);
throw new NullPointerException(); // Error to do the rollback
}
}
Controller.java:
#RestController
public class ReservationController
{
private final Logger logger = LoggerFactory.getLogger(ReservationController.class);
#Autowired
ReservationServiceImpl reservationService;
#Autowired
FileCabService fileCabService;
#Autowired
FileCounterService fileCounterService;
#RequestMapping(value = "/api/reservation", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public void reservationProcess()
{
FileCab fileCab = new FileCab();
fileCab.setnUser("user");
fileCab.setiPax(5);
fileCab.setnNamePax("");
Date dateIn = new Date();
fileCab.setdDateIn(dateIn);
fileCab.setdDateOut(dateIn);
fileCab.setnCodeRef("");
int fileCounter = fileCounterService.getiFileCounterByYear(2017, 1);
fileCab.setnTravelFile(String.valueOf(++fileCounter));
fileCab.setiUserGroup(1);
fileCab.setnYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
fileCab.setdOpenDay(Calendar.getInstance().getTime());
fileCab.setiAgency(0);
fileCab.setnStatus("Cerrado");
fileCab.setbPrePaid(0);
fileCab.setbPaid(0);
fileCab.setdDatePrePaid(null);
fileCab.setDcPrePaidAmount(BigDecimal.ZERO);
fileCab.setiTourService(0);
fileCab.setnObservations("");
fileCabService.insertFileCab(fileCab);
}
}
spring-database.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-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"
default-autowire="byName">
<context:annotation-config />
<context:component-scan base-package="es.app.spring" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://xxx.xxx.xxxx.xxx:3306/spring_res?autoReconnect=true" />
<property name="username" value="XXXXXX" />
<property name="password" value="XXXXXX" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="es.app.spring.model"/>
<property name="mapperLocations" value="classpath*:es.app.spring.mappers/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="es.app.spring.mappers" />
</bean>
</beans>
Any help will be appreciate.
Thank you
Related
I have a plugin project containing two portlets. For each portlet I defined its own applicatioContext file which works well but I have to put some definitions in each applicationContext.xml redundantly which I want to avoid.
I'd prefer to put this code
<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
into a parent applicationContext.xml which holds definitions for all portlets and only the specific configurations into the portlet specific applicationContext.xml s.
But this doesn't work. If I don't define the jspResolver in each applicationContext.xml it can't be found resulting in an error.
In my portlet.xml I have defined this init-param for each portlet:
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/spring-mvc-portlet.xml
/WEB-INF/first-portlet.xml</value>
</init-param>
...
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/spring-mvc-portlet.xml
/WEB-INF/second-portlet.xml</value>
</init-param>
whereby spring-mvc-portlet.xml holds the definitions used from all portlets.
The web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Circular-portlet</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-portlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-mvc-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>
<taglib-location>
/WEB-INF/tld/liferay-portlet.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://liferay.com/tld/aui</taglib-uri>
<taglib-location>/WEB-INF/tld/aui.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
The spring-mvc-portlet.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"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scan base-package="com.foo.bar" />
<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
<!-- <context:property-placeholder location="classpath:Config.properties" /> -->
<!-- With Spring 3.1 it should be org.springframework.context.support.PropertySourcesPlaceholderConfigurer -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:Config.properties</value>
</property>
</bean>
</beans>
The portlet1-portlet.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"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- <import resource="spring-mvc-portlet.xml"/> -->
<context:component-scan base-package="com.foo.bar"
use-default-filters="true">
<context:exclude-filter type="assignable" expression="com.foo.bar.portlet2.YyyController"/>
</context:component-scan>
<!-- <bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
<!-- <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> -->
<!-- <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" /> -->
<!-- <property name="prefix" value="/WEB-INF/jsp/" /> -->
<!-- <property name="suffix" value=".jsp" /> -->
<!-- <property name="order" value="1" /> -->
<!-- </bean> -->
</beans>
The portlet2-portlet.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"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- <import resource="spring-mvc-portlet.xml"/> -->
<bean id="xmlConverter" class="com.foo.bar.utils.XMLConverter">
<property name="marshaller" ref="castorMarshaller" />
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
<property name="mappingLocation" value="WEB-INF/res/mappings.xml" />
</bean>
<context:component-scan base-package="com.foo.bar"
use-default-filters="true">
<context:exclude-filter type="assignable" expression="com.foo.bar.portlet.YyyController"/>
</context:component-scan>
<!-- <bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
<!-- <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> -->
<!-- <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" /> -->
<!-- <property name="prefix" value="/WEB-INF/jsp/" /> -->
<!-- <property name="suffix" value=".jsp" /> -->
<!-- <property name="order" value="1" /> -->
<!-- </bean> -->
<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> -->
<!-- <property name="location"> -->
<!-- <value>classpath:Config.properties</value> -->
<!-- </property> -->
<!-- </bean> -->
</beans>
The portlet.xml:
<portlet>
<portlet-name>Portlet1</portlet-name>
<display-name>Portlet 1</display-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/portlet1-portlet.xml</value>
</init-param>
...
I think you are half way through.
Try to put yoour spring-mvc-portlet.xml into web.xml file like this:
<web-app ...>
...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/path/to/your/spring-mvc-portlet.xml</param-value>
</context-param>
...
</web-app>
It serves as definition of common portlet application context. Then put following lines into portlet.xml:
<portlet>
...
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/path/to/your/first-portlet.xml</value>
</init-param>
...
</portlet>
<portlet>
...
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/path/to/your/second-portlet.xml</value>
</init-param>
...
</portlet>
It works for me, so I hope it helps you...
A Spring controller has the following method :
#RequestMapping(value = "reportsOverall.html")
public/* #ResponseBody */
ModelAndView reportsOverall(SearchParameters searchParameters) {
searchParameters = new SearchParameters(840, "SCH_01", "PRM_07");
System.out.println("Inside controller");
String result = overallDetailsService
.getOverallDetails(searchParameters);
System.out.println("result is " + result);
Map<String, String> model = new HashMap<String, String>();
model.put("data", result);
ModelAndView modelAndView = new ModelAndView("reports/reportsOverall",
model);
return modelAndView;
}
I get the expected output on the server-side console :
result is { "_id" : { "SpId" : 840 , "Scheduler_id" : "SCH_01"} , "positive_count" : 64 , "neutral_count" : 78 , "negative_count" : 2}
But in the reportsOverall.jsp, when I retrieve the result object as :
function drawSentimentPieChart() {
var data = '<c:out value="${data}"/>';
alert(data);
var dataJson = JSON.parse(data);
......
}
in the alert I get :
{ "_id" : { "SpId" : 840 , "Scheduler_id" : "SCH_01"} , "positive_count" : 64 , "neutral_count" : 78 , "negative_count" : 2}
The space and "" quotes are encoded here, thereby, causing the parse to fail.
The spring-servlet.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.lnt" />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"></bean>
<!-- <bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
</array>
</property>
</bean> -->
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:userProfile,classpath:default,classpath:messages,classpath:customerAdmin,classpath:reports,classpath:superAdmin" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd hh:mm:ss" />
</bean>
</beans>
I tried several things in the Spring controller :
Using #ResponseBody; in this case, I got a dump on the page like this but the page wasn't rendered properly :
{"view":null,"model":{"data":"{ \"_id\" : { \"SpId\" : 840 , \"Scheduler_id\" : \"SCH_01\"} , \"positive_count\" : 64 , \"neutral_count\" : 78 , \"negative_count\" : 2}"},"empty":false,"viewName":"reports/reportsOverall","reference":true,"modelMap":{"data":"{ \"_id\" : { \"SpId\" : 840 , \"Scheduler_id\" : \"SCH_01\"} , \"positive_count\" : 64 , \"neutral_count\" : 78 , \"negative_count\" : 2}"}}
Added encoding filter to the web.xml :
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Attempted using MappingJacksonJsonView in vain !
What is that I'm overlooking?
I had the same problem, but this additional attribute saved me:
<c:out value="${data}" escapeXml="false"/>
I am using Spring with a JSP and jqGrid and trying to post JSON data to my server.
The GET successfully loads the JSP when I go to the URL:
http://localhost:8080/sportsSpring/sport-management/sport/
My POST successfully saves to the database but fails to reload the JSP afterwards with the exception "Could not resolve view with name 'sport' in servlet with name 'SpringApp'".
SpringApp-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"
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="spring.controller"/>
<!-- To enable #RequestMapping process on type level and method level -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
<bean id="sportController" class="spring.controller.SportController">
<property name="SportDao" ref="SportDao" />
</bean>
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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jd="http://www.springframework.org/schema/jdbc" 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 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="spring.controller,spring.beans"/>
<mvc:annotation-driven />
<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/dbName"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="SportDao" class="spring.controller.SportDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
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>SpringMVC</display-name>
<servlet>
<servlet-name>SpringApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpringApp</servlet-name>
<url-pattern>/sport-management/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tags/c.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
My SportController:
#RequestMapping(method=RequestMethod.GET, value="/sport")
public ModelAndView getSportList() throws NumberFormatException, SQLException, JSONException
{
sportDao = getSportDao();
List<SportBean> sportBeanList = sportDao.getSports();
JSONArray sportJsonArray = convertToJson(sportBeanList);
return new ModelAndView("sport", "sports", sportJsonArray);
}
#RequestMapping(method=RequestMethod.POST, consumes="application/json", value="/sport")
public ModelAndView addSport(#RequestBody String body) throws SQLException, JSONException
{
SportBean sportBean = convertToBean(body, true);
sportDao = getSportDao();
sportDao.saveSport(sportBean);
return new ModelAndView("sport");
}
Any help would be appreciated,
Thank you
Two solutions:
remove this:<property name="prefix" value="/"/>
or try to see what is actually the prefix to your path such as WEB-INF folder for your JSP pages such as <property name="prefix" value="WEB-INF/views/"/>
I have a web application in the following environment.
JPA 2.0
Spring 3.2.2
MySQL 5.6.11
Hibernate 4.2.0 CR1
Apache Tomcat 7.0.35
My configurations until now in the application-context.xml file are as under.
<?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:aop="http://www.springframework.org/schema/aop"
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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<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/social_networking?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="WebAppPU"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect"/>
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="testDAOService" class="admin.dao.TestDAO"/>
</beans>
The persistence.xml contains the following xml.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="WebAppPU" transaction-type="RESOURCE_LOCAL">
<!--<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>-->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>model.Test</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/social_networking?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop"/>-->
</properties>
</persistence-unit>
</persistence>
And the following is the only entity class right now. I have tried to perform an insert operation with this entity which has been succeeded.
package model;
#Entity
public class Test implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id", nullable = false)
private Integer id;
#Column(name = "description", length = 45)
private String description;
private static final long serialVersionUID = 1L;
public Test() {}
public Test(Integer id) {
this.id = id;
}
// Getters and setter.
}
Although the application runs, the following exception can be seen on the server console.
ERROR: HHH000299: Could not complete schema update
java.lang.NullPointerException
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences(DatabaseMetadata.java:156)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.<init>(DatabaseMetadata.java:70)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.<init>(DatabaseMetadata.java:63)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:196)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:178)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:505)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3926)
at org.apache.catalina.manager.ManagerServlet.reload(ManagerServlet.java:954)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:364)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1822)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Tried to use the following property inside the persistence.xml file but didn't help.
<property name="hibernate.hbm2ddl.auto" value="update"/>
What might be the reason?
It looks like you're incorrectly mixing Hibernate dialects and databases. In your original issue you have a MySQL database and a dialect of org.hibernate.dialect.HSQLDialect (see first code block below).
In your solution you have the MySQL database and the correct dialect of org.hibernate.dialect.MySQL5Dialect (see second code block below).
If you had changed the databasePlatform in the original to be the MySQL dialect it would have worked as well.
Original:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
...
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect"/>
</bean>
</property>
...
</bean>
Working:
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="WebAppPU" transaction-type="RESOURCE_LOCAL">
...
<properties>
...
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
...
</properties>
</persistence-unit>
</persistence>
In my case, the reason was that the disk was out of space.
I have an instance on OpenShift, and first JDBC started throwing some exception because MySQL was down, filling the logs with garbage, and that filled the disk in the end.
The problem in question vanished, when I insisted upon using a JNDI lookup. Accordingly, in the context.xml file, I have defined a resource like,
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/WebApp">
<Resource name="jdbc/social_networking"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/social_networking"/>
</Context>
The resource reference needs to be defined in the web.xml file like,
<resource-ref>
<res-ref-name>jdbc/social_networking</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
This datasource is referenced in the the persistence.xml file as follows.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="WebAppPU" transaction-type="RESOURCE_LOCAL">
<!--<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>-->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:comp/env/jdbc/social_networking</non-jta-data-source>
<class>model.Test</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.datasource" value="java:comp/env/jdbc/social_networking"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
</properties>
</persistence-unit>
</persistence>
And finally the application-context.xml file has been modified as follows.
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="admin.mangedbean converter" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
<context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>
</context:component-scan>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
<property name="jpaProperties">
<props>
<prop key="hibernate.enable_lazy_load_no_trans">false</prop>
<!-- I use fetch joins or queries/subqueries with a desired/required list of columns only for lazily loaded collections, when they are required to be fetched from outside of an active transaction boundary.
Therefore it is set to false. -->
</props>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false"/>
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/social_networking"/>
</bean>
<!--Bean registration-->
<bean id="testService" class="admin.dao.TestDAO"/>
</beans>
Please check if the table for entity exist.
If it exist then you get error for the below property.
<property name="hibernate.hbm2ddl.auto" value="update"/>
Change it to
<property name="hibernate.hbm2ddl.auto" value="create"/>
This will create the new entity table.
I am using POST MAN CLIENT of GOOGLE CHROME TO SEND articleName and articleId AS HEADER application/json.What things I needed to change in my controller and library as well as in my spring servlet.xml?My controller is as follows.
public class ArticleController {
#Autowired
private ArticleService articleService;
Article article = new Article();
Long articleId = article.getArticleId();
#RequestMapping(value = "/save", method = RequestMethod.POST)
public Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
int a = articleService.addArticle(article);
if (a == 1) {
return new ModelAndView("success");
} else {
return new ModelAndView("error");
}
}
My Spring servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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-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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="net.roseindia" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<mvc:annotation-driven />
<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.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>net.roseindia.model.Article</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.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Plz help me out....Thanks in advance.
I assume what you want is to return JSON easily from Spring.
To do that you need Jackson dependency:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
When you have it,
you can annotate your method with #ResponseBody annotation just like this:
public #ResponseBody Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
....
}
Such a method will return JSONified Article object in response.