springmvc+velocity+ Rest Services(xml,json)实例

来源:互联网 发布:飞控编程用什么语言 编辑:程序博客网 时间:2024/06/05 17:21

项目结构截图如下,该项目由maven构建的web项目,实例简单,无数据库连接操作,功能演示的请求地址分别在controller包下的三个类中,本例中的请求地址为:

http://localhost:8080/spring-mvc-velocity-bootstrap/greet           --默认欢迎

http://localhost:8080/spring-mvc-velocity-bootstrap/greet/zhangsan        --欢迎某人,这里是zhangsan,可任意

http://localhost:8080/spring-mvc-velocity-bootstrap/hello   --默认hello

http://localhost:8080/spring-mvc-velocity-bootstrap/hello-world     --hello world

http://localhost:8080/spring-mvc-velocity-bootstrap/hello-redirect     --重定向到hello world请求

http://localhost:8080/spring-mvc-velocity-bootstrap/user/zhang/san.json     --请求参数为json格式

http://localhost:8080/spring-mvc-velocity-bootstrap/user/zhang/san.xml      --请求参数为xml格式


该项目为简单的springmvc+velocity+rest service,且无数据库连接操作,下面给出controller包下的请求配置,和spring的xml文件配置,和velocity的模板配置,和web.xml的加载,监听配置。


