发表于: 2017-06-15 23:10:19

1 1092


今天完成的事情:

什么是rest

全称:表述性状态转移 (Representational State Transfer), 将资源的状态以最适合客户端或服务端的形式从服务器端转移到客户端(或者反过来)。

面向资源,而不是面向行为

资源通过URL进行识别和定位,

一般URL中都使用名词,不使用动词

对资源采取的行为使用HTTP方法来定义,如GET, POST, DELETE, PUT等,这样可以在前后台分离式的开发中使得前端开发人员不会对请求的资源地址产生混淆和大量的检查方法名的麻烦,形成一个统一的接口。

在Rest中,现有规定如下:

GET(SELECT):从服务器查询,可以在服务器通过请求的参数区分查询的方式。

POST(CREATE):在服务器新建一个资源,调用insert操作。

PUT(UPDATE):在服务器更新资源,调用update操作。

DELETE(DELETE):从服务器删除资源,调用delete语句。

了解这个风格定义以后,我们举个例子:

如果当前url是 http://localhost:8080/User

那么用户只要请求这样同一个URL就可以实现不同的增删改查操作,例如

http://localhost:8080/User?_method=get&id=1001  这样就可以通过get请求获取到数据库 user 表里面 id=1001 的用户信息

http://localhost:8080/User?_method=post&id=1001&name=zhangsan  这样可以向数据库 user 表里面插入一条记录

http://localhost:8080/User?_method=put&id=1001&name=lisi  这样可以将 user表里面 id=1001 的用户名改为lisi

http://localhost:8080/User?_method=delete&id=1001  这样用于将数据库 user 表里面的id=1001 的信息删除

这样定义的规范我们就可以称之为restAPI接口,我们可以通过同一个url来实现各种操作。


添加pojo对象

package me.wyc.springmvc.domain;

public class Message {

String name;
   String text;

   public Message(String name, String text) {
this.name = name;
       this.text = text;
   }

public String getName() {
return name;
   }

public String getText() {
return text;
   }

}

添加控制器

package me.wyc.springmvc.controller;

       import org.springframework.web.bind.annotation.PathVariable;
       import org.springframework.web.bind.annotation.RequestMapping;
       import org.springframework.web.bind.annotation.RestController;

       import com.yiibai.springmvc.domain.Message;

@RestController
public class HelloWorldRestController {

   @RequestMapping("/hello/{player}")
public Message message(@PathVariable String player) {

       Message msg = new Message(player, "Hello " + player);
       return msg;
   }

添加配置类

package me.wyc.springmvc.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

   @Configuration
@EnableWebMvc
@ComponentScan(basePackages = "me.wyc.springmvc")
public class HelloWorldConfiguration {

添加初始化类

package me.wyc.springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

   public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloWorldConfiguration.class };
       }

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
       }

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
       }

}

明天计划的事情:完成测试

遇到的问题:json什么的并不会用

收获:了解什么是REST



返回列表 返回列表
评论

    分享到