Json Root Name not coming in Camel Swagger Rest Service - json

I am trying to create rest service using apache camel swagger component.
Now i have this camel context 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:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<!-- a bean for user services -->
<bean id="personService" class="www.tempuri.person.PersonService"/>
<camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring">
<restConfiguration component="servlet" bindingMode="auto" contextPath="myService/rest" port="8080">
<dataFormatProperty key="prettyPrint" value="true"/>
</restConfiguration>
<!-- defines the rest services using the context-path /Equipment -->
<rest path="/getPerson/persons" consumes="application/json,application/xml" produces="application/json,application/xml">
<description>Person rest service</description>
<post uri="/search" type="www.tempuri.person.model.GetPerson"
outType="www.tempuri.person.model.GetPerson">
<description>Get Person(s)</description>
<param name="body" type="body" description="Get Person(s)" required="true"/>
<responseMessage code="400" message="Bad Request" />
<responseMessage code="200" message="Person Data" />
<responseMessage code="401" message="Unauthorized" />
<to uri="bean:personService?method=getPersons"/>
</post>
</rest>
</camelContext>
</beans>
And below is my model class GetPerson:
package www.tempuri.person.model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonRootName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#ApiModel(description = "Represents Persons")
#XmlRootElement(name="getPerson")
#JsonRootName(value = "getPerson")
public class GetPerson {
#ApiModelProperty(value = "Application Area of GetPerson", required = true)
private ApplicationArea applicationArea;
#ApiModelProperty(value = "Data Area of GetPerson", required = true)
private DataArea dataArea;
/**
* #return the dataArea
*/
public DataArea getDataArea() {
return dataArea;
}
/**
* #param dataArea the dataArea to set
*/
public void setDataArea(DataArea dataArea) {
this.dataArea = dataArea;
}
public ApplicationArea getApplicationArea() {
return applicationArea;
}
public void setApplicationArea(ApplicationArea applicationArea) {
this.applicationArea = applicationArea;
}
}
Now in case of application xml it is working good and the request structure has a root element as getPerson, but in case of JSON Request it doesn't show the root element getPerson. I know that there is something called WRAP_ROOT_VALUE which can be used to enable the root name in case of json. But the problem is i don't know how to do it using camel-config.xml.
How can i set the WRAP_ROOT_VALUE through my camel-config.xml or is there some other way. Thanks in advance..

Related

Kundera Redis plugin returns empty list on query

