Spring MVC sub mapping #RequestMapping throws 404 - spring

BE GENEROUS AND TELL US WHY I AM HAVING THIS SILLY ISSUE
Everything works fine with no mapping! but I have a simple issue. I have set a parent mapping # "/hello" and sub-mapped a method # "/showForm", Dispatcher is set to "/" but I get 404 (see code fig. 3). I couldn't find an answer to an issue SIMILAR to mine.
See code below & TAGS for my setup
Controller fig.1
#Controller
#RequestMapping("/hello")
public class HelloWorldController {
#RequestMapping("/showForm")
public String showForm() {
return "hello-world";
}
web.xml fig.2
<servlet>
<servlet-name>yktech</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>yktech</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Tomcat Error fig.3
Type Status Report
Message /yktech/hello/WEB-INF/view/hello-world.jsp
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
EDIT: FORGOT THE BEAN FIG. 4
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
EDIT: STRUCTURE TREE ( MESSY I KNOW )
enter image description here
edit 4 , index.jsp
<html>
<body>
<h2>Welcome to my homepage
</h2>
Show form
Show STUDENT form
</body>
</html>
edit 5 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yktech</groupId>
<artifactId>yktech</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>yktech</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>yktech</finalName>
</build>
</project>
EDIT 6 , SERVER LOG , MAPPING URLS
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/yktech-servlet.xml]
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processForm] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processForm.*] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processForm/] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processFormVersionTwo] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processFormVersionTwo.*] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/processFormVersionTwo/] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/showForm] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/hello/showForm.*] onto handler 'helloWorldController'
Jul 30, 2018 10:19:30 PM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
registerHandler
INFO: Mapped URL path [/hello/showForm/] onto handler 'helloWorldController'
... CARRIES ON SHOWS NO ERRORS....

Try this:
Requests to /hello will be handled by whatever() while request to /hello/showForm will be handled by showForm()
#Controller
#RequestMapping("/hello")
public class HelloWorldController {
#RequestMapping("/")
public String whatever() {
return "whatever";
}
#RequestMapping("/showForm")
public String showForm() {
return "hello-world";
}

Issue is in the view resolver bean,
the prefix does not have a "/" in the beginning causing Spring to call any parented mapping requests from root rather than from /WEB-INF/view

Related

lookup method - Injecting a prototype bean into a singleton bean issue

I am developing code for the Injecting a prototype bean into a singleton bean code, so far I developed code like below and when I run the main method, I see the below error is coming.
Jan 04, 2017 2:59:41 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6ed322: startup date [Wed Jan 04 14:59:41 IST 2017]; root of context hierarchy
Jan 04, 2017 2:59:41 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Constructor:: RequestProcessor instance created!
Constructor:: RequestProcessor instance created!
Request ID : 1212
Exception in thread "main" java.lang.AbstractMethodError: com.injection.testing.RequestProcessor.createValidator()Lcom/injection/testing/RequestValidator;
at com.injection.testing.RequestProcessor.handleRequest(RequestProcessor.java:12)
at com.injection.testing.MainDemo.main(MainDemo.java:13)
spring.xml
<!-- Lookup way -->
<bean id="requestProcessor" class="com.injection.testing.RequestProcessor" >
<lookup-method name="getValidator" bean="validator" />
</bean>
<bean id="validator" class="com.injection.testing.RequestValidator" scope="prototype" />
RequestProcessor.java
public abstract class RequestProcessor {
private RequestValidator validator;
public RequestProcessor(){
System.out.println("Constructor:: RequestProcessor instance created!");
}
public void handleRequest(String requestId){
System.out.println("Request ID : "+ requestId);
RequestValidator validator = createValidator(); //here Spring will create new instance of prototype bean
validator.validate(requestId);
}
public RequestValidator getValidator() {
return validator;
}
public void setValidator(RequestValidator validator) {
this.validator= validator;
}
protected abstract RequestValidator createValidator();
}
RequestValidator.java
public class RequestValidator {
private List<String> errorMessages = new ArrayList<String>();
public RequestValidator() {
System.out.println("Constructor:: RequestValidator instance created!");
}
// Validates the request and populates error messages
public void validate(String requestId){
System.out.println("RequestValidator :"+requestId);
}
public List<String> getErrorMessages() {
return errorMessages;
}
}
MainDemo.java
public class MainDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//RequestValidator requestValidator = (RequestValidator) context.getBean("validator");
RequestProcessor processor = (RequestProcessor) context.getBean("requestProcessor");
processor.handleRequest("1212");
System.out.println("------------------------");
processor.handleRequest("1213");
}
}
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
Update your spring.xml to shown below
<bean id="requestProcessor" class="com.injection.testing.RequestProcessor">
<lookup-method name="createValidator" bean="validator" />
</bean>
Basically you need to specify the name of the abstract method name in lookup-method xml attribute.
I got below output after the corrected configuration
Jan 04, 2017 4:11:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#13c675d: startup date [Wed Jan 04 16:11:20 IST 2017]; root of context hierarchy
Jan 04, 2017 4:11:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Constructor:: RequestProcessor instance created!
Request ID : 1212
Constructor:: RequestValidator instance created!
RequestValidator :1212
Request ID : 1213
Constructor:: RequestValidator instance created!
RequestValidator :1213

