springmvc+velocity+Reservices(xml,json)の例

12520 ワード

springmvc+velocity+ Rest Services(xml,json)实例_第1张图片
プロジェクト構造の概略図は、このプロジェクトは、mavenによって構築されたウェブプロジェクトの実例が簡単で、データベース接続操作がなく、機能デモンストレーションの要求アドレスは、それぞれcontrollerパッケージの下の3つのカテゴリーにあり、本例の要求アドレスは以下の通りである.
http://localhost:8080/spring-mvc-velocity-bootstrap/greet--デフォルト歓迎
http://localhost:8080/spring-mvc-velocity-boot strap/greet/zhangsan--誰かを歓迎します.ここはzhangsanです.任意でいいです.
http://localhost:8080/spring-mvc-velocity-bootstrap/hello--デフォルトハロー
http://localhost:8080/spring-mvc-velocity-bootstrap/hello-world--hello world
http://localhost:8080/spring-mvc-velocity-bootstrap/hello-redict-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類の要求配置のコードは、次の通りである.
package net.exacode.bootstrap.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Presents how to pass some values to controller using URL.
 * 
 * @author pmendelski
 * 
 */
@Controller
public class GreetingsController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value = "/greet/{name}", method = RequestMethod.GET)
	public String greetPath(@PathVariable String name, ModelMap model) {
		logger.debug("Method greetPath");
		model.addAttribute("name", name);
		return "greetings";
	}

	@RequestMapping(value = "/greet", method = RequestMethod.GET)
	public String greetRequest(
			@RequestParam(required = false, defaultValue = "John Doe") String name,
			ModelMap model) {
		logger.debug("Method greetRequest");
		model.addAttribute("name", name);
		return "greetings";
	}
}
package net.exacode.bootstrap.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Simple hello world controller.
 * Presents basic usage of SpringMVC and Velocity.
 * @author pmendelski
 *
 */
@Controller
public class HelloWorldController {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String hello() {
		logger.debug("Method hello");
		return "hello";
	}

	@RequestMapping(value = "/hello-world", method = RequestMethod.GET)
	public String helloWorld() {
		logger.debug("Method helloWorld");
		return "hello-world";
	}
	
	@RequestMapping(value = "/hello-redirect", method = RequestMethod.GET)
	public String helloRedirect() {
		logger.debug("Method helloRedirect");
		return "redirect:/hello-world";
	}

}
package net.exacode.bootstrap.web.controller;

import net.exacode.bootstrap.web.model.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Service hello world controller.
 * Presents basic usage of SpringMVC and REST service API.
 * @author pmendelski
 *
 */
@Controller
public class UserServiceController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@RequestMapping(value = "/user/{name}/{surname}.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody User getUserJson(@PathVariable String name, @PathVariable String surname) {
		logger.trace("Responding service request");
		User user = new User(name, surname);
		return user;
	}
	
	@RequestMapping(value = "/user/{name}/{surname}.xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody User getUserXml(@PathVariable String name, @PathVariable String surname) {
		logger.trace("Responding service request");
		User user = new User(name, surname);
		return user;
	}

}
その後、スプリングの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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:sec="http://www.springframework.org/schema/security" 
	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:annotation-driven />
	<mvc:default-servlet-handler/>
	<mvc:resources mapping="/resources/**" location="/resources/" />
	<context:component-scan base-package="net.exacode.bootstrap.web" />
	
	<bean id="velocityConfig"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="configLocation">
			<value>/WEB-INF/velocity/velocity.properties</value>
		</property>
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
		<property name="cache" value="false" />
		<property name="layoutUrl" value="/layout/main.vm" />
		<property name="prefix" value="/templates/" />
		<property name="suffix" value=".vm" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="contentType" value="text/html;charset=UTF-8" />
		<property name="viewClass"
			value="org.springframework.web.servlet.view.velocity.VelocityLayoutView" />
	</bean>

	<!-- Internationalization -->
	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:i18n/messages" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>

	<bean id="localeChangeInterceptor"
		class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
		<property name="paramName" value="lang" />
	</bean>

	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
		<property name="defaultLocale" value="en" />
	</bean>

	<bean id="handlerMapping"
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<property name="interceptors">
			<ref bean="localeChangeInterceptor" />
		</property>
	</bean>
</beans>
次に三つのvelocityのテンプレートと属性ファイルの構成である.
#define($content)
	<p>#springMessage("Hello"): $name</p>
	<p>#springMessage("Greetings")</p>
#end
#define($content)
	#springMessage("Hello")
#end
#set($page_title="#springMessage('HelloWorld')")

#define($content)
	#springMessage("HelloWorld")
#end
velocimacro.permissions.allow.inline=true
velocimacro.permissions.allow.inline.to.replace.global=true
velocimacro.permissions.allow.inline.local.scope=true
input.encoding=UTF-8
output.encoding=UTF-8
resource.loader=webapp, class
class.resource.loader.description=Velocity Classpath Resource Loader
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader 
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path=/WEB-INF/velocity/
webapp.resource.loader.cache=false
最後はweb.xmlの設定です.
<?xml version="1.0" encoding="UTF-8"?>
<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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.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>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>springDispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springDispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>
その他の具体的なコードを実現しました.アップロードしました.http://download.csdn.net/detail/johnjobs/7139187mavenの構築が完了したら、tomcatなどの容器に配置し、上記の請求住所を要求します.すなわち、効果のデモンストレーションが見られます.以下は効果のスクリーンショットです.例は簡単です.
springmvc+velocity+ Rest Services(xml,json)实例_第2张图片
springmvc+velocity+ Rest Services(xml,json)实例_第3张图片
springmvc+velocity+ Rest Services(xml,json)实例_第4张图片
springmvc+velocity+ Rest Services(xml,json)实例_第5张图片