A Spring controller has the following method :
#RequestMapping(value = "reportsOverall.html")
public/* #ResponseBody */
ModelAndView reportsOverall(SearchParameters searchParameters) {
searchParameters = new SearchParameters(840, "SCH_01", "PRM_07");
System.out.println("Inside controller");
String result = overallDetailsService
.getOverallDetails(searchParameters);
System.out.println("result is " + result);
Map<String, String> model = new HashMap<String, String>();
model.put("data", result);
ModelAndView modelAndView = new ModelAndView("reports/reportsOverall",
model);
return modelAndView;
}
I get the expected output on the server-side console :
result is { "_id" : { "SpId" : 840 , "Scheduler_id" : "SCH_01"} , "positive_count" : 64 , "neutral_count" : 78 , "negative_count" : 2}
But in the reportsOverall.jsp, when I retrieve the result object as :
function drawSentimentPieChart() {
var data = '<c:out value="${data}"/>';
alert(data);
var dataJson = JSON.parse(data);
......
}
in the alert I get :
{ "_id" : { "SpId" : 840 , "Scheduler_id" : "SCH_01"} , "positive_count" : 64 , "neutral_count" : 78 , "negative_count" : 2}
The space and "" quotes are encoded here, thereby, causing the parse to fail.
The spring-servlet.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.lnt" />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"></bean>
<!-- <bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
</bean>
</array>
</property>
</bean> -->
<bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:userProfile,classpath:default,classpath:messages,classpath:customerAdmin,classpath:reports,classpath:superAdmin" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd hh:mm:ss" />
</bean>
</beans>
I tried several things in the Spring controller :
Using #ResponseBody; in this case, I got a dump on the page like this but the page wasn't rendered properly :
{"view":null,"model":{"data":"{ \"_id\" : { \"SpId\" : 840 , \"Scheduler_id\" : \"SCH_01\"} , \"positive_count\" : 64 , \"neutral_count\" : 78 , \"negative_count\" : 2}"},"empty":false,"viewName":"reports/reportsOverall","reference":true,"modelMap":{"data":"{ \"_id\" : { \"SpId\" : 840 , \"Scheduler_id\" : \"SCH_01\"} , \"positive_count\" : 64 , \"neutral_count\" : 78 , \"negative_count\" : 2}"}}
Added encoding filter to the web.xml :
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Attempted using MappingJacksonJsonView in vain !
What is that I'm overlooking?
I had the same problem, but this additional attribute saved me:
<c:out value="${data}" escapeXml="false"/>
Related
I am stuck with the transaction in Spring.
I don't know why never do a rollback.
Does anybody know what it is happening?
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Security Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-database.xml, /WEB-INF/spring-security.xml</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
FileCabServiceImpl.java
#Service("FileCabService")
public class FileCabServiceImpl implements FileCabService
{
#Autowired
private FileCabMapper fileCabMapper;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertFileCab(FileCab fileCab)
{
fileCabMapper.insertFileCab(fileCab);
throw new NullPointerException(); // Error to do the rollback
}
}
Controller.java:
#RestController
public class ReservationController
{
private final Logger logger = LoggerFactory.getLogger(ReservationController.class);
#Autowired
ReservationServiceImpl reservationService;
#Autowired
FileCabService fileCabService;
#Autowired
FileCounterService fileCounterService;
#RequestMapping(value = "/api/reservation", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public void reservationProcess()
{
FileCab fileCab = new FileCab();
fileCab.setnUser("user");
fileCab.setiPax(5);
fileCab.setnNamePax("");
Date dateIn = new Date();
fileCab.setdDateIn(dateIn);
fileCab.setdDateOut(dateIn);
fileCab.setnCodeRef("");
int fileCounter = fileCounterService.getiFileCounterByYear(2017, 1);
fileCab.setnTravelFile(String.valueOf(++fileCounter));
fileCab.setiUserGroup(1);
fileCab.setnYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
fileCab.setdOpenDay(Calendar.getInstance().getTime());
fileCab.setiAgency(0);
fileCab.setnStatus("Cerrado");
fileCab.setbPrePaid(0);
fileCab.setbPaid(0);
fileCab.setdDatePrePaid(null);
fileCab.setDcPrePaidAmount(BigDecimal.ZERO);
fileCab.setiTourService(0);
fileCab.setnObservations("");
fileCabService.insertFileCab(fileCab);
}
}
spring-database.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName">
<context:annotation-config />
<context:component-scan base-package="es.app.spring" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://xxx.xxx.xxxx.xxx:3306/spring_res?autoReconnect=true" />
<property name="username" value="XXXXXX" />
<property name="password" value="XXXXXX" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="es.app.spring.model"/>
<property name="mapperLocations" value="classpath*:es.app.spring.mappers/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="es.app.spring.mappers" />
</bean>
</beans>
Any help will be appreciate.
Thank you
I can't get the attributes to the CAS client.
I did some research and try to find out how to forward attributes to a CAS client.
In the cas.properties I set this:
cas.principal.resolver.persondir.return.null=false
I added this dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
This is my servicesRegistry.conf:
{
"services":[
{
"id":1,
"serviceId":"https://localhost:8743/**",
"name":"HELLO_WORLD",
"description":"WEBAPP FOR TESTS",
"theme":"my_example_webapp",
"allowedToProxy":true,
"enabled":true,
"ssoEnabled":true,
"anonymousAccess":false,
"evaluationOrder":1,
"attributeReleasePolicy" : {
"#class" : "org.jasig.cas.services.ReturnAllowedAttributeReleasePolicy",
"principalAttributesRepository" : {
"#class" : "org.jasig.cas.authentication.principal.DefaultPrincipalAttributesRepository"
},
"allowedAttributes" : [ "java.util.ArrayList", [ "cn", "description", "telephoneNumber" ] ]
}
},
{
"id":2,
"serviceId":"https://yahoo.com",
"name":"YAHOO",
"description":"Test service with exact match on its serviceId and optional extra attributes",
"extraAttributes":{
"someCustomAttribute":"Custom attribute value"
},
"evaluationOrder":2
}
]
}
My ldapAuthenticationHandlerlooks like this:
<bean id="ldapAuthenticationHandler"
class="org.jasig.cas.authentication.LdapAuthenticationHandler"
p:principalIdAttribute="cn"
c:authenticator-ref="authenticator">
<property name="principalAttributeMap">
<map>
<entry key="cn" value="cn" />
<entry key="description" value="description" />
<entry key="telephoneNumber" value="telephoneNumber" />
</map>
</property>
</bean>
And my authenticationHandlersResolvers like this:
<util:map id="authenticationHandlersResolvers">
<entry key-ref="ldapAuthenticationHandler" value="#{null}" />
</util:map>
And here is my attributeRepository:
<bean id="attributeRepository" class="org.jasig.services.persondir.support.NamedStubPersonAttributeDao"
p:backingMap-ref="attrRepoBackingMap" />
<util:map id="attrRepoBackingMap">
<entry key="cn" value="cn" />
<entry key="description" value="description" />
<entry key="telephoneNumber" value="telephoneNumber" />
<entry>
<key><value>memberOf</value></key>
<list>
<value>faculty</value>
<value>staff</value>
<value>org</value>
</list>
</entry>
</util:map>
And at the client side I do this (edited version with out null check etc):
AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
final Map attributes = principal.getAttributes();
Iterator attributeNames = attributes.keySet().iterator();
String attributeName = (String) attributeNames.next();
However, I don't get any attributes. What am I missing?
EDIT:
I read in another thread that I have to change Cas20ProxyReceivingTicketValidationFilterto Cas30ProxyReceivingTicketValidationFilter, but that didn't change anything:
<filter>
<filter-name>CAS Validation Filter</filter-name>
<filter-class>org.jasig.cas.client.validation.Cas30ProxyReceivingTicketValidationFilter</filter-class>
<init-param>
<param-name>casServerUrlPrefix</param-name>
<param-value>https://localhost:8943/cas</param-value>
</init-param>
<init-param>
<param-name>serverName</param-name>
<param-value>https://localhost:8743</param-value>
</init-param>
<init-param>
<param-name>redirectAfterValidation</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>useSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
My problem was the servicesRegistry.conf. It didn't work for some reason and I couldn't figure out why.
If you have problem using the servicesRegistry.conf file, I recommend you use this inside your deployerConfigContext.xml:
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<property name="registeredServices">
<list>
<bean class="org.jasig.cas.services.RegexRegisteredService"
p:id="5" p:name="https.all" p:description="Allow HTTPS connection"
p:serviceId="^https://.*" p:evaluationOrder="5" >
<property name="attributeReleasePolicy">
<bean class="org.jasig.cas.services.ReturnAllAttributeReleasePolicy" />
</property>
</bean>
</list>
</property>
</bean>
This will allow all services that have an URL that fits the regex ^https://.*.
As seen in below code in step1 I'm reading users.xml and writing to database now in step2 I'm reading from userdetails.xml and writing to database but I need step1 auto generated key of tbl_user for step2. How Can I do that?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<import resource="../config/context.xml" />
<import resource="../config/database.xml" />
<bean id="xmlItemReader1" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="resource" value="file:xml/outputs/users.xml" />
<property name="fragmentRootElementName" value="user" />
<property name="unmarshaller" ref="userUnmarshaller"/>
</bean>
<bean id="xmlItemReader2" class="org.springframework.batch.item.xml.StaxEventItemReader">
<property name="resource" value="file:xml/outputs/userdetails.xml" />
<property name="fragmentRootElementName" value="userdetail" />
<property name="unmarshaller" ref="userUnmarshaller"/>
</bean>
<bean id="itemProcessor1" class="com.qmetry.recovery.mapper.UserItemProcessor" />
<bean id="itemProcessor2" class="com.qmetry.recovery.mapper.UserDetailItemProcessor" />
<job id="testJob2" xmlns="http://www.springframework.org/schema/batch">
<step id="step2_1">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader1" writer="databaseItemWriter1" processor="itemProcessor1"
commit-interval="100" />
</tasklet>
<listeners>
<listener ref="testListener" />
</listeners>
</step>
<step id="step2_2">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader2" writer="databaseItemWriter2" processor="itemProcessor1"
commit-interval="100" />
</tasklet>
</step>
</job>
<bean id="testListener" class="com.qmetry.recovery.mapper.TestListener" scope="step" />
<bean id="databaseItemWriter1" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into TBL_USER(USERNAME,EMAILID)
values (?, ?)
]]>
</value>
</property>
<!--We need a custom setter to handle the conversion between Jodatime LocalDate and MySQL DATE BeanPropertyItemSqlParameterSourceProvider-->
<property name="itemPreparedStatementSetter">
<bean class="com.qmetry.recovery.mapper.UserItemPreparedStatementSetter"/>
</property>
</bean>
<bean id="databaseItemWriter2" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into TBL_USERDETAIL(USERID,CONTACT)
values (?, ?)
]]>
</value>
</property>
<!--We need a custom setter to handle the conversion between Jodatime LocalDate and MySQL DATE BeanPropertyItemSqlParameterSourceProvider-->
<property name="itemPreparedStatementSetter">
<bean class="com.qmetry.recovery.mapper.UserDetailItemPreparedStatementSetter"/>
</property>
</bean>
users.xml
<?xml version="1.0" encoding="UTF-8"?><users>
<user>
<userId>1</userId>
<userName>Taher</userName>
<emailId>taher.tinwala#hotmail.com</emailId>
</user>
</users>
userdetails.xml
<?xml version="1.0" encoding="UTF-8"?><userdetails>
<userdetail>
<userDetailId>1</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>1111111111</contact>
</userdetail>
<userdetail>
<userDetailId>2</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>2222222222</contact>
</userdetail>
<userdetail>
<userDetailId>4</userDetailId>
<userId__TblUser>1</userId__TblUser>
<contact>4444444444</contact>
</userdetail>
</userdetails>
You need to pass data to a future step. For explantory documentation see http://docs.spring.io/spring-batch/trunk/reference/html/patterns.html#passingDataToFutureSteps
I have implemented the example from the documentation and adjusted it to your configuration with some assumptions here and there.
During the read (or the write, it depends when you get the data that you want to pass) in step 1 you need to store the data in the StepExecution. Add to your xmlItemReader the following:
public class YourItemReader implements ItemReader<Object>
private StepExecution stepExecution;
public void read(Object item) throws Exception {
// ...
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("tbl_user", someObject);
}
#BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
Your xml will look like this:
<step id="step2_1">
<tasklet transaction-manager="transactionManager">
<chunk reader="xmlItemReader1" writer="databaseItemWriter1" processor="itemProcessor1" commit-interval="100" />
</tasklet>
<listeners>
<listener ref="testListener" />
<listener ref="promotionListener"/>
</listeners>
</step>
Add the promotionListener bean:
<beans:bean id="promotionListener" class="org.springframework.batch.core.listener.ExecutionContextPromotionListener">
<beans:property name="keys" value="tbl_key"/>
</beans:bean>
And finally you need to retrieve the value in step 2. Again asuming you need it in the reader of step 2 you reader in step 2 needs the following code added:
public class YourItemReader2 implements ItemReader<Object>
private Object someObject;
#BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.someObject = jobContext.get("tbl_key");
}
Now you have acces to the value read in step 1.
EDIT - adding some example configuration for an extra read step:
After step 1 add a simple step 2 with the following reader to get the new value from the database
<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
YOUR SELECT STATEMENT
]]>
</value>
</property>
<property name="rowMapper" ref="rowMapper" />
</bean>
And a simple rowMapper bean
<bean id="rowMapper" class="exampleRowMapper" />
You will have to write your exampleRowMapper obviously to reflect the data your fetching. For example:
public class ExampleRowMapper implements ParameterizedRowMapper<String> {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return String.valueOf(rs.getString(1));
}
}
In your dummywriter you add the stepexecution and you will store your value in the step execution context.:
public class DummyItemWriter implements ItemWriter<Object> {
private StepExecution stepExecution;
#Override
public void write(List<? extends Object> item) throws Exception {
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("someKey", someObject);
}
}
And the bean for the writer:
<bean id="savingDummyWriter" class="your.package.DummyItemWriter" />
And wrap the reader and writer in a step.
<step id="step2">
<tasklet>
<chunk reader="itemReader" writer="dummyItemWriter" commit-interval="1" />
</tasklet>
<listeners>
<listener ref="promotionListener"/>
</listeners>
</step>
I am using Spring with a JSP and jqGrid and trying to post JSON data to my server.
The GET successfully loads the JSP when I go to the URL:
http://localhost:8080/sportsSpring/sport-management/sport/
My POST successfully saves to the database but fails to reload the JSP afterwards with the exception "Could not resolve view with name 'sport' in servlet with name 'SpringApp'".
SpringApp-servlet.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="spring.controller"/>
<!-- To enable #RequestMapping process on type level and method level -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
<bean id="sportController" class="spring.controller.SportController">
<property name="SportDao" ref="SportDao" />
</bean>
applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jd="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="spring.controller,spring.beans"/>
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/dbName"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="SportDao" class="spring.controller.SportDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>SpringApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpringApp</servlet-name>
<url-pattern>/sport-management/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tags/c.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
My SportController:
#RequestMapping(method=RequestMethod.GET, value="/sport")
public ModelAndView getSportList() throws NumberFormatException, SQLException, JSONException
{
sportDao = getSportDao();
List<SportBean> sportBeanList = sportDao.getSports();
JSONArray sportJsonArray = convertToJson(sportBeanList);
return new ModelAndView("sport", "sports", sportJsonArray);
}
#RequestMapping(method=RequestMethod.POST, consumes="application/json", value="/sport")
public ModelAndView addSport(#RequestBody String body) throws SQLException, JSONException
{
SportBean sportBean = convertToBean(body, true);
sportDao = getSportDao();
sportDao.saveSport(sportBean);
return new ModelAndView("sport");
}
Any help would be appreciated,
Thank you
Two solutions:
remove this:<property name="prefix" value="/"/>
or try to see what is actually the prefix to your path such as WEB-INF folder for your JSP pages such as <property name="prefix" value="WEB-INF/views/"/>
I am using POST MAN CLIENT of GOOGLE CHROME TO SEND articleName and articleId AS HEADER application/json.What things I needed to change in my controller and library as well as in my spring servlet.xml?My controller is as follows.
public class ArticleController {
#Autowired
private ArticleService articleService;
Article article = new Article();
Long articleId = article.getArticleId();
#RequestMapping(value = "/save", method = RequestMethod.POST)
public Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
int a = articleService.addArticle(article);
if (a == 1) {
return new ModelAndView("success");
} else {
return new ModelAndView("error");
}
}
My Spring servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="net.roseindia" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>net.roseindia.model.Article</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Plz help me out....Thanks in advance.
I assume what you want is to return JSON easily from Spring.
To do that you need Jackson dependency:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
When you have it,
you can annotate your method with #ResponseBody annotation just like this:
public #ResponseBody Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
....
}
Such a method will return JSONified Article object in response.