I'm trying to learn spring MVC, so far so good but I'm kind of stuck now. I'm trying to learn how to create json and get it with javascript(jquery).
But for testing purposes I tried to create something just so I can see that is displayed properly trough http request, then I'll try to create json and get it, but so far I can't even get the request to work. Here is my controller :
#Controller
#RequestMapping(value="/")
public class IndexController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
Map<Long,Item> itemMap = createItemMap();
#RequestMapping(value="item/{itemId}", method=RequestMethod.GET)
public #ResponseBody Item get(#PathVariable Long itemId) {
Item item = itemMap.get(itemId);
if (status == null) {
throw new ResourceNotFoundException(itemId);
}
return item;
}
private Map<Long,Item> createItemMap(){
//omitted because its irrelevant
//I created 2 item objects , with id 1 and 2 for testing purposes
}
}
This is content of my servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Imports user-defined #Controller beans that process client requests -->
<beans:import resource="controllers.xml" />
</beans:beans>
And controllers.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/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">
<!-- Scans within the base package of the application for #Components to configure as beans -->
<context:component-scan base-package="com.testing.mvc.controller" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
</beans>
My war is called Test.war, when I try localhost:8080/Test I get index view which is OK. But regardless of what I try:
localhost:8080/Test/item/1
localhost:8080/Test/item?itemId=1
localhost:8080/item?itemId=1
I end up with some kind of error, the most interesting is this one :
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
I've googled alot found these to be interesting :
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/
Mapping restful ajax requests to spring
Spring's Json not being resolved with appropriate response
Nothing helped so far, any idea what I'm missing. Sorry for providing too much info.
As far as I can tell you are missing this resolver like this in your dispatcher serlet:
<bean name="jsonViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
</bean>
Take look at this:
http://spring-json.sourceforge.net/quick_simpleform.html
You have to create file views.xml in yoru WEB-INF direcotry with this content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView"/>
</beans>
Related
I have a basic spring MVC project (the basic mold they create) and am trying to get it to run a html instead of a JSP (JSP works perfect)
my controller
#Controller
#RequestMapping("/")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello world!");
return "index";
}
}
my mvc dispatcher service
<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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.springapp.mvc"/>
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<property name="prefix" value="/WEB-INF/pages/"/>-->
<!--<property name="suffix" value=""/>-->
<!--</bean>-->
<mvc:resources mapping="/WEB-INF/pages/" location="/WEB-INF/pages/" />
I've tried numerous things, such as mapping to /WEB-INF/pages/** , removing the InternalResourceViewResolver completely (W/ the previous mappings,) leaving the suffix empty, with html, etc but to no avail. I've looked at the other questions similar to this but no luck. Also read about static folder for the htmls, but was confused... What am I doing wrong?
the file structure for webpages
webapp
--WEB-INF
----pages
------hello.jsp, index.html
<mvc:resources mapping="/WEB-INF/pages/" location="/WEB-INF/pages/" />
Mapping value stands for URL mapping. So give here for example "/pages/**"
<mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" />
Now you can access to static files like html page by localhost:8080/app/pages/index.html for example.
In Java Controller instead of return "index"; there should be return "redirect:/pages/index.html";
Read this example to get all detailed informations. Hope i could help.
I am pretty new in Spring and I have the following problem.
In a tutorial I found this configuration class example:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
.................
..............
}
How exactly works the addResourceHandlers() method in the previous code snippet? Looking on the official documentation it seems to understand that it add handlers to serve static resources such as images, js, and, css files from specific locations under web application root, the classpath, and others.
In the previous case it is used to add static resources related to Twitter BootStrap framework (something like CSS files and JavaScript files).
The problem is that the project on which I am working don't use Java configuration but use XML configuration and I have some problem to understand how can I do the same thing of the previous code snippet into my XML configuration.
In particular I have a servlet-context.xml file that contains the MVC configuration:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="it.hp.miur" />
</beans:beans>
I think that I have to put this configuration into this file but I don't know how do it. Can you help me?
Tnx
I have a web application which has more than 40 Mbean. I used Spring Framework.
I am doing good and its working well. But i have 40 Mbean, so want to generalize the thing.
#Component
#ManagedResource(objectName="ProjectCache:name=XMBean", log=true, logFile="jmx.log")
public class XMBean extends AbstractCacheMBean<String, XCO, XCache> {
#ManagedOperation(description ="ProjectCache XCO key")
#Override
public List<String> showAllKeys(){
return super.getKey();
}
#ManagedOperation(description ="ProjectCache XCO")
public List<String> showAllElements(){
return super.findAll();
}
#Override
public XCache getCache() {
return getFacadeCache().getXCache();
}
#ManagedOperation(description ="ProjectCache XCO by key)
#Override
public String ShowbyKey(String key) {
return super.findbyKey(key);
}
}
Now i have Same way Class YMbean, AMBean and so.
I configured the Spring in application mbean.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/beans"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- this bean must not be lazily initialized if the exporting is to happen -->
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
<property name="server" ref="mbeanServer"/>
<property name="assembler" ref="assembler" />
<property name="namingStrategy" ref="namingStrategy" />
</bean>
<bean id="jmxAttributeSource" class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
<!-- will create management interface using annotation metadata -->
<bean id="assembler" class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<property name="attributeSource" ref="jmxAttributeSource" />
</bean>
<!-- will pick up the ObjectName from the annotation -->
<bean id="namingStrategy" class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource" ref="jmxAttributeSource" />
</bean>
<bean id="xMBean"
class="in.projet.business.mbean.XMBean">
<property name="memoryCache" ref="repository" />
</bean>
And same way i am going to preapre YMbean Class and in xml going to initialise.
What should i do that not require modification in XML Whatsoever or number of class i create ,dont require to update XML.
property is same in all Mbean which i am going to use.
All ideas or input are welcome.
Thanks
Remove all of your configuration and replace with the use of the namespace and only once. Also your MBeans are #Components so you can simply scan for them. Which only would leave you with the following lines of xml
<context:component-scan base-package="in.projet.business.mbean" />
<context:mbean-export/>
Or if you want to keep your current configuration instead of the namespace replace it at least with the following and remove all other beans. This enables autodetection of MBeans in your application context (this is basically the same as the <context:mbean-export /> does.
For more information I strongly suggest the JMX chapter of the reference guide.
I am using SpringMVC 3 with Annotated Controllers. I successfully mapped my URL ("/HelloWorld) to a Controller and defined its GET processing method.
The error is that upon typing the (App)/HelloWorld URL, my web server (GlassFish) gives this error:
The requested resource is not available.
But in the GlassFish log I see that the URL was mounted.
Mapped "{[/HelloWorld],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView controllers.HelloWorldController.processHelloWorld()
My Files:
(1) HelloWorldController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
*
* #author */
#Controller
#RequestMapping("/HelloWorld")
public class HelloWorldController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView processHelloWorld()
{
ModelAndView model = new ModelAndView("HelloWorldPage");
model.addObject("msg", "Expanded string - hello world");
return model;
}
}
(2) Dispatcher-Servlet.xml. Note the MVC-Annotation-Driven approach. The indexController is not used.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="controllers" />
<mvc:annotation-driven />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
(3) HelloWorldPage.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Spring MVC Hello World Annotation Example</h1>
<h2>${msg}</h2>
</body>
</html>
Any ideas why the URL "/HelloWorld" is not being found? Thanks.
Problem solved. I had to invoke the URL "/HelloWorld.htm" for the mapping to work.
(The Dispatcher-Servlet's mapping in web.xml is "*.htm".) Thanks
I know this is a duplicate and you people are gonna chide me for it, but I didn't get a proper solution after reading all the posts.
I am trying to build a Spring Template application in Spring Source Tool Suite.
I am getting the following error.
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 16 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'resources'.
My root-context.xml is like this:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
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-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
</beans>
Please let me know if there is a jar file missing in my application.
These are the only jar files I have in my application:
displaytag-1.0-b3.jar, spring-2.0.6.jar, spring-asm-3.0.3.RELEASE.jar, spring-beans-3.0.3.RELEASE.jar, spring-context-3.0.3.RELEASE.jar, spring-core-3.0.3.RELEASE.jar, spring-expression-3.0.3.RELEASE.jar, spring-hibernate3-2.0.8.jar, spring-web-3.0.3.RELEASE.jar & spring-webmvc-3.0.3.RELEASE.jar
Here is my servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.foo.controller" />
</beans:beans>
Please help...it's really annoying.
Your XML is fine, but according to this comment on a SpringSource blog post about Spring MVC 3
The <mvc:resources/> tag is a new feature coming in Spring Framework 3.0.4
Your application uses Spring 3.0.3, so you need to upgrade to 3.0.4 or later to be able to use the resources tag.