三个controller类的请求配置的代码依次为:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package net.exacode.bootstrap.web.controller;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.ModelMap;  
  8. import org.springframework.web.bind.annotation.PathVariable;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.RequestParam;  
  12.   
  13. /** 
  14.  * Presents how to pass some values to controller using URL. 
  15.  *  
  16.  * @author pmendelski 
  17.  *  
  18.  */  
  19. @Controller  
  20. public class GreetingsController {  
  21.     private final Logger logger = LoggerFactory.getLogger(getClass());  
  22.   
  23.     @RequestMapping(value = "/greet/{name}", method = RequestMethod.GET)  
  24.     public String greetPath(@PathVariable String name, ModelMap model) {  
  25.         logger.debug("Method greetPath");  
  26.         model.addAttribute("name", name);  
  27.         return "greetings";  
  28.     }  
  29.   
  30.     @RequestMapping(value = "/greet", method = RequestMethod.GET)  
  31.     public String greetRequest(  
  32.             @RequestParam(required = false, defaultValue = "John Doe") String name,  
  33.             ModelMap model) {  
  34.         logger.debug("Method greetRequest");  
  35.         model.addAttribute("name", name);  
  36.         return "greetings";  
  37.     }  
  38. }  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package net.exacode.bootstrap.web.controller;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8.   
  9. /** 
  10.  * Simple hello world controller. 
  11.  * Presents basic usage of SpringMVC and Velocity. 
  12.  * @author pmendelski 
  13.  * 
  14.  */  
  15. @Controller  
  16. public class HelloWorldController {  
  17.       
  18.     private final Logger logger = LoggerFactory.getLogger(getClass());  
  19.   
  20.     @RequestMapping(value = "/hello", method = RequestMethod.GET)  
  21.     public String hello() {  
  22.         logger.debug("Method hello");  
  23.         return "hello";  
  24.     }  
  25.   
  26.     @RequestMapping(value = "/hello-world", method = RequestMethod.GET)  
  27.     public String helloWorld() {  
  28.         logger.debug("Method helloWorld");  
  29.         return "hello-world";  
  30.     }  
  31.       
  32.     @RequestMapping(value = "/hello-redirect", method = RequestMethod.GET)  
  33.     public String helloRedirect() {  
  34.         logger.debug("Method helloRedirect");  
  35.         return "redirect:/hello-world";  
  36.     }  
  37.   
  38. }  

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package net.exacode.bootstrap.web.controller;  
  2.   
  3. import net.exacode.bootstrap.web.model.User;  
  4.   
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.http.MediaType;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import org.springframework.web.bind.annotation.ResponseBody;  
  13.   
  14. /** 
  15.  * Service hello world controller. 
  16.  * Presents basic usage of SpringMVC and REST service API. 
  17.  * @author pmendelski 
  18.  * 
  19.  */  
  20. @Controller  
  21. public class UserServiceController {  
  22.     private final Logger logger = LoggerFactory.getLogger(getClass());  
  23.   
  24.     @RequestMapping(value = "/user/{name}/{surname}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)  
  25.     public @ResponseBody User getUserJson(@PathVariable String name, @PathVariable String surname) {  
  26.         logger.trace("Responding service request");  
  27.         User user = new User(name, surname);  
  28.         return user;  
  29.     }  
  30.       
  31.     @RequestMapping(value = "/user/{name}/{surname}.xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)  
  32.     public @ResponseBody User getUserXml(@PathVariable String name, @PathVariable String surname) {  
  33.         logger.trace("Responding service request");  
  34.         User user = new User(name, surname);  
  35.         return user;  
  36.     }  
  37.   
  38. }  

然后是spring的xml配置如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xmlns:sec="http://www.springframework.org/schema/security"   
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.     http://www.springframework.org/schema/mvc  
  10.     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  11.     http://www.springframework.org/schema/context  
  12.     http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  13.     <mvc:annotation-driven />  
  14.     <mvc:default-servlet-handler/>  
  15.     <mvc:resources mapping="/resources/**" location="/resources/" />  
  16.     <context:component-scan base-package="net.exacode.bootstrap.web" />  
  17.       
  18.     <bean id="velocityConfig"  
  19.         class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">  
  20.         <property name="configLocation">  
  21.             <value>/WEB-INF/velocity/velocity.properties</value>  
  22.         </property>  
  23.     </bean>  
  24.   
  25.     <bean id="viewResolver"  
  26.         class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">  
  27.         <property name="cache" value="false" />  
  28.         <property name="layoutUrl" value="/layout/main.vm" />  
  29.         <property name="prefix" value="/templates/" />  
  30.         <property name="suffix" value=".vm" />  
  31.         <property name="exposeSpringMacroHelpers" value="true" />  
  32.         <property name="contentType" value="text/html;charset=UTF-8" />  
  33.         <property name="viewClass"  
  34.             value="org.springframework.web.servlet.view.velocity.VelocityLayoutView" />  
  35.     </bean>  
  36.   
  37.     <!-- Internationalization -->  
  38.     <bean id="messageSource"  
  39.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
  40.         <property name="basename" value="classpath:i18n/messages" />  
  41.         <property name="defaultEncoding" value="UTF-8" />  
  42.     </bean>  
  43.   
  44.     <bean id="localeChangeInterceptor"  
  45.         class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">  
  46.         <property name="paramName" value="lang" />  
  47.     </bean>  
  48.   
  49.     <bean id="localeResolver"  
  50.         class="org.springframework.web.servlet.i18n.CookieLocaleResolver">  
  51.         <property name="defaultLocale" value="en" />  
  52.     </bean>  
  53.   
  54.     <bean id="handlerMapping"  
  55.         class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">  
  56.         <property name="interceptors">  
  57.             <ref bean="localeChangeInterceptor" />  
  58.         </property>  
  59.     </bean>  
  60. </beans>  

然后是三个velocity的模板和属性文件的配置:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #define($content)  
  2.     <p>#springMessage("Hello"): $name</p>  
  3.     <p>#springMessage("Greetings")</p>  
  4. #end  

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #define($content)  
  2.     #springMessage("Hello")  
  3. #end  

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #set($page_title="#springMessage('HelloWorld')")  
  2.   
  3. #define($content)  
  4.     #springMessage("HelloWorld")  
  5. #end  

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
  1. velocimacro.permissions.allow.inline=true  
  2. velocimacro.permissions.allow.inline.to.replace.global=true  
  3. velocimacro.permissions.allow.inline.local.scope=true  
  4. input.encoding=UTF-8  
  5. output.encoding=UTF-8  
  6. resource.loader=webapp, class  
  7. class.resource.loader.description=Velocity Classpath Resource Loader  
  8. class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader   
  9. webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader  
  10. webapp.resource.loader.path=/WEB-INF/velocity/  
  11. webapp.resource.loader.cache=false  

最后是web.xml的配置:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  5.     <welcome-file-list>  
  6.         <welcome-file>index.jsp</welcome-file>  
  7.     </welcome-file-list>  
  8.     <!-- The definition of the Root Spring Container shared by all Servlets   
  9.         and Filters -->  
  10.     <context-param>  
  11.         <param-name>contextConfigLocation</param-name>  
  12.         <param-value>classpath:applicationContext.xml</param-value>  
  13.     </context-param>  
  14.     <!-- Creates the Spring Container shared by all Servlets and Filters -->  
  15.     <listener>  
  16.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  17.     </listener>  
  18.     <listener>  
  19.         <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
  20.     </listener>  
  21.     <servlet>  
  22.         <servlet-name>springDispatcher</servlet-name>  
  23.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  24.         <load-on-startup>1</load-on-startup>  
  25.     </servlet>  
  26.     <servlet-mapping>  
  27.         <servlet-name>springDispatcher</servlet-name>  
  28.         <url-pattern>/</url-pattern>  
  29.     </servlet-mapping>  
  30. </web-app>  

其他具体代码实现我已上传到http://download.csdn.net/detail/johnjobs/7139187,maven构建完成之后,部署到tomcat等容器下,请求上面给到的请求地址,即可以看到效果演示,以下为效果截图,例子较为简单:








0 0
原创粉丝点击