web app startup warning:No MyBatis mapper was found in ... ,Please check your configuration

My configuration is:
spring-4.2.3
mybatis-3.3.0
mybatis-spring-1.2.3
mapper looks like:
package com.vsi.idp.map.server.mapper;
//imports...
public interface SeniorMapper extends BaseMapper<Long, Senior>
{
#Results({...})
#Select(...)
public List<Senior> query(...);
}
ServiceImpl looks like:
package com.vsi.idp.map.server;
//imports...
#Service("querySenior")
public class SeniorQueryServiceImpl extends RemoteServiceServlet implements SeniorQueryService
{
#Autowired
SeniorMapper mapper;
#Override
public List<Senior> query(Address address, String careType){...}
}
applicationContext.xml looks like:
<beans ... default-lazy-init="true">
<!-- MyBatis Mapper Interfaces -->
<mybatis:scan base-package="com.vsi.idp.map.server.mapper" />
//other configurations
</beans>
Spock unit test looks like below,and runs as expected
#ContextConfiguration(locations = "file:war/WEB-INF/applicationContext.xml")
public class SeniorQueryServiceImplTest extends Specification{
#Autowired
SeniorQueryServiceImpl service
def "query by full address"(){
//blabla
}
}
But when start web application,I got this warning:
WARNING: No MyBatis mapper was found in '[com.vsi.idp.map.server.mapper]' package. Please check your configuration.
So,how to solve this problem?
UPDATEit is a gwt web application,full error stack is:
INFO: Root WebApplicationContext: initialization started Nov 23, 2015 7:12:29 PM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Mon Nov 23 19:12:29 CST 2015]; root of context hierarchy Nov 23, 2015 7:12:29 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] Nov 23, 2015 7:12:29 PM org.mybatis.spring.mapper.ClassPathMapperScanner doScan
WARNING: No MyBatis mapper was found in '[com.vsi.idp.map.server.mapper]' package. Please check your configuration.Nov 23, 2015 7:12:30 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Module setup completed in 1698 ms
Nov 23, 2015 7:12:30 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 1557 ms
#MapperScan(basePackages = "com.vsi.idp.map.server.mapper")
you can try add it!
Have you defined MapperScannerConfigurer in applicationContext.xml? If so, please delete it.
I have the following config in my applicationContext.xml, and when I deleted it, the warning has gone.
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.james.reg.mapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

Issues with Oracle JDBC with Hibernate... Sometimes

I'm having a bit of a unique issue.
I'm able to successfully connect and manage entities when running JUnit tests, but once I start my actual application, I get "Specified JDBC Driver oracle.jdbc.OracleDriver class not found."
What confuses me is that it is there. It works when running my JUnit Tests.
Any insights are appreciated!
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="db">
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#host:port/db</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">db</property>
<property name="show_sql">true</property>
<mapping resource="org/entity/RunResultEntity.hbm.xml"/>
<mapping resource="org/entity/TransactionResultEntity.hbm.xml"/>
<mapping resource="org/entity/FailureResultEntity.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package org.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.*;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()
).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Exception thrown here!
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
pom.xml (dependency added to local repository)
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
<scope>provided</scope>
</dependency>
log
Oct 09, 2014 3:02:58 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Oct 09, 2014 3:02:58 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/RunResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/TransactionResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: org/entity/FailureResultEntity.hbm.xml
Oct 09, 2014 3:02:59 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: db
Oct 09, 2014 3:02:59 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Initial SessionFactory creation failed.org.hibernate.HibernateException: Specified JDBC Driver oracle.jdbc.OracleDriver class not found
Exception in thread "main" java.lang.ExceptionInInitializerError
I found my problem. Lower in my pom.xml I had this little snippet
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
The classifier was only giving access to my test suite. Removing the classifier fixed the issue.
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
</dependency>

