首页 > 代码库 > JavaEE 之 RESTful

JavaEE 之 RESTful

1.RESTful

  a.定义:一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

  b.四种方式:

    GET:/blog/1 HTTP GET =>  得到id=1的blog     一般用于读取

    DELETE:/blog/1 HTTP DELETE => 删除id=1的blog  用于删除

    PUT:/blog/1 HTTP PUT =>  更新id=1的blog 用于更新

    POST:/blog   HTTP POST =>  新增BLOG 用于增删改

 

 

2.使用步骤

  a.将myRest中jar包考入

  b.在web.xml中配置

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

  c.在mySpring-servlet.xml中配置

    <mvc:annotation-driven />
    <mvc:resources mapping="/img/**" location="/img/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/html/**" location="/html/" />
    <mvc:default-servlet-handler />    

    以及

    <bean id="myResourceHandler" name="myResourceHandler"
        class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler">
        <property name="locations" value="/" />
        <property name="supportedMethods">
            <list>
                <value>GET</value>
                <value>DELETE</value>
                <value>PUT</value>
                <value>POST</value>
            </list>
        </property>
    </bean>

  d.建SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.wode.bean"/>
    </typeAliases>
</configuration>

  e.在html中

        $("button").bind("click",function(){
            $.ajax({
                   type: "put",
                   url: "../user/update/13",
                   data: {name:"zhangsan",location:"chengdu"},
                   success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
                });
        })

  f.Controller中书写

@RequestMapping("/user")
public class HelloController {
    // http://127.0.0.1:8080/myRestFul/user/update/3
    @RequestMapping(path="/update/{id}",method=RequestMethod.PUT)
    public void upUser(@PathVariable("id")int id,String name,String location,PrintWriter pt){
        //用户的修改
        System.out.println("用户执行了更新"+id+" "+name+" "+location);
        pt.println("hello world");
    }
}

  g.注意:put方式还需在web.xml中配置

  <filter>
      <filter-name>httpPutFormFilter</filter-name>
      <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
  </filter>
   <filter-mapping>
           <filter-name>httpPutFormFilter</filter-name>
           <servlet-name>myRest</servlet-name>
   </filter-mapping>

 

JavaEE 之 RESTful