RESTful风格、异常处理、Spring框架

1.RESTful风格

  1. 什么是RESTful风格?

    • REST是REpressentational State Transfer的缩写,中文翻译为表述性状态转移,REST是一种体系结构,而HTTP是一种包含了REST架构属性的协议,为了便于理解,我们把它的首字母拆分成不同的几个部分:

      • 表述性(REpressentational):REST资源实际上可以用各种形式来进行表述,包括XML、JSON、甚至HTML——最适合资源使用者的任意形式;
      • 状态(State):当时用REST的时候,我们更关注资源的状态而不是对资源采取的行为;
      • 转义(Transfer):REST涉及到转义资源数据,它以某种表述性形式从一个应用转移到另一个应用

    简单的说,REST就是将资源的状态以适合客户端或服务端的形式从服务端转移到客户端(或者反过来)。在REST中,资源通过URL进行识别和定位,然后通过行为(即HTTP方法)来定义REST来完成怎样的功能。

  2. 实例说明
    1. 在平时Web开发中,表单中method属性常用的值是GET和POST,但是实际上,HTTP方法还有PATCH、DELETE、PUT等其他值,这些方法通常会匹配如下的CRUD动作:

      CRUD动作 HTTP方法
      Create(增) POST
      Select(查) GET
      Update(改) PUT或PATCH
      Delete(删) DELETE

      在使用RESTful风格之前,我们增加一条商品数据是这样的:
      /addProduct?name=xxx
      但是使用了RESTful风格之后就会变成:

      /product

      这就变成了使用同一个URL,通过约定不同的HTTP方法来实施不同的业务,这就是RESTful风格所做的事

用户User的实体类

package com.alibaba.wlq.bean;

public class User {
    @Override
    public String toString() {
        return "User [account=" + account + ", password=" + password + ", phone=" + phone + "]";
    }

    private String account;
    private String password;
    private String phone;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public User(String account, String password, String phone) {
        super();
        this.account = account;
        this.password = password;
        this.phone = phone;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(String account, String password) {
        super();
        this.account = account;
        this.password = password;
    }

    public User() {
        super();
    }

}

Controller控制类

package com.alibaba.wlq.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.wlq.bean.User;
@Controller
@RequestMapping("user")
public class UserController {
    //RESTful--->user/1
    //method:表示该方法处理get请求
    //1赋值给了{uid}了
    @RequestMapping(value="{uid}",method=RequestMethod.GET)//查询操作
    public String selectById(@PathVariable("uid")int id) {//@PathVariable:把uid的值赋值给形参id
        System.out.println("id====="+id);
        return "index";
    }
    @RequestMapping(value="{uid}",method=RequestMethod.POST)//添加操作
    public String addUser(@PathVariable("uid")int id,User user) {
        System.out.println(user);
        System.out.println("id====="+id);
        return "index";
    }
    //SpringMVC提供了一个过滤器,该过滤器可以把post请求转化为put和delete请求
    @RequestMapping(method=RequestMethod.PUT)//修改操作
    @ResponseBody
    public String updateUser(User user) {
        System.out.println(user+"======update");
        return "index";
    }
    @RequestMapping(value="{id}",method=RequestMethod.DELETE)//删除操作
    @ResponseBody
    public String deleteById(@PathVariable int id) {
        System.out.println(id+"=====delete");
        return "index";
    }
}

在web.xml配置文件中配置过滤器

<!-- 把post请求转化为put和delete请求
    使用_method表示真正的提交方式 -->
<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

index界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/9.5springmvcdemo/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $.ajax({
        url:"../user",
        type:"POST",
        data:{
            _method:"PUT",
            "account":"zhangsan",
            "password":"123456",
            "phone":"18360917652"
        },
        success:function(result){
            alert(result);
        }
    });

</script>
</head>
<body>
index界面
</body>
</html>

2.异常处理

  1. 全局异常处理

    package com.alibaba.wlq.controller;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    @ControllerAdvice
    public class ExceptionController {
     @ExceptionHandler
     public ModelAndView error(Exception exception) {
         ModelAndView mv = new  ModelAndView();
         mv.addObject("error",exception.getMessage());
         mv.setViewName("error");
         return mv;
     }
    }

3.Spring框架

Spring是一个开源框架

