Spring MVC Integration with Thymeleaf + Existing JSP apache tiles - spring

I am trying to configure Thymeleaf Html page with Spring MVC. I have controller method from which I am trying to return he thymeleaf template html page. Its existing project which uses spring mvc + tiles.I need to integrate thymeleaf in to existing project. The template Engine is autowired which is coming from different Jar file. I have provided configuration below. I am not getting any exception but getting Page Not found when I try to load the page.
IS it possible to have one flow which resolves view with Tiles + Jps and another flow with Thymeleaf template. how can I achieve it .
#Controller
#RequestMapping("/thymeleafConfiguration")
public class ConfigController {
#Autowired
TemplateEngine templateEngine; // This class is coming from different jar and I have
//autowired. xml configuration is provided for reference
#PostConstruct // Changes needs to apply only to certain class so I am using
//postconstruct method in controller
// where I need to use thymeleaf template.
public void Init() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setCacheable(false);
templateResolver.setPrefix("/templates/thymeleafPage/");
templateResolver.setSuffix(".html");
templateEngine.setTemplateResolver(templateResolver);
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setOrder(1);
resolver.setTemplateEngine(templateEngine);
}
#RequestMapping(value = "/view") // controller method where I am redirecting thymeleaf
page
public String viewTemplate(){
return "thymeleaf";
}
}
application-context.xml
<bean id="thymeleafProcessor" class="com.java.ThymeleafTemplateProcessor">
<property name="templateEngine" ref="templateEngine"/>
</bean>
<bean id="htmlStringTemplateResolver" class="org.thymeleaf.templateresolver.StringTemplateResolver">
<property name="templateMode" value="HTML" />
<property name="cacheable" value="true" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="enableSpringELCompiler" value="true" />
<property name="templateResolvers">
<set>
<ref bean="htmlStringTemplateResolver" />
</set>
</property>
</bean>
Project Structure :
myProject
|
|Src
-Java
-templates
-thymeleafPage
- thymeleaf.html
-webContent
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.*</url-pattern>
</servlet-mapping>
Can you please guide me how can I load the Page. I have referred documentation of thymeleaf
ThymeleafDocumetation
Tutorial
I have followed some examples but couldnt find much difference. I appreciate your help.
Jordan

I have found the solution how to make it work for Jsp , HTML and Thymeleaf template together.
Thank you

Related

Html integration with Spring MVC

I had sample poc which I did with jsp and spring mvc and working fine, I configured DispatcherServlet and InternalResourceViewResolver like this
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and in my servlet-context.xml I configured InternalResourceViewResolver like this
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
My request and response are working good.
Now I am trying to start a new sample project with html rather than jsp I changed InternalResourceViewResolver like this
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".html" />
</beans:bean>
but I am getting an exception that
"Info: WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/Organization_Management/WEB-INF/views/check.html] in DispatcherServlet with name 'appServlet'"
I want to start a new sample application with html and spring mvc.
can any one please suggest me in this regard.
Solution 1: In the InternalResourceViewResolver you can leave the Suffix part empty and the InternalResourceViewResolver will resolve both .jsp as well as .html files.
But make sure that in your controller you have have methods that return html views and methods that return jsp views based on the suffix. For example, if index.html and index.jsp both exist in WEB-INF/pages you can do:
#RequestMapping("/htmlView")
public String renderHtmlView() {
return "index.html";
}
#RequestMapping("/jspView")
public String renderJspView() {
return "index.jsp";
}
Solution 2:
Since .html files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an mapping. This requires Spring 3.0.4+.
For example:
<mvc:resources mapping="/static/**" location="/static/" />
which would pass through all requests starting with /static/ to the webapp/static/ directory.
So by putting index.html in webapp/static/ and using return "static/index.html"; from your method, Spring should find the view.

How to configure SockJsHttpRequestHandler using XML in a working application

