笔记:
RESTful 风格的 webservice 越来越流行了, sun 也推出了 RESTful WebService 的官方规范: JAX-RS ,全称:
Java API for RESTful WebService。该规范定义了一系列的注解
RESTful 简化了 web service 的设计,它不再需要 wsdl ,也不再需要 soap 协议,
而是通过最简单的 http 协议传输数据 ( 包括 xml 或 json) 。
既简化了设计,也减少了网络传输量(因为只传输代表数据的 xml 或 json ,没有额外的 xml 包装)。
REST(Representational State Transfer-表现层状态转化)是一种新的软件架构风格,
它以资源(resource)为核心,使用 HTTP、 URI、XML 以及 HTML 等流行协议和标准来完成对资源的操作及显示。
这些操作包括获取、创建、修改和删除资源(CRUD),分别对应于 HTTP 协议的 GET、POST、PUT 和 DELETE 方法。
RESTful架构可以总结为以下三个内容:
(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”。
对应数据库的操作, 有以下请求
GET用来获取资源,
POST用来新建资源(也可以用于更新资源),
PUT用来更新资源,
DELETE用来删除资源。
注释(Annotation):
在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。
@Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。
@GET:这意味着以下方法可以响应 HTTP GET 方法。
@Produces:以纯文本方式定义响应内容 MIME 类型。
@Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。
@Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。
@PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。
@Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。
使用SpringMVC Restful风格搭建web项目:
服务器端配置文件:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<!-- mvc标签配置handlermapping,handlerAdapter -->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 扫描包Controller -->
<context:component-scan base-package="com.ssm.controller"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.ssm.utils.DateConverter" />
</list>
</property>
</bean>
<bean class="com.ssm.utils.UserExceptionResolver"></bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Day1101_SSMPro</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
</web-app>
服务端配置文件:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- mvc标签配置handlermapping,handlerAdapter -->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 扫描包Controller和实现类 -->
<context:component-scan base-package="com.cxf.controller,com.cxf.service.impl"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
//spring访问服务的客户端组件
<bean id="restTemlate" class="org.springframework.web.client.RestTemplate"></bean>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.cxf.utils.DateConverter" />
</list>
</property>
</bean>
</beans>
客户端service、
public interface AuctionService {
List<Auction> findAllAuction(Auction auction);
Auction findAucById(int aid);
public void addAuction(Auction auction);
// public void updateAuction(Auction auction);
public void deleteAuctionById(int id);
void update2Auction(Auction auction);
}
客户端实现类
@Service
public class AuctionServiceImpl implements AuctionService {
@Autowired
private RestTemplate restTemplate;
@Override
public List<Auction> findAllAuction(Auction auction) {
return restTemplate.getForObject("http://localhost:8080/Day1101_SSMPro/rest/loadAllAuction",List.class);
}
@Override
public Auction findAucById(int aid) {
return restTemplate.getForObject("http://localhost:8080/Day1101_SSMPro/rest/findAuctionById/"+aid,Auction.class);
}
@Override
public void addAuction(Auction auction) {
restTemplate.postForObject("http://localhost:8080/Day1101_SSMPro/rest/addAuction?method=post",auction,void.class);
}
@Override
public void update2Auction(Auction auction) {
restTemplate.put("http://localhost:8080/Day1101_SSMPro/rest/addAuction?method=put",auction,Auction.class);
}
/* @Override
public void updateAuction(Auction auction) {
restTemplate.put("http://localhost:8080/Day1101_SSMPro/rest/updateAuction",auction);
}
*/
@Override
public void deleteAuctionById(int id) {
restTemplate.delete("http://localhost:8080/Day1101_SSMPro/rest/deleteAuction/"+id);
}
}
客户端controller
@RestController
@RequestMapping("/auction")
public class AuctionController {
@Autowired
private AuctionService auctionService;
@RequestMapping("/findAllAuction")
public List<Auction> findAllAuction(){
return auctionService.findAllAuction(new Auction());
}
@RequestMapping("/getAuctionById/{auctionid}")
public Auction getAuctionById(@PathVariable int auctionid){
return auctionService.findAucById(auctionid);
}
/* @RequestMapping("/updateAuction/{id}")
public void updateAuction(@PathVariable int id){
Auction auction = auctionService.findAucById(id);
auction.setAuctionname("json修改的商品");
auctionService.updateAuction(auction);
}*/
@RequestMapping(value = "/addAuction")
public void addAuction (){
Auction auction1 = new Auction();
auction1.setAuctionid(25);
auction1.setAuctionname("json添加的商品");
auction1.setAuctionstartprice(1000D);
auction1.setAuctionupset(500D);
auction1.setAuctionstarttime(new Date());
auction1.setAuctionendtime(new Date());
auction1.setAuctiondesc("use json add Auction");
auctionService.addAuction(auction1);
}
@RequestMapping("/updateAuction/{id}")
public void update2Auction(@PathVariable int id){
Auction auction = auctionService.findAucById(id);
auction.setAuctionname("json修改的商品");
auctionService.update2Auction(auction);
}
@RequestMapping("/deleteAuction/{id}")
public void deleteAuction(@PathVariable int id){
auctionService.deleteAuctionById(id);
}
}
客户端通过restTemplate可以设定提交到服务端的请求的提交方式,同一个请求地址可以处理不同的业务,通过设定提交方式让服务器加以区分,这里客户端的添加和修改用户就用同一个用户请求(/addAuction)区别仅仅是restTemplate后面的提交方式,put修改,post是新增,客户端控制器接受参数要把json对象转成相应格式所以入参处使用@PathVariable注解,客户端和服务端传递数据是json形式的所以服务端接收客户端发来的json也要通过注解@RestController转成相应格式:
@RestController
@RequestMapping("/rest")
public class RestfulController {
@Autowired
AuctionService auctionService;
@RequestMapping("/loadAllAuction")
public List<Auction> loadAllAuction(){
return auctionService.findAllAuction(new Auction());
}
@RequestMapping("/findAuctionById/{auctionid}")
public Auction findAuctionById(@PathVariable int auctionid) {
return auctionService.findAucById(auctionid);
}
@RequestMapping(value="/addAuction",method=RequestMethod.POST)
public void addAuction(@RequestBody Auction auction) {
auctionService.addAuction(auction);
}
@RequestMapping(value="/addAuction",method=RequestMethod.PUT)
public void update2Auction(@RequestBody Auction auction) {
auctionService.updateAuction(auction);
}
@RequestMapping(value="/updateAuction",method=RequestMethod.PUT)
public void updateAuction(@RequestBody Auction auction) {
auctionService.updateAuction(auction);
}
@RequestMapping("/deleteAuction/{id}")
public void deleteAuction(@PathVariable int id) {
auctionService.deleteSingleAuc(id);
}
}
这里服务端指定了method后面的.PUT或.POST是指接收的请求方式,也就是说如果写.PUT就只能接收客户端的PUT请求,用这种方式作区分,当客户端请求同一个服务url时,可用接收的请求方式加以区分,这里添加和修改都是用addAuction,区别是服务端的method定义方式,也就是说客户端访问在url后时加一个‘?method=post’,服务端就会执行添加方法,如果客户端请求的url是?method=put,服务端就执行修改方法。