SpringMVC3.0+rest小例子
先看web.xml配置
<!-- 像js,css,gif等静态文件,需要配置为默认的servlet -->
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> <!-- url配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问。如配为*.do,则不影响静态文件的访问 --> </servlet-mapping>
<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" xsi:schemaLocation="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"> <!-- 自动扫描bean,把作了注解的类转换为bean --> <context:component-scan base-package="com.mvc.rest" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> <bean id="multipartResolver" p:defaultEncoding="utf-8" /> </beans>
package com.mvc.rest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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.servlet.ModelAndView;@Controllerpublic class RestController { public RestController(){ } @RequestMapping(value = "/login/{user}", method = RequestMethod.GET) public ModelAndView myMethod(HttpServletRequest request, HttpServletResponse response, @PathVariable("user") String user, ModelMap modelMap) throws Exception { modelMap.put("loginUser", user); return new ModelAndView("/login/hello", modelMap); } @RequestMapping(value = "/welcome", method = RequestMethod.GET) public String registPost() { return "/welcome"; } }<html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK"><title>Insert title here</title></head><body>欢迎</body></html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK"><title>Insert title here</title></head><body>你好:<%=request.getAttribute("loginUser") %></body></html>