HTML page and Spring - html

I create Simple MVC project in Spring. Defaultr generic a jsp pages. I try change jsp to html and i:
<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>
replace this:
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".html" />
</beans:bean>
and create html page in views folder, but after changes and try run i have this error:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/myapp/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'
Why i have this error? I only change jsp to html.

The InternalResourceViewResolverdoes not forward the request to the view folder. Instead it is responsible for selecting the 'jsp' (or what ever) according to the return value of an Controller(Method). Like
#RequestMapping("home")
public ModelAndView controllerMethodForHome(){
//will render /WEB-INF/views/homeView.html
return new ModelAndView("homeView");
}
with:
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".html" />
</beans:bean>
will return the /WEB-INF/views/homeView.html for localhost:8080/myApp/home
Maybe the thing you want to use is the static resource mapping
<mvc:resources mapping="/css/**" location="/resources/css/" />
Have a look at this question/answer for an example

Related

Basic CRUD application using SpringMvc hibernate MySql and maven

I'm a beginner in spring and hibernate Frameworks and all I need is a CRUD app complete and working tutorial to start. I tried many tutorials but none of them worked for me :( I'll be so glad if someone could possibly help me..
Have a great day
you can refer bellow link for basic tutorial spring and hibernate Frameworks with mysql database creation.:
http://www.journaldev.com/3524/spring-hibernate-integration-example-tutorial
https://dzone.com/tutorials/java/spring/spring-hibernate-integration-1.html
this is my spring-servlet.xml file
<resources mapping="/resources/**" location="/resources/" />
<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>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/CountryData" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.arpit.java2blog.model.Country</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<context:component-scan base-package="org.arpit.java2blog" />
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>

Way to map Spring viewresolver to html file

I am doing project on Spring MVC with html file as viewResolver. Already my project done in ftl (freemarker template) files as viewResolver perfectly. But I want to do conversion of all ftl files into html files. Hence I have tried hard for two days and do some configuration changes in view resolver like below, but nothing worked.
My original code in applicationContext.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".ftl" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="allowRequestOverride" value="false" />
<property name="exposeSessionAttributes" value="true" />
<property name="allowSessionOverride" value="false" />
<property name="exposePathVariables" value="true" />
<property name="requestContextAttribute" value="rc" />
</bean>
I have made some changes like below
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
</bean>
My DispatcherServlet configuration
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></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>
My html files are in "/WEB-INF/views/" folder. What changes I need to do to run the html files. Any alternate way also warmly welcome. Thanks in advance guys...
HTML pages meant for implementing static views, we have great feature in spring to render the static resources like html, css and images i.e.
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
Similar question asked here SpringViewResolver for HTML views
================================ SOLUTION ========================================
Newly created Folder structure:
WEB-INF
`-static
|-html
`-index.html
Spring config:
<resources mapping="/static/**" location="/WEB-INF/static/" />
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="" />
<beans:property name="suffix" value=".html" />
</beans:bean>
My web.xml
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></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>
Controller method:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String homePage(ModelMap model, HttpServletRequest servletRequest, HttpServletResponse response) {
String returnText = "static/html/index";
return returnText;
}
I have searched and implemented various ways. Its now working like a boss.
Below link helped me and stiched my time a lot. Also need to work various html files with this solution.
Spring MVC ViewResolver not mapping to HTML files

spring & tiles - including .html files