Spring No mapping found for HTTP request with URI

I looked at everypost related with this problem and tried nearly all of them. I'm getting this error. I also have created an empty Spring Maven MVC project and duplicated view and controller and named them as example.jsp and ExampleController.java etc. Shortly, I can not get any respond from Tomcat. I do not know it has anything to do with it but I' also getting and error at the beginning of Console log.
Thanks in advance...
Console log beginning warning (I do not know it has an affect on this problem):
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:SpitterSpring' did not find a matching property.
Here is my actual part of error:
Tem 11, 2014 4:55:32 PM org.springframework.web.servlet.handler.SimpleUrlHandlerMapping registerHandler
INFO: Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Tem 11, 2014 4:55:32 PM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'appServlet': initialization completed in 885 ms
Tem 11, 2014 4:55:32 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Tem 11, 2014 4:55:32 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Tem 11, 2014 4:55:32 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 9260 ms
Tem 11, 2014 4:55:34 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spitter/] in DispatcherServlet with name 'appServlet'
Tem 11, 2014 4:55:39 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spitter/spitter/deneme] in DispatcherServlet with name 'appServlet'
Tem 11, 2014 4:55:45 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spitter/deneme] in DispatcherServlet with name 'appServlet'
Tem 11, 2014 4:55:52 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spitter/deneme] in DispatcherServlet with name 'appServlet'
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/application-config.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Here is my servlet-context.xml file
<?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 />
<context:component-scan base-package="com.ex.spitter.mvc" />
<!-- 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:beans>
Here is my com.ex.spitter.mvc -> HomeController:
package com.ex.spitter.mvc;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ex.spitter.service.SpitterService;
#Controller
public class HomeController {
private SpitterService spitterService;
#Inject
public HomeController(SpitterService spitterService) {
this.spitterService = spitterService;
}
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String showHomePage(Map<String, Object> model) {
model.put("spittles", spitterService.getRecentSpittles(spittlesPerPage));
return "home";
}
// <start id="spittlesPerPage"/>
public static final int DEFAULT_SPITTLES_PER_PAGE = 25;
private int spittlesPerPage = DEFAULT_SPITTLES_PER_PAGE;
public void setSpittlesPerPage(int spittlesPerPage) {
this.spittlesPerPage = spittlesPerPage;
}
public int getSpittlesPerPage() {
return spittlesPerPage;
}
// <end id="spittlesPerPage"/>
}
The problem was not solved but I changed my workspace and try to do it copy the codes. Besides, I will try to use a different version of Tomcat or install a Jboss

Failed to Load ApplicationContext during Spring unit test

