spring mvc and ReloadableResourceBundleMessageSource - spring

I am trying to build a spring MVC application (basically for self trainning reasons). This application has spring MVC, tiles, spring thems and jsp (sorry for numbering all but since i am not sure what i do wrong, i just wish to number all i think may help you help me).
my spring mvc configuration seems to work, untill i try to get message property from property files through org.springframework.context.support.ReloadableResourceBundleMessageSource.
so here is my configuration
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:cacheSeconds="3000">
<property name="basenames">
<list>
<value>messages</value>
<value>dev</value>
<value>theme</value>
</list>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" p:definitions="/WEB-INF/tiles-defs/tiles-defs.xml" />
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver" p:basename="views" />
<!-- Declare the Interceptor -->
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="language"/>
<bean id="themeChangeInterceptor" class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" p:paramName="theme"/>
<!-- Declare the Resolver -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
<bean id="themeResolver" class="org.springframework.web.servlet.theme.SessionThemeResolver"/>
<!-- Spring themes -->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<ref local="themeChangeInterceptor" />
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
tiles and theme seem to work, so in my tiles baselayout i have:
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<c:set var="css"><spring:theme code="css"/></c:set>
<c:if test="${not empty css}">
<link rel="stylesheet" href="<c:url value='${css}'/>" type="text/css"/>
</c:if>
this works! html is rendered with the correct css that i have in css property located inside theme.properties file loaded from ReloadableResourceBundleMessageSource and magically existing inside tiles!
So, getting courage i go to my jsp and insert
attempt 1:
<p><spring:message code="context"/></p>
attempt 2:
<p><fmt:message key="context"/></p>
tags used:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
(is there a difference? both work? seen both over web... so i tried once the first and then the second one)
and in the messages.properties/messages_el_gr.properties files i type context=default and context=greek.
This gives me exception in the first case and in the second just the string context prefixed and postfixed with ???.
Exception i get is:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/homeAutomation] threw exception [Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException: ServletException including path '/WEB-INF/tiles/baseLayout.jsp'.] with root cause
javax.servlet.jsp.JspTagException: No message found under code 'context' for locale 'el_GR'.
at org.springframework.web.servlet.tags.MessageTag.doStartTagInternal(MessageTag.java:184)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
at org.apache.jsp.WEB_002dINF.jsp.friends_jsp._jspx_meth_spring_005fmessage_005f0(friends_jsp.java:104)
at org.apache.jsp.WEB_002dINF.jsp.friends_jsp._jspService(friends_jsp.java:75)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:927)
at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:684)
at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:678)
at org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:103)
at org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:96)
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.renderer.impl.ChainedDelegateAttributeRenderer.write(ChainedDelegateAttributeRenderer.java:76)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:336)
at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:210)
at org.apache.tiles.template.InsertAttributeModel.end(InsertAttributeModel.java:126)
at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:311)
at org.apache.jsp.WEB_002dINF.tiles.baseLayout_jsp._jspx_meth_tiles_005finsertAttribute_005f3(baseLayout_jsp.java:307)
at org.apache.jsp.WEB_002dINF.tiles.baseLayout_jsp._jspService(baseLayout_jsp.java:108)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:241)
at org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:222)
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
at ......
I consider that i do not have the messageSource inside my context, so i considered as next step of searching what is going on to do the following (found on web)
#Autowired
ReloadableResourceBundleMessageSource messageSource;
#RequestMapping("/friends.htm")
public ModelAndView getPage()
{
ModelAndView modelAndView=new ModelAndView("friends");
modelAndView.addObject(messageSource);
return modelAndView;
}
by the way, my previeus controller had that method as follows:
#RequestMapping("/friends.htm")
public String getPage()
{
return friends;
}
This again throws same exception.. messageSource is not null.. it is autowired.
if i do inside the controller:messageSource.getMessage("context", null, Locale.ENGLISH), this throws the same exception when trying to get it.. (Greek locale does not exist?? with english it will go to default locale properties file which is messages.properties, correct?)
Ah, what else can i give you... yes property files are located in the src/main/resources directory and in war inside homeAutomation.war\WEB-INF\classes\ and homeAutomation.war (why?? i thought these would exist only in homeautomation.war directory... but skip this, atleast they are there...) my poms war plugin configuration is as follows:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>src/main/resources</directory>
</resource>
</webResources>
</configuration>
</plugin>
in target directory again i see the property files in both target\classes directory and target\homeAutomation.
After all these, i still do not know what i do wrong and i cannot get localized properties inside my jsp working. I hope i gave al the necessary info (sorry for the too much info..., did not know which was relevant and which not). If you need more info please ask. Have been searching for this five days now and still have no clue.

