【设计风格】-Restful

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010785685/article/details/51547327

什么是restful?

Rest是设计风格而不是标准,只提供了一组设计原则和约束条件

资源由URI来指定(URI:统一资源标识符)

对资源的包括包括获取、创建、修改、和删除资源

这些操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法

通过操作资源的表现形式来操作资源

简单来说:

非rest风格url: http://..../queryUsers.action?id=001&type=T01

Rest风格url:http://..../localhost:8080/lk-dubbo-consumer-client/user/1

Rest风格特点:简洁、有层次、易于实现缓存等机制。

接下来介绍springmvc中增加restful编码风格的demo.

服务端如何编写restful风格API?

web.xml中的配置:
 <!--配置中央控制器  -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--所有访问的地址都由DispatcherServlet进行解析  -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
springmvc.xml中的配置:
	<!-- 注解扫描 -->
	<mvc:annotation-driven />

	<!-- 配置controller扫描 -->
	<context:component-scan base-package="com.tgb.lk.consumer.controller" />


	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/WEB-INF/"></property>
		<!-- 后缀 -->
		<property name="suffix" value=".jsp"></property>
	</bean>

Controller中方法的写法:

GET

/blog/1

得到id=1blog

DELETE

/blog/1

删除id=1blog

PUT

/bolg/1

更新id=1blog

POST

/bolg

新增blog

(@RequestMapping:用来处理请求地址映射的注解,可用于类或者方法上)

查询列表:

@RequestMapping(method=RequestMethod.GET)
根据ID查询:

@RequestMapping(method=RequestMethod.GET,value="{id}")
根据删除:
@RequestMapping(method=RequestMethod.DELETE,value="{id}")
添加:

@RequestMapping(method=RequestMethod.POST)
修改:

@RequestMapping(method=RequestMethod.PUT)

restful用的还比较浅,后面继续深入学习和使用。



猜你喜欢

转载自blog.csdn.net/u010785685/article/details/51547327