I am trying to run a Junit functional test using Springs java-config for my application context. I am not sure if it is a problem with Spring or Junit... just not sure.. The application runs fine on my local server (hitting the db), but when I try to run my test it bombs out.
I just moved from xml to java config so I can always import my xml context files (which I know works in my tests) but going forward I would rather just use my java config.
My Test Class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = { AppConfig.class, ServletConfig.class })
#EnvironmentConfiguration(db2Enabled = true)
public class EventDAOTest {
The StackTrace
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader <clinit>
SEVERE: ERROR - Configuration Framework not detected!
Feb 4, 2014 11:51:45 AM com.aoins.config.CachingPropertyFileReader readFile
SEVERE: Unable to build property reference for: (common).
2014-02-04 11:51:45,510 | DEBUG | : | LoggerConfigurer | Msg: Log4j configured with: 'C:/javalog/log4jPCProperties.xml'
2014-02-04 11:51:48,248 | INFO | : | EnvironmentConfigurer | Msg: DB2 Connection was established
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: CICS Connection was established
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: JMS Connection was NOT established according to the configuration
2014-02-04 11:51:48,279 | INFO | : | EnvironmentConfigurer | Msg: EMail Connection was NOT established according to the configuration
Feb 4, 2014 11:51:48 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext#215d215d: startup date [Tue Feb 04 11:51:48 EST 2014]; root of context hierarchy
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associates],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associate.AssociateDataController.retrieveAssociates(java.lang.String)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/associateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/dateFilterTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.datefiltertype.DateFilterDataController.retrieveEventFilterType(java.lang.String) throws com.aoins.sales.eventplanning.datefiltertype.DateFilterTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/departments/{pDepartmentCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.department.DepartmentDataController.retrieveDepartment(java.lang.String) throws com.aoins.sales.eventplanning.department.DepartmentNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/divisions],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.division.DivisionDataController.retrieveDivisionsDepartments()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showEvents()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[//Test],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.aoins.sales.eventplanning.events.EventController.showTests()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveEvent(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[GET],params=[page && associateFilter && dateFilter],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.retrieveFiltered(com.aoins.sales.eventplanning.associatefiltertype.AssociateFilterType,com.aoins.sales.eventplanning.datefiltertype.DateFilterType,java.lang.Integer,com.aoins.sales.user.User)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/events],methods=[POST],params=[],headers=[],consumes=[application/json],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.events.EventDataController.saveEvent(com.aoins.sales.eventplanning.events.EventBeanImpl,com.aoins.sales.user.User) throws com.aoins.sales.eventplanning.events.EventException
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public java.util.List<com.aoins.sales.eventplanning.events.Event> com.aoins.sales.eventplanning.events.EventDataPublicController.doList()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/Public/events/{pEventId}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public com.aoins.sales.eventplanning.events.Event com.aoins.sales.eventplanning.events.EventDataPublicController.doRetrieve(java.lang.Integer)
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventTypes()
Feb 4, 2014 11:51:49 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/Data/eventTypes/{pTypeCode}],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.ui.ModelMap com.aoins.sales.eventplanning.eventtype.EventTypeDataController.retrieveEventType(java.lang.String) throws com.aoins.sales.eventplanning.eventtype.EventTypeNotFoundException
Feb 4, 2014 11:51:49 AM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#20c820c8] to prepare test instance [com.aoins.sales.eventplanning.events.EventDAOTest#f7e0f7e]
Throwable occurred: java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:326)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
at com.aoins.func.tester.AOSpringFunctionalTester.run(AOSpringFunctionalTester.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:121)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 26 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
... 41 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at java.lang.Throwable.<init>(Throwable.java:67)
at org.springframework.util.Assert.notNull(Assert.java:111)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:330)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.CGLIB$defaultServletHandlerMapping$22(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f$$FastClassByCGLIB$$ff8cbba8.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:326)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$104f0b6f.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 42 more
So it appears that it is not finding the configuration framework, but I have been following the reference guides and API... not sure what I am missing or not configuring correctly. I am using Spring 4.0, Junit 4.10
Also, for each test it throws this error. That to me means it is trying to load the ApplicationContext again (prepareRefresh)... once for each #Test -- that also doesn't make sense to me...
Here are some resources:
ContextConfiguration API
Spring Reference Guide
Spring blog post
I moved from spring 3.2.0 to 4.0.3 and had to update my javax.servlet dependency (in maven) from servlet 2.5 to servlet 3.0.1. The final dependency was
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
Then it worked
You'll need to annotate your test class with
#WebAppConfiguration
so that the test environment provides your WebApplicationContext with a mock ServletContext required by your MVC configuration.
Since a couple people mentioned Servlet version issues:
As of Spring 4.0 the set of mocks is now based on the Servlet 3.0 API.
You have two options:
use 3.2.x spring-test dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.14.RELEASE</version>
<scope>test</scope>
</dependency>
upgrade to servlet 3.0
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
In gradle
testCompile 'javax.servlet:javax.servlet-api:3.1.0'
Note: this works for me even though I'm testing against Google App Engine (servlet 2.4) Because it is only used for tests.
https://jira.spring.io/browse/SPR-11049
the way to solve such problems -
try to force import of the notFoundClass manually, by smth like:
Class c = javax.servlet.SessionCookieConfig.class;
so Idea+Maven suggested me to add maven dependency, i agreed. And suddenly in pom.xml the code appeared:
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-servlet_3.0_spec</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
then i removed "Class c = javax.servlet.SessionCookieConfig.class;" - there is no need in it, rather than to load necessary dependency.
You can add a MockServletContext to your test applicationContext.
The MockServletContext can be found in spring-test.jar (or maven dependency). You should (obviously) not use this in production, but only register it in a context that you include in your test context.
Use #ActiveProfiles({"{test", "default"}) annotation

Resources