I am trying to resolve a problem where I cannot return a list with Kundera query for redis back end. I have problem returning a single entity and no problem persistening entities. However when I try to do a simple select to return a single type it always returns me an empty list.
<persistence 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
https://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="redis_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>com.factory.ng.api.domain.DomainEntity</class>
<class>com.factory.ng.api.domain.Factory</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="kundera.show.query" value="true" />
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="6379" />
<property name="kundera.keyspace" value="RedisK" />
<property name="kundera.dialect" value="redis" />
<property name="kundera.client" value="redis" />
<property name="kundera.client.lookup.class" value="com.impetus.client.redis.RedisClientFactory" />
<property name="kundera.transaction.resource.class" value="com.impetus.client.redis.RedisTransaction" />
<property name="kundera.indexer.class" value="com.impetus.client.redis.RedisIndexer" />
</properties>
</persistence-unit>
...
Here is the entity that I am trying to retrieve.
#Entity
#XmlRootElement
public class Factory extends DomainEntity implements IHasSlots {
/**
* Serialization Id
*/
private static final long serialVersionUID = 7829467874878679280L;
private String name;
private List<Line> lines;
public Factory() {
this(null);
}
public Factory(String name) {
this(name, new ArrayList<Line>());
}
public Factory(String name, Collection<Line> lines) {
this(name, new ArrayList<Line>(lines));
}
...
This unit test always ends with an assert error that the list is empty.
#Test
public void testList() {
EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("redis_pu");
EntityManager em = emFactory.createEntityManager();
List<Factory> factories = em.createQuery("SELECT e FROM Factory e").getResultList();
//Collection<Factory> factories = factoryDao.list();
Assert.assertTrue(factories.size() > 0);
}

Why jackson formats date to yyyy-MM-dd instead of timestamp?

I have my first spring project with a rest service.
Only one problem I cannot solve myself. My "get" request gives the objects date value this way:
{"id":6,"type":"Trainer","changed":"2015-06-20","created":"2015-06-19"}
but I want it in timestamp format, as I thought was the default.
The input dates in my PUT request are parsed from timestamp format as expected.
I am using springframework 4.1.6.RELEASE and fasterxml.jackson 2.5.4
with these spring artifacts: spring-context, spring-webmvc, spring-jdbc
and these fasterxml artifacts: jackson-core, jackson-databind
This is my Controller method:
#Override
#RequestMapping(value="/{id}", method=RequestMethod.GET)
#ResponseBody
public T getObject(#PathVariable("id") long id) {
T obj = dao.getById(id);
logger.debug("GET " + getClass().getSimpleName() + "." + id + ": " + obj);
return obj;
}
My 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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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
classpath:Beans.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>
</web-app>
servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="de.kreth.clubhelperbackend" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
and my Beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/clubhelperbackend" />
<property name="username" value="markus" />
<property name="password" value="0773" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<bean id="sqlForDialect" class="de.kreth.clubhelperbackend.SqlForMysql">
<constructor-arg ref="jdbcTemplate" />
</bean>
<bean id="personDao" class="de.kreth.clubhelperbackend.dao.PersonDao">
<property name="sqlDialect" ref="sqlForDialect" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="dbcheckAspect" class="de.kreth.clubhelperbackend.aspects.MysqlDbCheckAspect">
<constructor-arg ref="dataSource" />
</bean>
<!-- <bean id="logger" class="de.kreth.clubhelperbackend.aspects.LoggerAspect" /> -->
<aop:aspectj-autoproxy>
<aop:include name="dbcheckAspect" />
<!-- <aop:include name="logger"/> -->
</aop:aspectj-autoproxy>
</beans>
So, how can I get the json date output in general as a timestamp?
Please note, that I don't want to change the data classes (getters) as they are generated from another project.
--- Edit:
The Person Model:
public class Person implements java.io.Serializable, Data {
private static final long serialVersionUID = -2810735258874241724L;
private Long id;
private String type;
/** Not-null value. */
private java.util.Date changed;
/** Not-null value. */
private java.util.Date created;
public Person() {
}
public Person(Long id) {
this.id = id;
}
public Person(Long id, String type,java.util.Date changed, java.util.Date created) {
this.id = id;
this.type = type;
this.changed = changed;
this.created = created;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/** Not-null value. */
public java.util.Date getChanged() {
return changed;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setChanged(java.util.Date changed) {
this.changed = changed;
}
/** Not-null value. */
public java.util.Date getCreated() {
return created;
}
#Override
public void setCreated(Date created) {
this.created = created;
}
}
The date interface:
package de.kreth.clubhelperbackend.pojo;
import java.util.Date;
public interface Data {
public Long getId() ;
public void setId(Long id);
public Date getChanged();
public void setChanged(Date changed);
public Date getCreated();
public void setCreated(Date created);
}
According Jackson docs, Jackson should use timestamps in miliseconds by default.
So I see two options. One is that your date format is enforced by #JsonFormat annotation on your date field as #beerbajay mentioned in his comment.
Second option is that somebody configured custom ObjectMapper for your MappingJacksonHttpMessageConverter. Such example configuration is in this SO answer. I would try to find it in your application and talk to the teammate that introduced it why it's needed.
If such custom ObjectMapper isn't configured, it's strange, but at least you can try to explicitly configure SerializationConfig.getDateFormat as WRITE_DATES_AS_TIMESTAMPS to true.
I think Jackson treats java.util.Date and java.sql.Date differently. Even though the later is actually a subclass of the former, Jackson assumes both classes are totally different.
So, if you don't want the value to be converted to 'yyyy-MM-dd', ensure that it is not a java.sql.Date object.
For example:
class Student {
private java.util.Date birthDate;
// getter and setter
}
Student san = new Student();
// Then JSON converted to: 'yyyy-MM-dd' format
san.setBirthDate(new java.sql.Date(System.currentTimeMillis()));
// Then JSON converted to: timestamp format or according to #JsonFormat format
san.setBirthDate(new java.util.Date());

How to persist image in mysql database using Spring MVC and JPA

This is my imageForm.jsp:
%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title></title>
</head>
<body>
<h2>Image Form</h2>
<form:form method="POST" action="/showImage">
Picture: <input type="file" name="image">
<br />
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
This is showImage.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<h2>Show Image</h2>
<p>Profile Picture : ${image.image}</p>
</body>
</html>
And this is my controller:
package com.springapp.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#RequestMapping(value = "/imageForm")
public ModelAndView showImageForm(Model model) {
return new ModelAndView("imageForm", "command", new Image());
}
#Transactional
#RequestMapping(value = "/showImage")
public ModelAndView showResult(#ModelAttribute("")Image image, ModelAndView model) {
model.setViewName("showImage");
System.out.println("Transaction");
em.persist(image);
System.out.println("persisted");
model.addObject("image", image);
return model;
}
}
This is the Image.java model class:
package com.springapp.mvc;
import javax.persistence.*;
#Entity
public class Image {
#Id
private int imageID;
private byte[] image;
public int getImageID() {
return imageID;
}
public void setImageID(int imageID) {
this.imageID = imageID;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
And the persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.springapp.mvc.Image</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/advocatoree"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
I can choose an image from my PC and when I press the submit button, the showImage.jsp page shows me this: Profile Picture : [B#1c6a19f
The entry is persisted in database, but under the image attribute, it shows: [BLOB - 39 B]
If I click on it, I get a .bin file downloaded. I don't how I should approach this problem, can someone please help me?
the best way to do it - save the picture in any working directory using FileOutputStream, in db you can save unique picture name or path to it. Also you shall receive from the client byte[] in base64 format. The problem may be that you get an byte array represented as string (like "asd561$%#!"), then use Base64.getDecoder().decode(your_string).

Test Camel Integration with JUnit

I have a Camel integration flow. At one point, there is client creation, which is as following configuration:
<routeContext id="clientCreation" xmlns="http://camel.apache.org/schema/spring">
<route customId="true" id="clientCreationRouter">
<from uri="direct:client-creation-start" customId="true" id="Client-Creation-Initiator"/>
<bean ref="clientCreationService" method="constructClientDto" />
<bean ref="clientCreationService" method="populateClientRequestMessage" />
<bean ref="clientCreationService" method="saveClientDetails" />
<bean ref="clientCreationService" method="createClientCreationFixedLengthMessage" />
<setHeader headerName="flow-status" customId="true" id="Client-Creation-Update-Header">
<simple>CLIENT_CREATED</simple>
</setHeader>
</route>
</routeContext>
ConstructClientDto has FlowInfo object as the input.
createClientCreationFixedLengthMessage has a String as the output. I want to test this part of the flow. Basically, I want to provide a FlowInfo object which is ready for Client-Creation and then see whether this part of the integration is successful based on the result provided at the end.
So far, this is what I tried:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration (locations={"/META-INF/spring/data-extractor.xml",
"/META-INF/spring/data-splitter.xml",
"/META-INF/spring/client-creation.xml"})
public class ClientCreationFlowTest extends CamelTestSupport{
#Produce (uri = "direct:client-creation-start")
protected ProducerTemplate template;
#EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
#Autowired
FlowRepository repository;
#Test
public void testClientCreation () throws Exception {
FlowInfo flowInfo = repository.findById("1234");
template.sendBody(resultEndpoint, flowInfo);
}
}
When I run the test case, I get success. But when I debugged it, it does not seemed to be running through ClientCreationService. I am very new to Camel and the task is critical. Any help would be appreciated.
First, in your route definition you must send the result to mock:result at the end:
<routeContext id="clientCreation" xmlns="http://camel.apache.org/schema/spring">
<route customId="true" id="clientCreationRouter">
<from uri="direct:client-creation-start" customId="true" id="Client-Creation-Initiator"/>
<bean ref="clientCreationService" method="constructClientDto" />
<bean ref="clientCreationService" method="populateClientRequestMessage" />
<bean ref="clientCreationService" method="saveClientDetails" />
<bean ref="clientCreationService" method="createClientCreationFixedLengthMessage" />
<setHeader headerName="flow-status" customId="true" id="Client-Creation-Update-Header">
<simple>CLIENT_CREATED</simple>
</setHeader>
<to uri="mock:result"/>
</route>
</routeContext>
Second, in your JUnit test class you must not send the message to the mock endpoint but to direct:client-creation-start which is automatically done as the template is autowired with this uri:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration (locations={"/META-INF/spring/data-extractor.xml",
"/META-INF/spring/data-splitter.xml",
"/META-INF/spring/client-creation.xml"})
public class ClientCreationFlowTest extends CamelTestSupport{
#Produce(uri = "direct:client-creation-start")
protected ProducerTemplate template;
#EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
#Autowired
FlowRepository repository;
#Test
public void testClientCreation () throws Exception {
FlowInfo flowInfo = repository.findById("1234");
resultEndpoint.expectedBodiesReceived("my string output");
template.sendBody(flowInfo);
resultEndpoint.assertIsSatisfied();
}
}
Try template.sendBody(flowInfo); instead of directly sending it to the result endpoint, which bypasses your whole route.

Welcome file not working with html file in spring

I have given my welcome file in web.xml
But when running the application, it is showing 404 error on http://172.16.2.16:8080/sampletest/
It is a spring application.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>sampletest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Spring MVC -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I am using eclipse luna, java 8, tomcat 8 and maven framework.
index.html file is directly under webapp folder and web.xml is under webapp/WEB-INF folder.
If I use index.jsp instead of index.html, it is working. Then welcome page will load using http://172.16.2.16:8080/sampletest/
The issue is only with welcome file. Otherwise spring configuration is working.
http://localhost:8080/sampletest/test/ will load the data from database.
Error log in console
......................
Jul 10, 2014 12:38:42 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 4963 ms
Jul 10, 2014 12:38:42 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/sampletest/] in DispatcherServlet with name 'dispatcher'
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
Dispatcher
<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:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<context:component-scan base-package="com.sample.test" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan">
<array>
<value>com.sample.test.domain</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.CharSet">UTF-8</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sampletest?autoConnect=true" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- HibernateTransactionManager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
<property name="flushModeName">
<value>FLUSH_AUTO</value>
</property>
</bean>
</beans>
Controller
package com.sample.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sample.test.dto.Response;
import com.sample.test.facade.AccelFlowFacade;
#Controller
public class SampleTestController {
#Autowired
#Qualifier("sampleTestFacade")
SampleTestFacade sampleTestFacade;
public SampleTestFacade getSampleTestFacade() {
return sampleTestFacade;
}
public void setSampleTestFacade(SampleTestFacade sampleTestFacade) {
this.sampleTestFacade= sampleTestFacade;
}
#RequestMapping(value = "/test", method = RequestMethod.GET)
public #ResponseBody Response display() throws Exception {
sampleTestFacade.disaply();
Response res = new Response();
return res;
}
}
Try adding <mvc:default-servlet-handler/> in your dispatcher-servlet.xml.
See here for details.
You have mapped all your incoming requests to the dispatcher here,
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
So all your URL requests for the application goes inside the dispatcher as '/' maps all incoming requests . check for the stacktraces in your application server log
update:
You get the below warning because there are no handler for the '/' pattern,
WARNING: No mapping found for HTTP request with URI [/AccelFlow/] in
DispatcherServlet with name 'dispatcher'
You can do either of below options ,
Map a url with '/' to the controller
Add a specific URL pattern to the spring dispatcher such as .htm or .do as you wish
Modify your web.xml,
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
And in your controller,
#RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public #ResponseBody Response display() throws Exception {
accelFlowFacade.disaply();
Response res = new Response();
return res;
}
At the startup by default all incoming requests are mapping to '/' pattern as you write in the web.xml:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
update:
Try to map a Controller method for the default view:
#RequestMapping(value = "/", method = GET)
public String welcome() {
return "index";
}
Add viewresolver to dispather-servlet.xml:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/"
p:suffix=".jsp" />
Remove welcome file from the web.xml as automatically spring will search for index page by default:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Welcome file can be access using following changes.
change 1. add resource path in dispatcher as following :
<mvc:resources mapping="/" location="/index.html" />
change 2. add controller handler like following :
#Controller
public class RestController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome() {
return "index.html";
}
}
changes 3: index.html file should be in WebContent folder in project.
Note : If you are not able to add mvc bean in dispatcher servlet file then add
xmlns:mvc="http://www.springframework.org/schema/mvc
in dispatcher servlet config file.
using <mvc:resources mapping="/" location="/index.html" /> is goods for static pages , however changing it to
#RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome() {
return "index.html";
}
is not good design as all model in other controllers may point back to index page, instead use
<mvc:resources mapping="/" location="/redfresh.html" />
and make refresh page such
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="refresh" content="0;URL='/index'" />
</head>
<body>
</body>
</html>
and point in controller to index such:
#Controller
public class indexPageController {
#RequestMapping(value = "/index", method = RequestMethod.GET, produces = "text/html")
public String index() {
return "index";
}
}
Just add your index.html to webContent folder. Because welcome file is searched in that folder itself.