I'm new to spring controllers using annotated controllers.
Here is my configuration
Bean definition
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
Controller
package learn.web.controller.annotation;
import javax.servlet.http.HttpServletRequest;
import learn.web.controller.BaseController;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class FirstController extends BaseController {
#RequestMapping("/annotation/first.ftl")
public ModelAndView first(HttpServletRequest request) {
if(messageSource instanceof ReloadableResourceBundleMessageSource){
ReloadableResourceBundleMessageSource m = (ReloadableResourceBundleMessageSource) messageSource;
m.clearCache();
}
messageSource.getMessage("learn.message.first", new Object[] {},
localResolver.resolveLocale(request));
return new ModelAndView("/annotation/first");
}
}
When tried to access the given URL Spring is throwing a warning org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/Learn/annotation/first.ftl] in DispatcherServlet with name 'springapp'
I think what you are missing is the component scan
<context:component-scan base-package="learn.web.controller" />
Add this to your configuration and try.
This will load all annotated components from the specified package
Your configuration may look like this
<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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="learn.web.controller" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
</beans>
Related
I am getting exception mentioned in subject line. Could you please explain what is wrong:
package mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/req")
public class Req {
#RequestMapping(method = RequestMethod.GET)
#ResponseBody
public String get(#RequestBody String body) {
return body;
}
}
SpringMVC-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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!--It tells the Spring framework to look for annotations and then do appropriate dependency injections.-->
<context:annotation-config/>
<!--used to provide base package to scan components-->
<context:component-scan base-package="mvc"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
When i tries to access http://localhost:8080/SpringMVC/req
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect ().
Apache Tomcat/7.0.16
Kindly help me in figure out the cause of this issue.
Thanks,
Sandip
Change method to POST and send some data with HTTP POST so the (#RequestBody String body) binding works.
You could use SoapUi or HTTP Requester plugin for browsers to conveniently send HTTP POST.
Otherwise define method as:
#RequestMapping(method = RequestMethod.GET)
#ResponseBody
public String get() {
return "Some string";
}
Hi I read all previous threads on my issue and i applied all suggestions, but i haven't found a solution.
In my springMVC+AspectJ config, controller works fine but the pointcut is not performed.
Here my configs and code:
-- /WEB-INF/web.xml ---
<web-app>
<display-name>MODULE-WEB</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
...
**
-- /WEB-INF/ApplicationContext.xml -----
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
>
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="it.max.test"/>
<!-- AOP -->
<aop:aspectj-autoproxy/>
<!-- EJB -->
<bean id="testService" class="org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean">
<property name="jndiName" value="java:app/MODULE-EJB/TestService"/>
<property name="businessInterface" value="it.max.test.services.ITestService"/>
</bean>
</beans>
**
-- Monitor.java ---
package it.max.test.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
#Component
#Target(value={ElementType.METHOD, ElementType.TYPE})
#Retention(value=RetentionPolicy.RUNTIME)
public #interface Monitor {
}
**
-- AuthorizationInterceptor.java --
package it.max.test.security;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class AuthorizationInterceptor {
#Before(value="#within(it.max.test.security.Monitor) || #annotation(it.max.test.security.Monitor)")
public void before(JoinPoint jp){
Object[] paramValues=jp.getArgs();
String[] paramNames=((CodeSignature)jp.getStaticPart().getSignature()).getParameterNames();
for(int i=0;i<paramValues.length;i++){
System.out.println("["+paramNames[i]+"]:["+paramValues[i]+"]");
}
}
}
**
--TestController.java---
package it.max.test.controllers;
import it.max.test.security.Monitor;
import it.max.test.services.ITestService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#Autowired
private ITestService testService;
#Monitor
#RequestMapping("/test.view")
protected ModelAndView test(HttpServletRequest arg0,HttpServletResponse arg1) throws Exception {
ModelAndView mv=new ModelAndView();
testService.test("AAA");
mv.setViewName("test");
return mv;
}
}
Your annotated method is protected, but it should be public.
Spring manual, chapter 9.2.3 says:
Due to the proxy-based nature of Spring’s AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn’t applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!
If you want to match protected or private methods, use AspectJ via LTW.
I'm receiving the an error when trying to autowire a class that extends JdbcDaoSupport. I have my DAO classes and Controller classes separated into 2 different spring contexts. DAO classes are in the root context and the Controller classes are in the servlet context. I've set up the component-scanning so that there is no overlap in beans between the 2 contexts (is that the correct pattern?). All these factors combined with the fact that my DAOs extend JdbcDaoSupport seems to be causing the issue, and I don't understand why. I'm just learning spring so I don't fully understand all the concepts yet.
EDIT: This behavior seems to be caused by the fact that JdbcDaoSupport/DaoSupport implements the InitializingBean interface. Still confused though.
Here is the error I am receiving:
Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.test.dao.CustomerDAO2 org.test.servlet.HomeController.customerDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.test.dao.CustomerDAO2] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Here are my files:
HomeController.java
package org.test.servlet;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
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 org.test.dao.*;
#Controller
public class HomeController
{
#Autowired
CustomerDAO2 customerDAO;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
model.addAttribute("customer", customerDAO.getCustomer());
return "home";
}
}
CustomerDAO2.java
package org.test.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.*;
import org.test.dto.Customer;
#Repository
public class CustomerDAO2 extends JdbcDaoSupport
{
public CustomerDAO2()
{
}
#Autowired
public CustomerDAO2(DataSource datasource)
{
this.setDataSource(datasource);
}
#Transactional
public Customer getCustomer()
{
JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
Customer customer = jdbcTemplate.queryForObject("select * from customer", new CustomerMapper());
return customer;
}
public static class CustomerMapper implements RowMapper<Customer>
{
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException
{
Customer customer = new Customer();
customer.setCustomerId(rs.getInt("customerId"));
customer.setCustomerNumber(rs.getString("customerNumber"));
return customer;
}
}
}
application-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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-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">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="org.test">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<!-- Enables the configuration of transactional behavior based on annotations -->
<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://localhost/crm?user=root&password=password" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
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/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">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<!-- #Controller, #Service, #Configuration, etc. -->
<context:component-scan base-package="org.test.servlet"/>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I found my answer in this post:
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
Basically, I need to create an interface for my DAO classes. Something like this:
public interface ICustomerDAO {
Customer getCustomer();
}
Note: it would probably be better to make a more generic CRUD interface.
Then you use the interface type for dependency injection instead of using the class type:
#Autowired
ICustomerDAO customerDAO;
The reason this is necessary is because Spring creates underlying proxy classes:
http://insufficientinformation.blogspot.com/2007/12/spring-dynamic-proxies-vs-cglib-proxies.html
http://docs.spring.io/spring/docs/2.5.x/reference/aop.html#aop-proxying
I'm learning Spring and Data JPA. I have a problem with Ehcache. I want to cache the return value of one of my methods that returns some records from database. This is an exercise with Ehcache instance pre-configured (I assume). The problem is that I cannot use the annotation #Cacheable to mark my method as the method that its return value should be cached. I get an incompatible type compile error (required: boolean, found: String). Here is one of the classes in my service layer that I think I should put #Cacheable here (am I right?):
package wad.datatables.service;
import javax.persistence.Cacheable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import wad.datatables.domain.Book;
import wad.datatables.repository.BookRepository;
import wad.datatables.view.DataTablesResponse;
#Service
public class JpaDataTablesBookService implements DataTablesBookService {
#Autowired
private BookRepository bookRepository;
#Override
#Transactional(readOnly = true)
#Cacheable("books")
public DataTablesResponse getBooks(String queryString) {
Pageable pageable = new PageRequest(0, 10, Sort.Direction.ASC, "title");
Page<Book> page = bookRepository.findByTitleContaining(queryString, pageable);
DataTablesResponse response = new DataTablesResponse();
response.setTotalRecords(page.getTotalElements());
response.setTotalDisplayRecords(page.getNumberOfElements());
response.setData(page.getContent());
return response;
}
}
And my repository layer (only one class):
package wad.datatables.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import wad.datatables.domain.Book;
public interface BookRepository extends JpaRepository<Book, Long> {
Page<Book> findByTitleContaining(String title, Pageable pageable);
}
And here are my config files:
cache.xml (located in WEB-INF/spring/):
<?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:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
</beans>
And ehcache.xml (located in src/main/resources):
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<cache name="books" maxEntriesLocalHeap="1000" eternal="true" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
The error is because you are using wrong Cacheable annotation. Instead of javax.persistence.Cacheable use org.springframework.cache.annotation.Cacheable.
i'm using Spring-WS and have the following spring-ws-servlet.xml file.
The injection of defaultURI and marshaller doesn't work because when i get to the method in the client of the service these properties are null.
What happens is that the setters are being called with correct values, but in the method of the client getSum() these values are null. What could be wrong?
<?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:sws="http://www.springframework.org/schema/web-services"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<context:component-scan base-package="com.coral.project.endpoints"/>
<sws:annotation-driven />
<sws:dynamic-wsdl id="test" portTypeName="TestCase" locationUri="/testService/"
targetNamespace="http://www.example.org/schemasDef/test/definitions">
<sws:xsd location="/WEB-INF/schemasDef/test.xsd"/>
</sws:dynamic-wsdl>
<bean id="springWSClient" class="com.coral.project.endpoints.SpringWSClient">
<property name="defaultUri" value="http://localhost:8080/parking/springServices/testService"/>
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="marshaller" />
</bean>
<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="com.coral.project.entity.Street"/>
</oxm:jaxb2-marshaller>
</beans>
i get the exception:
Exception while calling encodeEnd on component : {Component-Path : [Class: org.ajax4jsf.component.AjaxViewRoot,ViewId: /appealConversionStatusReport.jsp][Class: org.apache.myfaces.custom.div.Div,Id: j_id_jsp_1406177460_4][Class: com.exadel.htmLib.components.UITable,Id: j_id_jsp_1406177460_5][Class: com.exadel.htmLib.components.UITbody,Id: j_id_jsp_1406177460_6][Class: org.apache.myfaces.component.html.ext.HtmlInputHidden,Id: j_id_jsp_546672833_0]}
Caused by:
java.lang.IllegalStateException - No marshaller registered. Check configuration of WebServiceTemplate.
the client:
package com.coral.project.endpoints;
import java.io.IOException;
import java.io.StringWriter;
import javax.inject.Inject;
import javax.xml.soap.SOAPException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.xml.transform.StringSource;
import com.coral.project.dao.ifc.StreetDao;
import com.coral.project.entity.Street;
import com.coral.utils.SpringUtils;
public class SpringWSClient extends WebServiceGatewaySupport {
public void getSum() throws SOAPException, IOException, TransformerException {
StreetDao streetDao = SpringUtils.getBean(StreetDao.class);
Street street = streetDao.findById(1);
getWebServiceTemplate().marshalSendAndReceive(
"http://localhost:8080/parking/springServices/testService",street);
}
}
Are you new'ing the SpringWSClient instance in your code?
Also, for the streetDao, you shouldn't need to use SpringUtils.getBean. Instead, it should be a field annotated with #Autowired (or #Resource).