you can use <p><spring:message code="context"/></p>
but you should have context= what you want in one of the following files :
messages_el_GR.properties
dev_el_GR.properties
theme_el_GR.properties

Related

Getting this error while working on Spring MVC and Apache tiles

I am not sure where the error is.
message
Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException:
org.apache.tiles.util.TilesIOException:
JSPException including path '/WEB-INF/views/hotels/enterBookingInfo.jsp'.
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException:
Request processing failed; nested exception is org.apache.tiles.impl.CannotRenderException:
org.apache.tiles.util.TilesIOException: JSPException including path '/WEB-INF/views/hotels/enterBookingInfo.jsp'.
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause
org.apache.tiles.impl.CannotRenderException: org.apache.tiles.util.TilesIOException:
JSPException including path '/WEB-INF/views/hotels/enterBookingInfo.jsp'.
org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:692)
org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:124)
org.springframework.js.ajax.tiles2.AjaxTilesView.renderMergedOutputModel(AjaxTilesView.java:131)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
tiles.xml defintion is as follows
<tiles-definitions>
<definition name="enterBookingInfo" extends="standardLayout">
<put-attribute name="body" value="/WEB-INF/views/hotels/enterBookingInfo.jsp"> </put-attribute>
</definition>
</tiles-definitions>
Tiles configuration extract
<beans:bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions">
<beans:value>
/WEB-INF/**/tiles.xml
</beans:value>
</beans:property>
</beans:bean>
I got this resolved by setting the commandName attribute of the form to the name of the modelAttribute object used in my controller.
I also had to modify the method syntax to have BindingResult parameter which had to follow the ModelAttribute object.
public String ultimateBooking(#RequestParam("hotelId") String hotelId,#ModelAttribute("booking") Booking bookingValidation,BindingResult result,ModelMap model)
No changes were made to tile.xml

Exception : Cannot render a null template in Spring tiles

I have created one simple DAO interface and DAOImpl class for implementation of DAO. Taking data from the jsp and storing it to database. On successful completion I am rendering to a tiles to xml. I am getting below exception while returning view for tiles. Is there any problem in defining tiles as mentioned in this post ? The data is getting stored in the database but on the frontend I am getting the below exception and also on console.
Aug 11, 2015 4:01:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [User] in context with path [/SpringUser] threw exception [Request processing failed; nested exception is org.apache.tiles.impl.InvalidTemplateException: Cannot render a null template] with root cause
org.apache.tiles.impl.InvalidTemplateException: Cannot render a null template
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:51)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
at org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:124)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:262)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1180)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
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.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:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The tiles file for the same is as below
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="user.reg" template="/jsp/template.jsp">
<put-attribute name="title" value="Sample App"/>
<put-attribute name="header" value=""/>
<put-attribute name="body" value=""/>
<put-attribute name="footer" value=""/>
</definition>
<definition name="user.registration" extends="user.reg">
<put-attribute name="body" value="/jsp/success.jsp" />
</definition>
<definition name="user.registrationUserSuccess" >
<put-attribute name="body" value="/jsp/login.jsp" />
</definition>
<definition name="user.home" >
<put-attribute name="body" value="/jsp/login.jsp" />
</definition>
<definition name="user.profile">
<put-attribute name="body" value="/jsp/profile.jsp" />
</definition>
<definition name="user.error">
<put-attribute name="body" value="/jsp/error.jsp" />
</definition>
</tiles-definitions>
The controller class for the same is as below -
package com.controller;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Controller
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
String errForward = "user.error", forward = null;
#Autowired
UserDAO userDAO;
UserDetails ud = new UserDetails();
#RequestMapping("/registerUser")
public String registerUser(HttpServletRequest request) {
logger.info("### Inside registeration controller ####");
System.out.println("registerUser");
int isSave=0;
Date creation_time=null,lastModTime=null;
SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy 'at' hh:mm:ss a zzz");
Date date=new Date();
String input = ft.format(date);
try {
creation_time = ft.parse(input);
lastModTime = ft.parse(input);
} catch (ParseException e) {
logger.error("/* Unable to parse date ****["+ ft+"]*****/");
}
String fName=request.getParameter("fName");
fName=(fName.equals(""))?"":fName.trim();
String lName=request.getParameter("lName");
lName=(lName.equals(""))?"":lName.trim();
int age=Integer.parseInt(request.getParameter("age"));
age=(age==0)?0:age;
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
ud.setFirstName(fName);
ud.setLastName(lName);
ud.setAge(age);
ud.setPassword(pswd);
ud.setEmail(email);
ud.setCreationTime(creation_time);
ud.setLastModTime(lastModTime);
try{
isSave=userDAO.saveUserDetails(ud);
if (isSave==0){
forward="user.registrationUserSuccess";
logger.info("/******** Successfully saved the data :::["+isSave+"]::: *****/");
}
}catch(Exception e){
logger.error("##### Error while saving use details #####"+e);
return (forward);
}
return (forward);
}
}
Contents of servlet file are as -
?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
</bean> -->
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.controller"></context:component-scan>
<context:component-scan base-package="com.dao"></context:component-scan>
<context:component-scan base-package="com.entity"></context:component-scan>
<!-- title defining -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<!-- defining title file location -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I checked the project from top to bottom. I did not find anything until I changed my directory structure. The jsp page path was inside WEB-INF folder, instead it should be outside WEB_INF and inside WEB CONTENT folder. After correcting the structure I got the required result.