From spring-websocket-portfolio-master WebConfig.java:
#Bean
public SimpleUrlHandlerMapping handlerMapping() {
DefaultSockJsService sockJsService = new DefaultSockJsService(sockJsTaskScheduler());
//sockJsService.setDummySessionCookieEnabled(true);
HttpRequestHandler requestHandler = new SockJsHttpRequestHandler(sockJsService, stompWebSocketHandler());
SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();
hm.setOrder(-1);
hm.setUrlMap(Collections.singletonMap("/portfolio/**", requestHandler));
return hm;
}
I want to add to XML configuration in current application. I have the following in web.xml:
<servlet>
<servlet-name>mximonitor</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mximonitor</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have this so far (and I hope it is right):
<!-- Following two beans were wrapped in a SimpleUrlHandlerMapping bean -->
<bean id="sockJsService" class="org.springframework.web.socket.sockjs.support.DefaultSockJsService">
<constructor-arg index="0" ref="sockJSTaskScheduler"/>
</bean>
<bean id="sockJsHttpRequestHandler" class="org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler">
<constructor-arg index="0" ref="sockJsService"/>
<constructor-arg index="1" ref="stompWebSocketHandler"/>
</bean>
I would like to be able to add new request handler to existing configuration. I guess I would use 'SimpleUrlHandlerMapping' but I am fairly new to Spring (and web programming in general). How would I configure? Is 'SimpleUrlHandlerMapping' additive (meaning it will not interfere with existing controllers?
Thanks in advance (and for your patience),
James

Spring Controller's URL request mapping not working as expected

I have created a mapping in web.xml something like this:
<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>/about/*</url-pattern>
</servlet-mapping>
In my controller I have something like this:
import org.springframework.stereotype.Controller;
#Controller
public class MyController{
#RequestMapping(value="/about/us", method=RequestMethod.GET)
public ModelAndView myMethod1(ModelMap model){
//some code
return new ModelAndView("aboutus1.jsp",model);
}
#RequestMapping(value="/about", method=RequestMethod.GET)
public ModelAndView myMethod2(ModelMap model){
//some code
return new ModelAndView("aboutus2.jsp",model);
}
}
And my dispatcher-servlet.xml has view resolver like:
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
To my surprise: request .../about/us is not reaching to myMethod1 in the controller. The browser shows 404 error. I put a logger inside the method but it isn't printing anything, meaning, its not being executed.
.../about works fine! What can be the done to make .../about/us request work? Any suggestions?
You need to use #RequestMapping(value="/us", method=RequestMethod.GET) or you need to request about/about/us
Since you have mapped "/about" in your web.xml, the url it will pass will be like this www.xyz.com/about/*
As your configuration says it will work for
www.xyz.com/about/about/us
www.xyz.com/about/about
In order to to work properly either use
/* in web.xml instead of /about
or change the controller's endpoint to
#RequestMapping(value="/us", method=RequestMethod.GET)
#RequestMapping(value="/", method=RequestMethod.GET)
Okay I got the thing working, here are things I added in the dispatcher-servlet.xml:
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true" />
</bean>

RequestMapping not working with multi-level URLs

I have a scenario where I'm making a simple get request through a link and my #RequestMapping configuration is not behaving as I'd expect.
Within an anchor tag I reference a url with the following pattern '/action-plan/export/pdf?token=xxx&taskId=1111&taskId=2222...'
Within my controller class I have this mapping at the class level:
#RequestMapping("/action-plan/export")
And this mapping at the method level
#RequestMapping(value="/pdf", method=RequestMethod.GET)
public String exportToPdf(#RequestParam("taskId") String[] taskIds,
#RequestParam("token") String[] encryptedEmplId, ModelMap model)
But every time I try this I get a 404 page not found error and the following Spring exception:
org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException: No matching handler method found for servlet request: path '/pdf', method 'GET', parameters map['taskId' -> array['1962326', '1962264', '1962317', '1962328', '1962324', '1962427', '1962325', '1962323', '1963147', '1962327', '1962318', '1962329', '1962330'], 'token' -> array['xxxx']]
I've noticed that when I remove the "/pdf?" portion of the link and remove 'value="/pdf"' from the method #RequestMapping it works fine. For the life of me I don't understand why adding /pdf to the url and RequestMapping is not working.
I think danny.lesnik's answer was pretty close but I'm writing my own answer so I can be more verbose.
I was working on a different project and figured out why the above doesn't work. In reference to my original question here is the relevant web.xml servlet mapping:
<servlet-mapping>
<servlet-name>spring-dispatcherServlet</servlet-name>
<url-pattern>/action-plan/export/*</url-pattern>
</servlet-mapping>
I noticed that whatever portion of the path I included in the of web.xml was not being included in the evaluation of RequestMapping values. I would have thought this bean configuration would have prevented that scenario (note the "alwaysUseFullPath" property):
<bean id="annotationHandlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="2"/>
<property name="alwaysUseFullPath" value="true"/>
</bean>
Maybe someone can shed some light on this detail for me.
In any case, thanks danny.lesnik
I recreated your problem and solved it by mapping servlet using .action extentions.
For example:
#Controller
#RequestMapping(value="/test")
public class DefaultController {
#RequestMapping(value="/pdf.action", method=RequestMethod.GET)
public ModelAndView indexView(#RequestParam("taskId") String[] taskIds,
#RequestParam("token") String[] encryptedEmplId){
ModelAndView mv = new ModelAndView("index");
return mv;
}
Spring XML mapping:
<context:annotation-config />
<context:component-scan base-package="com.vanilla.controllers" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
and this web.xml servlet mapping
<display-name>SpringMvcServlet</display-name>
<servlet>
<servlet-name>SpringMvcServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
This code resolves this url
/test/pdf.action?token=3&token=4&taskId=4
flawless.

mvc:view-controller causes PageNotFound in Spring Tiles2

I have a webapp based on Spring 3.0.6 which works fine on Tomcat 7.0.
The web.xml defines the dispatcher as following:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The dispatcher defines the view resolver in the usual way:
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles-def.xml</value>
</list>
</property>
</bean>
I have a controller annotated with #RequestMapping("/home") and a "home" view defined in tiles-def.xml. When I point my browser to the /myapp/home.html, the Tiles page is opened.
If I add <mvc:resources mapping="/resources/**" location="/resources/" /> or <mvc:view-controller path="/" view-name="home.html"/> to my dispatcher xml file, pointing the browser to /myapp/home.html results in a 404. The log says:
21:34:22,128 WARN PageNotFound:947 – No mapping found for HTTP request with URI [/myapp/home.html] in DispatcherServlet with name 'dispatcher'
What am I doing wrong?
Thanks a lot
The problem in my application was due to the automatic view name resolution. My annotated method in my #Controller returned void, and the framework tried to guess the tiles view name using the request path.
I modified my annotated method as following, returning a String:
#RequestMapping(value="/page", method = RequestMethod.GET)
public String showForm(HttpServletRequest request, Model model) {
// TO BUSINESS LOGIC
// return tiles view name as configured in 'tiles-def.xml'
return "my_tiles_view_name";
}
With this change, everything works fine.

Resources