美文网首页
Java-springmvc对RESTful支持

Java-springmvc对RESTful支持

作者: 王子也寂寞 | 来源:发表于2017-10-21 22:18 被阅读0次

RESTful(即RepresentationalStateTransfer的缩写)其实是对http的很好的诠释.

1.对url进行规范,写RESTful格式的url.

2.hhttp的方法规范.

3.对http的contentType规范

请求时指定contentType,要json数据,设置成json格式的type

4.其他细节:

  • 使用URL模板映射:
@RequestMapping("/itemsView/{id}/{type}")
    public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id, @PathVariable("type" ) String abc) throws Exception {
        //调用service查询商品信息
        ItemsCustom itemsCustom = itemsService.findItemsById(id);
        return itemsCustom;
    }
  • 配置RESTful风格的前端控制器:
<!--springmvcRESTful风格的前端控制器-->
  <servlet>
    <servlet-name>springmvc_RESTful</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>springmvc_RESTful</servlet-name>
    <!--第一种:*.action,访问以.action结尾由DispatchServlet进行解析
    第二种:/,所有访问地址都由DispatcherServlet进行解析,
    对于静态文件的解析需要配置不让DispatcherServlet进行解析,
    使用此种方式可以实现RESTful风格的url
    第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然由DispatcherServlet解析,会出问题-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

注意:配置前端控制器的rul-patten中指定"/"的时候,对静态资源的解析出现问题.这时候需要在springmvc.xml文件中添加静态资源的解析方法.

<!--静态资源的解析
    包括:js,css,img...-->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/img/**" location="/img/"/>

相关文章

网友评论

      本文标题:Java-springmvc对RESTful支持

      本文链接:https://www.haomeiwen.com/subject/iyjwuxtx.html