org.springframework.core.NestedIOException: Cannot find Velocity template for URL

Velocity Configuration with spring,I am missing some configuration. Please tell me why it is happening so.
Getting the below error when I hit my url.
SEVERE: Servlet.service() for servlet springDispatcher threw exception
org.springframework.core.NestedIOException: Cannot find Velocity template for URL [layout.vm]: Did you specify the correct resource loader path?; nested exception is org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'layout.vm'
at org.springframework.web.servlet.view.velocity.VelocityLayoutView.checkResource(VelocityLayoutView.java:133)
at org.springframework.web.servlet.view.UrlBasedViewResolver.loadView(UrlBasedViewResolver.java:438)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.createView(AbstractCachingViewResolver.java:186)
at org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:401)
at org.springframework.web.servlet.view.AbstractCachingViewResolver.resolveViewName(AbstractCachingViewResolver.java:103)
at org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1211)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1160)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
spring-context.xml
<bean id="velocityConfig"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/" />
</bean>
<!-- View resolvers can also be configured with ResourceBundles or XML files.
If you need different view resolving based on Locale, you have to use the
resource bundle resolver. -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".vm" />
</bean>
I'm getting the below exception when the velocityconfig is dropped.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.web.servlet.view.velocity.VelocityConfig] is defined: expected single bean but found 0
at org.springframework.beans.factory.BeanFactoryUtils.beanOfTypeIncludingAncestors(BeanFactoryUtils.java:367)
at org.springframework.web.servlet.view.velocity.VelocityView.autodetectVelocityEngine(VelocityView.java:239)
at org.springframework.web.servlet.view.velocity.VelocityView.initApplicationContext(VelocityView.java:225)
at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)
at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:117)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1448)
at org.springframework.beans.fact
If I am not wrong, you will be able to achieve the Velocity configuration using your viewResolver alone.
Modify your prefix to the one mentioned in your resourceLoaderPath and it should be fine (didn't test it myself)
<property name="prefix"><value>/WEB-INF/velocity/</value></property>
Also, you could drop the velocityConfig tag altogether.
you should use
(bean id="ViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver")
not
(bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver")
this bean use 'layout.vm',i also have this problem.

Using the Struts2-Rest-Plugin with Spring

I'm starting to use the Struts2 Rest Plugin in our Spring application.
Let's start with our struts.xml:
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="lang/messages" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
<constant name="struts.mapper.class" value="rest" />
<package name="default">
<action name="document" class="DocumentRestaction" />
</package>
</struts>
Then in Spring, I'm doing the following (to see if the String is injected):
<bean name="DocumentRestaction" class="be.example.actions.DocumentRestaction">
<property name="injected" value="Oh Hai" />
</bean>
I do a POST request to the URL /documents and end up in the create() method, great! In debug, my injected variable is injected. But when I let the debug continue, I get following exception:
4129 [http-8080-2] ERROR org.apache.struts2.rest.RestActionInvocation - Exception processing the result.
java.lang.RuntimeException: Invalid action class configuration that references an unknown class named [DocumentRestaction]
at org.apache.struts2.convention.ConventionsServiceImpl.determineResultPath(ConventionsServiceImpl.java:100)
at org.apache.struts2.convention.ConventionUnknownHandler.determinePath(ConventionUnknownHandler.java:379)
at org.apache.struts2.convention.ConventionUnknownHandler.handleUnknownResult(ConventionUnknownHandler.java:268)
at com.opensymphony.xwork2.DefaultUnknownHandlerManager.handleUnknownResult(DefaultUnknownHandlerManager.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.createResult(DefaultActionInvocation.java:227)
at org.apache.struts2.rest.RestActionInvocation.executeResult(RestActionInvocation.java:221)
at org.apache.struts2.rest.RestActionInvocation.processResult(RestActionInvocation.java:198)
at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:146)
at com.opensymphony.xwork2.DefaultActionProxy.execute(DefaultActionProxy.java:147)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.lang.ClassNotFoundException: DocumentRestaction
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.struts2.util.ClassLoaderUtils.loadClass(ClassLoaderUtils.java:111)
at org.apache.struts2.convention.ConventionsServiceImpl.determineResultPath(ConventionsServiceImpl.java:98)
... 27 more
But the class has been found .. (I ended up in create), why is it saying this? And most importantly, what am I doing wrong?
I'm using Spring v3.0.5, struts2-rest-plugin v2.3.1, struts2-core v2.3.1 and struts2-spring-plugin 2.3.1
In case anyone is looking for a solution to this, this article might help.
There's an omission in the sample code given though - in your applicationContext.xml, make sure you define the "id" and "class" to be the fully qualified class name of your controller:
<bean id="com.mersoft.web.controller.TestController" class="com.mersoft.web.controller.TestController">
<constructor-arg ref="testManager" />
</bean>
Hope that helps. Oh, and to be clear, you don't have to remove the convention plugin as suggested in an earlier comment.

Transaction problem with JPA2-spring-Hibernate

Hi I got a problem with the above integration of the frameworks.
I'm using JPA2 in a maven configuration with the library versions:
Spring 3.0.5
Hibernate 3.5.4
Hibernate-jpa-2.0-api-1.0.0.Final
I'm using the persistence.xml:
<persistence-unit name="AccountingPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.westernacher.wps.bnotk.fibu.domain.BaseEntity</class>
<class>com.westernacher.wps.bnotk.fibu.domain.AccountSettings</class>
<!-- This is not any more necessary, it will be done in spring config.
<properties>
<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
</properties> -->
</persistence-unit>
and the applicationContext.xml:
<context:annotation-config />
<context:component-scan base-package="com.westernacher.wps.bnotk.fibu.dao" />
<context:component-scan base-package="com.westernacher.wps.bnotk.fibu.service" />
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="false"
mode="proxy" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${dataSource.driverClassName}" p:url="${dataSource.url}"
p:username="${dataSource.username}" p:password="${dataSource.password}" />
<context:property-placeholder location="classpath:datasource.properties" />
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
The class AccountSettingsDaoImpl is annotated with #Repository.
The methods for database access in this class are marked with #Transactional:
#Transactional(readOnly=false)
public void save(E entity) {
// entityManager.merge(entity);
// entityManager.flush();
entityManager.persist(entity);
}
The Test class is the following:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/applicationContext.xml")
public class AccountSettingsDaoImplTest {
#Resource
private AccountSettingsDaoImpl accountSettingsDaoImpl;
private final static Long id=1L;
#Test
public void testSave() throws Exception {
AccountSettings accountSettings = new AccountSettings();
accountSettings.setCategory("A");
accountSettings.setDescription("adlkjsadhad asdlkasdkjahsdlkashd ");
accountSettingsDaoImpl.save(accountSettings);
Long localId = accountSettings.getId();
System.out.println("id="+localId);
}
}
But running my JUnit-Tests, I will get the following exception:
29.07.2011 18:46:01 org.springframework.test.context.TestContextManager prepareTestInstance
SCHWERWIEGEND: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#127e942f] to prepare test instance [com.westernacher.wps.bnotk.fibu.dao.AccountSettingsDaoImplTest#6b9c18ae]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.westernacher.wps.bnotk.fibu.dao.AccountSettingsDaoImplTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountSettingsDaoImpl' must be of type [com.westernacher.wps.bnotk.fibu.dao.AccountSettingsDaoImpl], but was actually of type [$Proxy23]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountSettingsDaoImpl' must be of type [com.westernacher.wps.bnotk.fibu.dao.AccountSettingsDaoImpl], but was actually of type [$Proxy23]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:349)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:541)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:297)
... 26 more
29.07.2011 18:46:01 org.springframework.context.support.AbstractApplicationContext doClose
Can anyone help me?
Best Regards, Daniel
You can't inject proxies by concrete type (if they are made by interface) - you should use the interface instead:
#Inject
private AccountSettingsDao accountSettingsDao;

Resources