I've got a spring project using tiles as UI framework. I wanted to provide a generic controller handling static html files (no dynamic content - so no custom controllers). The generic controller is org.springframework.web.servlet.mvc.UrlFilenameViewController. The whole thing works for if I put static content in .jsp extension files. As long as I try to put them in .html - I get 404 error and I want to figure out why.
web.xml:
<display-name>
lyricsBase
</display-name>
<servlet>
<servlet-name>lyricsBaseApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>lyricsBaseApp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>list.html</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/404.jsp</location>
</error-page>
lyricsBaseApp-servlet.xml:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
<bean id="staticViewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController">
<property name="prefix" value="t." />
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/list.html">jukeboxController</prop>
<prop key="/display.html">songController</prop>
<prop key="/static/about.html">staticViewController</prop>
</props>
</property>
</bean>
tiles.xml:
<definition name="t.base" template="/WEB-INF/tiles/base.jsp">
<put-attribute name="title" value="SomeTitle"/>
</definition>
<definition name="t.static/about" extends="t.base">
<put-attribute name="body" value="/WEB-INF/static/about.jsp"/>
<put-attribute name="title" expression="about"/>
</definition>
This is the URL I'm accessing the static page at: http://localhost:8084/lyricsBase/static/about.html
I've got both about.html and about.jsp files in the proper directory. If a
<put-attribute name="body" value="/WEB-INF/static/about.jsp"/>
to
<put-attribute name="body" value="/WEB-INF/static/about.html"/>
I start getting the warning in tomcat:
2013-02-16 18:21:45 org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/lyricsBase/WEB-INF/static/about.html] in DispatcherServlet with name 'lyricsBaseApp'
Why?
I know this question was asked 2 years ago, but I encountered the same problem and maybe sometime someone else.
I think Tiles only supports JSP, Freemarker or Velocity. I could find a workaround. Define a static handler like so:
#Configuration
#EnableWebMvc
#ComponentScan(value = "com.xy"))
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/lyricsBase/static/**")
.addResourceLocations("/WEB-INF/static/");
}
}
now you should be able to use your html template by tiles:
<put-attribute name="body" value="/lyricsBase/static/about.html"/>

Spring configuration - mvc:annotation-driven, AnnotationMethodHandlerAdapter, and JSON

Thanks in advance any help.
I'm trying to get one of my controller methods to return JSON. Starting off with a simple test:
#RequestMapping(value="/myReqPath", method=RequestMethod.GET)
#ResponseBody
public Map<String, String> myJsonMethod() {
Map<String, String> response = new TreeMap<String, String>();
response.put("test", "test");
return response;
}
It's my understanding that I need <mvc:annotation-driven/> added to my servlet context to accomplish this. The problem is when I add it, it breaks my custom AnnotationMethodHandlerAdapter.
[B]How do I extract and add the needed parts of <mvc:annotation-driven/> to return JSON from the controller?[/B]
Here are the pertinent parts of my servlet config:
<!--Skipping this for now...
<mvc:annotation-driven/>
-->
<!-- JSON Marshaling -->
<util:constant id="jsonBasicClassIntrospector"
static-field="org.codehaus.jackson.map.introspect.BasicClassIntrospector.instance" />
<bean id="jsonJaxbAnnotationIntrospector"
class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jsonVisibilityChecker"
class="org.codehaus.jackson.map.introspect.VisibilityChecker.Std"
factory-method="defaultInstance" />
<bean id="jsonDefaultTypeFactory"
class="org.codehaus.jackson.map.type.TypeFactory"
factory-method="defaultInstance" />
<bean id="jsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationConfig">
<bean class="org.codehaus.jackson.map.SerializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
<property name="deserializationConfig">
<bean class="org.codehaus.jackson.map.DeserializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
</bean>
...
<!-- My custom AnnotationMethodHandlerAdapter... -->
<bean id="sessionArgResolver" class="com.SessionParamArgumentResolver"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
</bean>
As it stands, my controller method is invoked however, the browser returns http status 406:
406 Not Acceptable - [url]http://localhost:8080/myApp/myReqPath[/url]
If you already have a custom AnnotationMethodHandlerAdapter declaration, you can just add a list of HttpMessageConverters to it:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
<property name = "messageConverters">
<list>
<bean
class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name = "objectMapper" ref = "jsonObjectMapper" />
</bean>
</list>
</property>
</bean>

configuring the jacksonObjectMapper not working in spring mvc 3

What I am aiming to do is to configure spring mvc 3 to not return “null” object in json response.
I've asked the question how to configure spring mvc 3 to not return "null" object in json response? . And the suggestion I got is to configure the ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL. So Based on Spring configure #ResponseBody JSON format, I did the following changes in spring config file. But I got the error "Rejected bean name 'jacksonObjectMapper': no URL paths identified org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping:86-AbstractDetectingUrlHandlerMapping.java" during app startup.
<?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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<!--<mvc:view-controller path="/" view-name="welcome"/>-->
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_DEFAULT</value>
</list>
</property>
</bean>
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
I have no idea why it's been rejected. Any suggestion is greatly appreciated!
<mvc:annotation-driven /> and AnnotationMethodHandlerAdapter cannot be used together. (ref: spring forum thread). Possible solution
do not use <mvc:annotation-driven/>. Declaring bean: DefaultAnnotationHandlerMapping
and AnnotationMethodHandlerAdapter and other settings like validation, formatting.
use spring 3.1, which has <mvc:message-converters> (ref: Spring jira)