I have restful webservice with spring which has following mapping:
<?xml version="1.0"?>
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Object Mapping DTD Version 1.0//EN"
"http://Castor.exolab.org/mapping.dtd">
<mapping>
<class name="com.example.web.Contacts">
<field name="contacts" type="com.example.web.model.Contact"
collection="arraylist">
<bind-xml name="contact" />
</field>
</class>
<class name="com.example.web.model.Contact" identity="id">
<map-to xml="contact" />
<field name="id" type="long">
<bind-xml name="id" node="element" />
</field>
<field name="firstName" type="string">
<bind-xml name="firstName" node="element" />
</field>
<field name="lastName" type="string">
<bind-xml name="lastName" node="element" />
</field>
<field name="birthDate" type="string" handler="dateHandler">
<bind-xml name="birthDate" node="element" />
</field>
<field name="version" type="integer">
<bind-xml name="version" node="element" />
</field>
</class>
<field-handler name="dateHandler"
class="com.example.web.DateTimeFieldHandler">
<param name="date-format" value="yyyy-MM-dd" />
</field-handler>
</mapping>
Contacts class:
public class Contacts implements Serializable {
private List<Contact> contacts;
public Contacts() {
}
public Contacts(List<Contact> contacts) {
this.contacts = contacts;
}
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
Contact class:
#Entity
#Table(name = "contact")
public class Contact implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private int version;
private String firstName;
private String lastName;
private DateTime birthDate;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
public Long getId() {
return id;
}
#Version
#Column(name = "VERSION")
public int getVersion() {
return version;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
#Column(name = "BIRTH_DATE")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getBirthDate() {
return birthDate;
}
public void setId(Long id) {
this.id = id;
}
public void setVersion(int version) {
this.version = version;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setBirthDate(DateTime birthDate) {
this.birthDate = birthDate;
}
#Override
public String toString() {
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: "
+ birthDate;
}
}
When I process GET with xml format from curl, I am receiving following output:
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<contacts>
<contacts>
<id>1</id>
<version>0</version>
<firstName>Chris</firstName>
<lastName>Schaefer</lastName>
<birthDate>
<dayOfMonth>3</dayOfMonth>
<dayOfWeek>7</dayOfWeek>
<era>1</era>
<year>1981</year>
<dayOfYear>123</dayOfYear>
<millisOfDay>3600000</millisOfDay>
<monthOfYear>5</monthOfYear>
<hourOfDay>1</hourOfDay>
<minuteOfHour>0</minuteOfHour>
<weekyear>1981</weekyear>
<yearOfEra>1981</yearOfEra>
<yearOfCentury>81</yearOfCentury>
<centuryOfEra>19</centuryOfEra>
<secondOfDay>3600</secondOfDay>
<minuteOfDay>60</minuteOfDay>
<secondOfMinute>0</secondOfMinute>
<millisOfSecond>0</millisOfSecond>
<weekOfWeekyear>18</weekOfWeekyear>
<millis>357696000000</millis>
<zone>
<uncachedZone>
<fixed>false</fixed>
<cachable>true</cachable>
<id>Europe/Belgrade</id>
</uncachedZone>
<fixed>false</fixed>
<id>Europe/Belgrade</id>
</zone>
<chronology>
<zone>
<uncachedZone>
<fixed>false</fixed>
<cachable>true</cachable>
<id>Europe/Belgrade</id>
</uncachedZone>
<fixed>false</fixed>
<id>Europe/Belgrade</id>
</zone>
</chronology>
<afterNow>false</afterNow>
<beforeNow>true</beforeNow>
<equalNow>false</equalNow>
</birthDate>
</contacts>
...
</contacts>
</Contacts>
Maven dependencies (same for web and client app):
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId> org.jadira.usertype </groupId>
<artifactId>usertype.core</artifactId>
<version> 3.0.0.CR3 </version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.castor</groupId>
<artifactId>castor-xml</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.castor</groupId>
<artifactId>castor-core</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.30</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
Then when I am trying to get java objects (in client application) via org.springframework.web.client.RestTemplate I have following exception:
Exception in thread "main"
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read [class com.example.web.Contacts]; nested exception is
org.springframework.oxm.UnmarshallingFailureException: SAX reader
exception; nested exception is org.xml.sax.SAXException: The class for
the root element 'Contacts' could not be found. at
org.springframework.http.converter.xml.MarshallingHttpMessageConverter.re
adFromSource(MarshallingHttpMessageConverter.java:134)
...
I belive that something wrong is with my mapping file. As You can see I have triple contacts tag even in mapping file I have other names.. Do anyone know what can be a reason of having this exception/wrong xml format?
What is happening is that when unmarshaller is looking for class he's looking for alias "Contacts" as in XML. What he has in cache is "contacts" mapping and its not the same as "Contacts". Problem was that marshaller library was not the same as unmarshaller. Probably something wrong in configuration..
What I did is change of implementation to jaxb I put #XMLRootElement and #XMLElement on model classes and completely removed configuration of messageConverters in mvc:annotation-driven (also mapping xml files). On client application I changed messageConverter to:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxb2Marshaller" />
<property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>
</list>
</property>
</bean>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.example.web.model.Contact</value>
<value>com.example.web.Contacts</value>
</list>
</property>
</bean>
And everything works fine.
Related
I am try to execute sample send and recive message to/from activemq by mvc spring But when I Run the project I get this error :
java.lang.NullPointerException
com.sarf.jms.MessageProducerBean.sendMessage(MessageProducerBean.java:24)
com.sarf.testactimq.HomeController.home(HomeController.java:42)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My source code :
MessageObject.java :
package com.sarf.data;
public class MessageObject {
private String mailId;
private String message;
public MessageObject(){};
public MessageObject(String mailId, String message) {
super();
this.mailId = mailId;
this.message = message;
}
public String getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
MessageConsumerBean.java :
package com.sarf.jms;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.JmsUtils;
import com.sarf.data.MessageObject;
public class MessageConsumerBean{
private JmsTemplate jmsTemplate;
private Destination destination;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public MessageObject receiveMessage() {
MapMessage message = (MapMessage) jmsTemplate.receive(destination);
try {
MessageObject messageObj = new MessageObject();
messageObj.setMailId(message.getString("mailId"));
messageObj.setMessage(message.getString("message"));
return messageObj;
} catch (JMSException e) {
throw JmsUtils.convertJmsAccessException(e);
}
}
}
MessageProducerBean.java :
package com.sarf.jms;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import com.sarf.data.MessageObject;
public class MessageProducerBean {
//JMS Template object
private JmsTemplate jmsTemplate;
private Destination destination;
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public void sendMessage(final MessageObject messageObj) {
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
MapMessage message = session.createMapMessage();
message.setString("mailId", messageObj.getMailId());
message.setString("message", messageObj.getMessage());
return message;
}
}); //send method close here
}//method ends here
}
Homecontroller :
package com.sarf.testactimq;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.sarf.data.MessageObject;
import com.sarf.jms.MessageProducerBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sarf.jms.*;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
MessageProducerBean mp = new MessageProducerBean();
mp.sendMessage(new MessageObject("1234", "Test Message"));
/*
MessageConsumerBean mc = new MessageConsumerBean();
MessageObject messageObj = mc.receiveMessage();
System.out.println("Message from " +
messageObj.getMailId() + " received");
*/
return "home";
}
}
servlete_context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<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="connectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<beans:property name="brokerURL" value="tcp://localhost:61616" />
</beans:bean>
<beans:bean id="mailDestination"
class="org.apache.activemq.command.ActiveMQQueue">
<beans:constructor-arg value="mail.queue" />
</beans:bean>
<beans:bean id="jmsTemplate"
class="org.springframework.jms.core.JmsTemplate">
<beans:property name="connectionFactory" ref="connectionFactory" />
</beans:bean>
<beans:bean id="producer"
class="com.sarf.jms.MessageProducerBean">
<beans:property name="destination" ref="mailDestination" />
<beans:property name="jmsTemplate" ref="jmsTemplate" />
</beans:bean>
<beans:bean id="consumer"
class="com.sarf.jms.MessageConsumerBean">
<beans:property name="destination" ref="mailDestination" />
<beans:property name="jmsTemplate" ref="jmsTemplate" />
</beans:bean>
<context:component-scan base-package="com.sarf.testactimq" />
</beans:beans>
root_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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="connectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616" />
</bean>
<bean id="mailDestination"
class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="mail.queue" />
</bean>
<bean id="jmsTemplate"
class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="producer"
class="com.sarf.jms.MessageProducerBean">
<property name="destination" ref="mailDestination" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
<bean id="consumer"
class="com.sarf.jms.MessageConsumerBean">
<property name="destination" ref="mailDestination" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
</beans>
pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sarf</groupId>
<artifactId>testactimq</artifactId>
<name>testmessage</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.13.3</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
the error in run time caused by call the methode sendMessage which define in MessageProducerBean called in my controller , I run my activemq as image shown below :
Note :I am using spring suite tool with tc server and activemq version 5.13.3
so what wrong I am doing any help ?
In HomeController you are creating the MessageProducerBean like so:
MessageProducerBean mp = new MessageProducerBean();
And then immediately using the MessageProducerBean to send a message:
mp.sendMessage(new MessageObject("1234", "Test Message"));
However, at this point MessageProducerBean is attempting to use the jmsTemplate variable which you haven't initialized so it's null. Hence you receive a java.lang.NullPointerException.
I'm new to Spring MVC. I know there are a lot of similar questions like this but I already tried most of them for several hours and still facing the issue that 404 error shows up when I request http://localhost:8080/SpringRESTFulExample/ from browser. But there's no any exception in console.
Here is my code,
RootConfig.java
#Configuration
#ComponentScan(basePackages = "springrestful_example")
public class RootConfig {
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "springrestful_example")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
.
.
.
}
WebInitializer.java
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
UserController.java
#RestController
public class UserController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelandView = new ModelAndView("index");
return modelandView;
}
.
.
}
index.jsp is under /WEB-INF/views/index.jsp
Dependencies I use
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
That's all I got. Correct me if my code is being wrong. I will be happy if i see Hello World text written in index.jsp body.
What package are your Config classes in? Are they in basePackages you specify? Try not specifying the basePackages in the Component scan annotation.
I have prepared a sample spring mvc application to understand Hibernate Validator
API.
The view is not getting displayed, when I run it, even though I have all the
required files ready.
The following are my files :
List item
_
#EnableWebMvc
#Configuration
#ComponentScan({"com.*"})
public class SpringConfig extends WebMvcConfigurerAdapter {
public void addHandler(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**/").addResourceLocations("/resources/"
);
}
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/view/");
vr.setSuffix(".jsp");
return vr;
}
}
Controller
#RequestMapping("/form")
public class FormController {
#RequestMapping(method=RequestMethod.GET)
public String initForm(Model model) {
Form form = new Form();
model.addAttribute("form", form);
return "form";
}
#RequestMapping(method = RequestMethod.POST)
public String submitForm(#Valid Form form, BindingResult result) {
String returnVal = "successForm";
if(result.hasErrors()) {
returnVal = "form";
}
return returnVal;
}
}
Model
public class Form {
#Size(min=5, max=10, message="Should be of 5-10 characters")
private String name;
#Min(value = 5, message="Should be atleast of 5 characters")
private String lastname;
#NotNull(message="Cannot be empty")
#Size(min=5, max=10, message="Should be of 5-10 characters")
private String password;
#Pattern(regexp="[0-9]+",message="Wrong Zip")
private String zip;
#Min(value=18,message="Should not be below 18")
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
JSP
"http://www.w3.org/TR/html4/loose.dtd">
Insert title here
Fill your form!
<form:form method="POST" commandName="form">
<table>
<tr>
<td>Enter your name:</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
</tr>
<tr>
<td>Enter your lastname:</td>
<td><form:input path="lastname" /></td>
<td><form:errors path="lastname" cssStyle="color: #ff0000;" />
</tr>
<tr>
<td>Enter your password:</td>
<td><form:input path="password" /></td>
<td><form:errors path="password" cssStyle="color: #ff0000;" />
</tr>
<tr>
<td>Enter your zip:</td>
<td><form:input path="zip" /></td>
<td><form:errors path="zip" cssStyle="color: #ff0000;" /></td>
</tr>
<tr>
<td>Enter your email:</td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssStyle="color: #ff0000;" /></td>
</tr>
<tr>
<td>Enter your age:</td>
<td><form:input path="age" /></td>
<td><form:errors path="age" cssStyle="color: #ff0000;" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
</table>
</form:form>
pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.samples.service.service
HibernateValidation
0.0.1-SNAPSHOT
war
<properties>
<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.2.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<dependency>
javax.el
javax.el-api
2.2.4
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
org.glassfish.web
javax.el
2.2.4
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
<groupId>asm</groupId>
<artifactId>asm-util</artifactId>
<version>3.3.1</version>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
I am new to spring boot web mvc. My view on RequestMapping("/") is not getting resolved. Below i have shared required code.
my controller class is
#Controller
public class ExpenseSheetController {
#Autowired
private ExpenseSheetDao expenseSheetDao;
#RequestMapping("/")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home");
modelAndView.addObject("message","on home page");
return modelAndView;
}
}
pom.xml is as follows
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- my-sql connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
I have kept my view at src/main/resources/templates as home.html
First note that I am a total beginner regarding this. I started spring maven web project and wrote 3 classes (posted below).
I put the project to be run on my tomcat server (from eclipse) and when I start it i can access localhost:8080 (tomcat default page is shown), but when i try to access localhost:8080/greeting i get 404 error, what am I doing wrong? I'll also post my pom.xml
Thank you
Greeting:
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingController:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
Application:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<artifactId>WebTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.2.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If you deploy your application into a standalone Tomcat instance and it is not deployed as the ROOT application, you have to add the name of the application in your URL. You can check the Tomcat log for the exact name. If you named your project "helloworld", then Eclipse usually deploys the project with that name as application name, so you should call your application with the URL http://localhost:8080/helloworld/greeting
Unless you really need to deploy your application to an external Tomcat server, you can solve your problem by just running your application's main method directly. Spring Boot will start an embedded Tomcat instance for you.
If you need to be able to deploy your application to an external Tomcat server, then you need to change your Application class a little bit so that it'll start up correctly. You need to extend SpringBootServletInitializer and override the configure method:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
This is covered in the traditional deployment section of the Spring Boot reference documentation.