学习spring ,3.0有新的变化,以前只用XML作为配置文件,现在还有标记了,这个实在是方便不少.谢谢aegeanmoon的提示,查了一下springMVC,支持Rest。这里用到springMVC,不过这个以前没有用过,以前只用过strutst2. 好吧,建立如下的项目结构.
1.???????? 文件结构
?
?用springMVC的时候会涉及到很多支持spring的包,如果不引入来会出现大量的错误。这个包会在spring的project的ant之类的文件中找到。
2.???????? 写第一个配置文件web.xml,没有配置spring
的公共容器,只用servlet.
?<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.???????? 在默认的路径下写rest-servlet.xml
文件(图所示的路径)?
?4.???????? 写一个TestSimpleControl.java作为MVC
中的Controller.
?package com.lr;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
@Controller
@RequestMapping("/test")
public class TestSimpleControl {
// /test/index/对应的处理
@RequestMapping("/index")
public String index(HttpServletRequest request, HttpServletResponse response) {
// response,request会自动传进来
request.setAttribute("message","REST:index page , no input id!");
return "index";
}
// 根据ID获取不同的内容,通过@PathVariable 获得属性
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String get(@PathVariable("id") String id, HttpServletRequest request,
HttpServletResponse response) throws IOException {
request.setAttribute("message","REST:input ID is "+ id + "");
return "index";
}
//{}用了占位符,这个用于Ajax中的异步请求
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public void testAjax(@PathVariable("id") String id,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().write("ID is " + id);
}
}
5.???????? 测试1:输入-----http://localhost:8080/TestRest/test/index
?
?
6.???????? 测试2:输入------http://localhost:8080/TestRest/test/118
7.???????? 测试3:输入------http://localhost:8080/TestRest/responseAjax.jsp
?
?
?