spring mvc(简单搭建restful Web Service)

pojo

   User.java

package pojo;

public class User {
	private String name;
	private String birthday;
	
	public User(){}
	
	public User(String name, String birthday) {
		this.name = name;
		this.birthday = birthday;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	
}

 service 

    DisplayService.java

package service;

import org.springframework.stereotype.Service;

import pojo.User;

@Service("displayService")
public interface DisplayService {
	public String getHelloWorld();
	
	public int getRandomNumber();
	
	public User getUser();
}

    DisplayServiceImpl.java

package service.impl;

import java.util.Random;

import org.springframework.stereotype.Service;

import pojo.User;
import service.DisplayService;

@Service("displayService")
public class DisplayServiceImpl implements DisplayService{

	@Override
	public String getHelloWorld() {
		return "Hello World, Spring 3.0!";
	}

	@Override
	public int getRandomNumber() {
		Random random = new Random();
		return random.nextInt(100);
	}

	@Override
	public User getUser() {
		User user = new User("孝","2000-01-01");
		return user;
	}

}

controller

    DisplayController.java

package web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import pojo.User;
import service.DisplayService;

@Controller
public class DisplayController {
	private Logger logger = Logger.getLogger(DisplayController.class.getName());
	
	@Autowired
	private DisplayService displayService;
	
	
	@RequestMapping("display")
	public ModelAndView helloWorld() {
		String message = displayService.getHelloWorld();
		logger.info(message);
		return new ModelAndView("display", "message", message);
	}
	
	@RequestMapping(value="display/random")
	public @ResponseBody String displayJson() throws Exception{
		int randomValue = displayService.getRandomNumber();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("随机数", randomValue);
		ObjectMapper objectMapper = new ObjectMapper();  
		String result = objectMapper.writeValueAsString(map);  
		return result;
	}
	
	@RequestMapping(value="display/user",produces={"application/json;charset=UTF-8"})
	public @ResponseBody List<User> displayUser(HttpServletResponse response) throws Exception{
		User user = displayService.getUser();
		List<User> users = new ArrayList<User>();
		users.add(user);
		return users; 
	}
	
}

spring 配置 app-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"  
       xmlns:context="http://www.springframework.org/schema/context"  
       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-3.1.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.1.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">  
	<context:component-scan base-package="web.controller" />
	
	<context:component-scan base-package="service" />
	
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter" />
                <ref bean="jsonHttpMessageConverter" />
            </list>
        </property>
    </bean>

	<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/plain;charset=UTF-8</value>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean> 

	<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
	
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

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">
	<display-name>Spring3MVC</display-name>

	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:app-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>


	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

 

maven 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>SpringMVC</groupId>
	<artifactId>SpringMVC</artifactId>
	<packaging>jar</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVC</name>
	<url>http://maven.apache.org</url>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
		</dependency>
	</dependencies>


</project>

相关推荐