I'm using Spring 3.0.5. None of my annotated controllers are getting recognized. I have XML for my application …
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:annotation-driven/>
<context:component-scan base-package="com.myco.systems.leadsmonitor"/>
My static assets are getting picked up fine. But I'm getting a 404 when I try and reach an annotated controller …
package com.myco.systems.leadsmonitor.web.controller;
#Controller
public class HomeController {
…
#RequestMapping("/")
public void index(Model model) {
model.addAttribute("latestLeadTime", MonitorStatistics.getInstance().getLatestLeadCreationTime());
model.addAttribute("lastDBCheck", MonitorStatistics.getInstance().getLastDBCheck());
}
What else do I need to do to get my controllers picked up by Spring? Thanks, - Dave
I think the reason you are getting a 404 is because the view is not being resolved in the contoller method. By default a void return type is mapped using to a view name based on the URI, in your case since the path is "/", it probably gets resolved to "", which does not get mapped to any logical view.
Can you try a couple of things:
Start in a debug mode and see if your request is actually coming to the RequestMapping method
If it is, can you explicitly return a view name from your method and see if this view name is getting resolved to a correct view(assuming that you have a view resolver registered)
You should check both URL mappings in web.xml and view resolution configuration in your spring configuration.
One good resource is Spring By Example.org
see: http://www.springbyexample.org/examples/simple-spring-mvc-form-annotation-config-webapp.html
Another one are the tutorials available in SpringSource ToolSuite (STS), where they walk you through creating a Spring MVC web application. Those tutorials usually include the UrlRewriteFilter from tuckey.org
e.g. servlet maps to /app, then add this servlet filter
<!-- Enables clean URLs with JSP views e.g. /welcome instead of /app/welcome -->
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<!-- <init-param>-->
<!-- <param-name>logLevel</param-name>-->
<!-- <param-value>DEBUG</param-value>-->
<!-- </init-param>-->
</filter>
Related
I have 3 modules on project. One of them calls common. In this module i am trying to start Spring container. One of beans live in another module (webapp) and also i have a module testapp. So now, after deploying project on server (webapp and common) it is all OK, but if I try to deploy common and testapp it fails with exception:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class[...]
i whant to know if it is any possibility to ignore unexisting bean and run container? I am using xml configuration, no annotations. Due to business logic it should be exactly xml
Make use of Spring profiles to determine when specific beans should be instantiated. For example you can have two profiles web (for common + webapp) and test (for common + testapp)
Then in your application context xml configuration define your beans as follows
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- define common beans here-->
<beans profile="test">
<!-- define test beans here-->
</beans>
<beans profile="web">
<!-- define web beans here-->
</beans>
</beans>
Then depending on how you launch your application you need to provide a system property named spring.profiles.active to provide the profile to use.
For example -Dspring.profiles.active=web or -Dspring.profiles.active=test
I am inheriting a project from a developer who left, and I am trying to understand GWT and Spring Framework.
The original problem that lead me to this path: GWT had one module where I loaded ALL third party javascripts... that could result in conflicts. Example, I would include chart drawing libraries, etc. all in one page.
Possible solutions: Have the chart drawing library in an iframe so that it would not conflict with other third party libraries of javascript... OR open the page in a new window.
I decided to go with a new window.
So I did this:
Window.Location.assign(GWT.getHostPageBaseURL()
+ "chartModule.html?gwt.codesvr=127.0.0.1:9997/");
However, in my new chartModule.java (GWT) the problem I have is I do not have the beans/classses defined in (Spring framework) applicationContext.xml anymore:
#Autowired
ApplicationContext applicationContext;
And applicationContext is null after I have changed the host page url... so I do not have any beans that I tried autowiring...
Is it possible to reload the beans from applicationContext.xml??
Here is my 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- This file has properties that are used by other XML files loaded via ${var name} syntax -->
<context:property-placeholder location="/WEB-INF/classes/environment.properties" />
<import resource="spring-security-cas.xml" />
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans. For example #Controller and #Service. Make sure to set the
correct base-package -->
<context:component-scan base-package="com.javamango.sixtydegrees" />
<import resource="mongo-config.xml" />
<import resource="rabbitmq-context.xml" />
<import resource="spring-mail.xml" />
</beans>
You cannot use spring beans on client side. If you want retriewe some data from spring in gwt, you can do this at two ways:
1) use server side library like gwt-sl to inject spring beans in gwt servlet
#Service("greetingService")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService
{
#SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(GreetingServiceImpl.class);
#Autowired
UserFileService userFileService;
#Autowired
UserService userService;
}
now you can autowire spring beans and obtain data via gwt-rpc
2) put data via jsp in hidden html form fields and retriewe data from it
<input type="hidden" value="7" id="documentid"/>
String id = (InputElement) (Element) DOM.getElementById("documentid").value
im using spring for my java web app. the site has got bigger and i would like to set some configurations.
i have been researching and came across things like document builder factory, replacing spring xml with java config and others. i dunno where to start.
im thinking of implementing the configurations in xml (WEB/newConfig.xml) and have it read by the java beans. basically i wanna input my cofiguration values into xml and have it load by a java bean so that i can use it in controllers and jstl.
im just giving some examples here. for example xml configurations:
<property name="numberOfCars" value="3" />
<property name="webSiteName" value="New Spring Web App" />
....
and i read it in my java class:
class Config {
public getNumberOfCars() {
return numOfCars;
}
public getWebSiteName() {
return webSiteName;
}
}
where should i start and what online materials can i read?
==============================
update
here is what i have created.
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="/WEB-INF/your_prop_file.properties" />
<bean id="ConfigMgr" class="org.domain.class.ConfigMgr">
<property name="username" value="${username}">
</bean>
</beans>
you_prop_file.properties
username=hello world name
ConfigMgr.java
public class ConfigMgr {
private String username;
...getter
...setter
}
in my controller, here is what i did:
ConfigMgr config = new ConfigMgr();
sysout.out.println(config.getUsername());
i am getting null and i am sure im missing something here. where should i set the username value to the ConfigMgr class?
Spring Java configuration is a newer feature that allows you to configure your Spring application using Java classes instead of XML files. Its just an alternative for XML configuration. XML way is equally feature rich.
From what I could figure out from your problem, you want to move the hardcoded values of params (numberOfCars,webSiteName.. ) outisde your configuration file.
If that is the case, you don't have to go that far.
Just use :-
<context:property-placeholder location="classpath:your_prop_file.properties" />
in your spring xml file and replace the param values like:-
<property name="webSiteName" value="${website.name}" />
You need to have a your_prop_file.properties file in your classpath with enteries like:-
website.name=New Spring Web App
You are not injecting the ConfigMgr bean that you created in XML file.
What you are doing is you are creating a new Object in controller which does not have a clue about properties file.
Now you can inject it using either #Autowired inside your controller or through xml configuration.
There are plenty of examples available in google on basic spring dependency injection.
I am working on struts2 application with spring for back end.
We are using database.properties file and the entries are as follows:
jdbc.url=jdbc:mysql://localhost:3306/myDb
jdbc.username=root
jdbc.password=rooooot
jdbc.csvlocation=C:\myCSV
I added the following new entry in database.properties
enhancePerf.Flag=true
In applicationcontext.xml I am fetching the value like this :-
<bean id="userLogin" scope="prototype"
class="com.hello.something.actions.UserLoginAction">
<property name="perfEnhance" value="${enhancePerf.Flag}"/>
</bean>
After declaring a global variable perfEnhance in UserLoginAction, and forming the setters and getters method of the same, I'm still not getting the value.
I followed the following link:-
http://www.roseindia.net/tutorial/spring/spring3/web/applicationcontext.xml-properties-file.html
Please advise.
Instead of your PropertyPlaceholderConfigurer bean, put:
<context:property-placeholder location="classpath:path/to/database.properties"
ignore-unresolvable="false"/>
This way if the property is not found, it will complain. Otherwise it seems that you may have another "database.properties" file in your classpath, that simply does not have such a property.
Make sure that "path/to/database.properties" is in your classpath. If database.properties itself is your class path, then no "path/to" is needed => just classpath:database.properties
You also have to configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, as well as you have to use bean names in Struts config. If you have the following in your struts-config.xml file:
<action path="/users" .../>
You must define that Action's bean with the "/users" name in action-servlet.xml:
<bean name="/users" .../>
Please take a look at Spring Struts Integration from official Spring's docs.
EDIT to answer the comment:
context is an XML namespace that should be defined in the XML file where it is used:
<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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
I'm just starting with Spring MVC trying to create a new project, and came accross an issue for which no manual or tutorial seems to help...
I have set up a simple application with no logic, just trying to get Spring configured properly. The controller just returns the name of a view to be displayed, but the view resolver is not rendering the jsp, and returning a 404 error....
Any help is greatly appreciated.
My web.xml is:
<web-app 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">
<servlet>
<servlet-name>openstats</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>openstats</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<display-name>OpenStats API Server</display-name>
</web-app>
An my openstats-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<context:component-scan base-package="org.openstats.api.controller"/>
<!-- Enable to request mappings PER METHOD -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- Enable annotated POJO #Controller -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<!-- Define the view resolver to use jsp files within the jsp folder -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="prefix"><value>/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
</beans>
The controller itself has no logic whatsoever, it's simply:
#Controller
public class ProductController {
#RequestMapping(value = "/products.do", method = RequestMethod.GET)
public ModelAndView listProducts(HttpServletRequest request) {
ModelAndView model = new ModelAndView("index");
return model;
}
}
The controller is reached, the issue is when attempting to render...
I set up log4j in debug, and this is part of what I get:
02:08:19,702 DEBUG
DispatcherServlet:1094 - Testing handler adapter
[org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#397b6074]
02:08:19,803 DEBUG
HandlerMethodInvoker:134 - Invoking
request handler method: public org.springframework.web.servlet.ModelAndView
org.openstats.api.controller.ProductController.listProducts(javax.servlet.http.HttpServletRequest)
02:08:19,833 DEBUG
DefaultListableBeanFactory:1367 -
Invoking afterPropertiesSet() on bean
with name 'index' 02:08:19,876 DEBUG
InternalResourceViewResolver:81 -
Cached view [index] 02:08:19,877 DEBUG
DispatcherServlet:1181 - Rendering
view
[org.springframework.web.servlet.view.JstlView:
name 'index'; URL [/jsp/index.jsp]] in
DispatcherServlet with name
'openstats' 02:08:19,877 DEBUG
JstlView:240 - Rendering view with
name 'index' with model {} and static
attributes {} 02:08:19,923 DEBUG
JstlView:234 - Forwarding to resource
[/jsp/index.jsp] in
InternalResourceView 'index'
02:08:19,926 DEBUG
DispatcherServlet:955 -
DispatcherServlet with name
'openstats' determining Last-Modified
value for [/api-server/jsp/index.jsp]
02:08:19,927 DEBUG
DispatcherServlet:1054 - Testing
handler map
[org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#440c4cee]
in DispatcherServlet with name
'openstats' 02:08:19,928 DEBUG
DefaultAnnotationHandlerMapping:179 -
No handler mapping found for
[/jsp/index.jsp] 02:08:19,929 DEBUG
DispatcherServlet:962 - No handler
found in getLastModified 02:08:19,937
DEBUG DispatcherServlet:781 -
DispatcherServlet with name
'openstats' processing request for
[/api-server/jsp/index.jsp]
02:08:19,938 DEBUG
DispatcherServlet:843 - Bound request
context to thread: GET
/api-server/products.do HTTP/1.1
My jsp folder is right within "webapp" and the index.jsp file exists.
Thanks in advance.
I do have the same problem with Spring 3.x.
Any progress so far?
EDIT:
I figured it out myself :-) I used the following servletmapping:
<servlet-mapping>
<servlet-name>spring-frontcontroller</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Editing the url-pattern to e.g. *.do fixes the problem of not rendering the JSP.
But this leaves the question how this is possible with your url-pattern.
Does your web.xml define index.jsp in the welcome-file-list, if so it may be getting overridden. Try changing the jsp name to products.jsp.
e.g.
#Controller
public class ProductController {
#RequestMapping(value = "/products.do", method = RequestMethod.GET)
public String handleRequest() {
return "products";
}
}
doesn't your .jsp and your .do conflict? since a file cannot end with both .jsp and .do .. therefore it will never resolve... so you should get rid of .jsp or change your url pattern to /*
Changing
import org.springframework.web.servlet.ModelAndView;
by
import org.springframework.web.portlet.ModelAndView;
Works in my case.