  1. 加入jar包
  2. 加入配置文件

原文地址:https://www.cnblogs.com/wuliqqq/p/11470321.html

时间: 2024-08-30 09:50:40

RESTful风格、异常处理、Spring框架的相关文章

RESTful风格的SSM框架搭建

1 使用idea编辑工具,maven项目构建工具搭建RESTful风格的java项目 2 进行项目配置 2.1 pom文件依赖 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

spring boot 2 全局统一返回RESTful风格数据、统一异常处理

全局统一返回RESTful风格数据,主要是实现ResponseBodyAdvice接口的方法,对返回值在输出之前进行修改.使用注解@RestControllerAdvice拦截异常并统一处理. 开发环境:IntelliJ IDEA 2019.2.2jdk1.8Spring Boot 2.2.2 1.创建一个SpringBoot项目,pom.xml引用的依赖包如下 <dependency> <groupId>org.springframework.boot</groupId&g

RESTful风格的Web服务框架:Swagger

Swagger与SpringMVC项目整合 为了方便的管理项目中API接口,在网上找了好多关于API接口管理的资料,感觉目前最流行的莫过于Swagger了,功能强大,UI界面漂亮,并且支持在线测试等等,所以本人仔细研究了下Swagger的使用,下面就如何将Swagger与个人的SpringMVC项目进行整合做详细说明: 最终API管理界面:  详细步骤: Step1:项目中引入相关jar包: <properties> <project.build.sourceEncoding>UT

Spring MVC RESTful风格URL welcome-file-list不起作用问题解决

[Spring框架]<mvc:default-servlet-handler/>的作用 优雅REST风格的资源URL不希望带 .html 或 .do 等后缀.由于早期的Spring MVC不能很好地处理静态资源,所以在web.xml中配置DispatcherServlet的请求映射,往往使用 *.do . *.xhtml等方式.这就决定了请求URL必须是一个带后缀的URL,而无法采用真正的REST风格的URL. 如果将DispatcherServlet请求映射配置为"/",

基于restful风格的maven项目实践(融合spring)

我们我们经常在老式的项目开发过程中,遇到找java包的问题:甚至有时候一找一天就过去了.maven 是我们开发工程师的福音,它可以根据我们的配置自动的下载并加装到我们的工程中,并在发布的时候同时发布对应的Java包.这样大大提高了我们的工作效率,更有时间学习前沿的技术. 什么是maven? maven是专用于进行项目的配置管理工作:用maven创建的项目中必须包括一个pom.xml文件,用于设置依赖关系.项目的基本配置(grouId,artifactId,version等),编译项目时用插件.环

springboot集成spring security实现restful风格的登录认证 附代码

一.文章简介 本文简要介绍了spring security的基本原理和实现,并基于springboot整合了spring security实现了基于数据库管理的用户的登录和登出,登录过程实现了验证码的校验功能. 完整代码地址:https://github.com/Dreamshf/spring-security.git 二.spring security框架简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.主要包括:用户认证

Spring Boot 中 10 行代码构建 RESTful 风格应用

RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 RESTful 提供了很好的支持,常见的相关注解有: @RestController @GetMapping @PutMapping @PostMapping @DeleteMapping @ResponseBody ... 这些注解都是和 RESTful 相关的,在移动互联网中,RESTful 得

三、Spring MVC之Restful风格的实现

先抛论点:我觉得Restful风格仅仅是一种风格,并不是什么高深的技术架构,而是一种编程的规范.在我们进行应用程序开发的过程中,我们可以发现,80%以上的操作都是增删查改式的操作,restful就是定义了CRUD的开发规范.下面把restful风格的url和传统风格的url进行一个对比. 业务操作 传统风格URL 传统请求方式 restful风格URL restful请求方式 新增 /add GET/POST /order POST 修改 /update?id=1 GET/POST /order

让python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE等请求

这两天在用python的bottle框架开发后台管理系统,接口约定使用RESTful风格请求,前端使用jquery ajax与接口进行交互,使用POST与GET请求时都正常,而Request Method使用PUT或DELETE请求时,直接爆“HTTP Error 405: Method Not Allowed”错误.而ajax提交的Request Method值DELETE也变成了OPTIONS了. 度娘了好多答案,要么说是浏览器不支持,要么说自己重新封装jquery,还有其他的一些方法...