restful请求风格的增删改查-----查询and添加

一、restful风格的介绍

restful也称之为REST ( Representational State Transfer ),可以将它理解为一种软件架构风格或设计风格,而不是一个标准。简单来说,restful风格就是把请求参数变成请求路径的一种风格。例如,传统的URL请求格式为:

http://localhost:8080/chapter14restful/adduser.jsp?id=1

采用restful请求格式后,变为

http://localhost:8080/chapter14restful/adduser.jsp/1

restful风格在HTTP请求中,使用put、delete、 post 和get方式分别对应添加、删除、修改和查询的操作。不过目前国内开发,还是只使用post和get方式来进行增删改查操作。
 

二、准备工作:

使用软件:eclipse。

正确创建实体类,并创建set、get、tostring、有/无参构造方法。

了解restful风格在HTTP请求中,使用的put,delete,post,get方式对应增删改查。这一点在前后端相连时,很重要。你请求的Ajax方式对应后端@RequestMapping的方式。

三、查询:

前端:

<%@ page language="java" contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"%>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>restful测试</title>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8">
<link rel="stylesheet" href="${pageContext.request.contextPath }/js/bootstrap-4.6.2-dist/css/bootstrap.min.css">
<script src="${pageContext.request.contextPath }/js/jquery-3.5.1/jquery-3.5.1.min.js"></script>
<script src="${pageContext.request.contextPath }/js/bootstrap-4.6.2-dist/js/bootstrap.bundle.min.js"></script>

<script type="text/javascript">
	function search(){
		//获取输入的用户名和密码
		var id = $("#number").val();
		$.ajax({
			url:"${pageContext.request.contextPath }/user/"+id,
			type:"GET",
			//定义相应的数据格式为Json
			dataType:"json",
			//成功响应结果
			success: function(data){
				 if(data.username!=null){
					 alert("您查询的用户名为:"+data.username);
				 }else{
					 alert("没有找到id为"+id+"的用户")
				 }
			}
		});
		
	}
</script>

</head>
<body>
   <form >
      	编号:<input type="text" name="number" id="number"><br>
        <input type="button" value="查询" class="btn btn-success" onclick="search()"><br>
   </form>
</body>
</html>

后端:

   /*
	*接受Restful风格的请求,其接受方式为get----查询操作
	*/
	@GetMapping(value="/user/{id}")
	@ResponseBody
	public User selectUser(@PathVariable("id") String id) {
		//查看数据接收
		System.out.println("您查询到了id="+id);
		User user = new User();
		//模拟根据id查询到用户对象
		if("1234".equals(id)) {
			user.setUsername("Tom");
		}
		return user;		
	}

前端结果显示:

四、添加:

我的妈,卡了好久,结果超级简单的逻辑,前端获取到的信息我们用一个对象来存,这样我们传给后端时,直接传递这个对象就行,后端接受对象需要用到注解@RequestBody 。

同时要注意@RequestParam 注解来接收参数。这意味着 'id' 参数应该作为 URL 查询参数发送,而不是请求主体中的 JSON 数据。请确保请求的 URL 中包含了合适的查询参数,例如 http://localhost/user?id=123,其中 '123' 是有效的整数值。我采取的是通过请求主体以 JSON 格式发送参数,那么前端代码和后端代码都需要JSON 格式。

前端:

<%@ page language="java" contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"%>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8">
<link rel="stylesheet" href="${pageContext.request.contextPath }/js/bootstrap-4.6.2-dist/css/bootstrap.min.css">
<script src="${pageContext.request.contextPath }/js/jquery-3.5.1/jquery-3.5.1.min.js"></script>
<script src="${pageContext.request.contextPath }/js/bootstrap-4.6.2-dist/js/bootstrap.bundle.min.js"></script>
<title>添加用户页面</title>
<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
</style>

<script type="text/javascript">
function add(){
    //添加对象
    var user = {
            id:parseInt($("#id").val()),
            username:$("#username").val(),
            password:$("#password").val()
    };
    //能正确获取输入框里的元素
    alert("id: " + user.id + ", username: " + user.username + ", password: " + user.password);
    
    $.ajax({
        url:"${pageContext.request.contextPath }/user",
        type:"put",
        //data表示发送的数据,将三个参数绑定到一起
        data:JSON.stringify({ id: user.id, username: user.username, password: user.password }),
        //定义发送请求的数据格式为JSON字符串
        contentType:"application/json;charset=UTF-8",
        //成功响应结果
        success: function(data){
            if(data!=null){
                alert("您成功添加了编号为"+user.id+"的用户")
            }else{
                alert("添加出错了")
            }
        }
    });
}
</script>

</head>
<body>
    <div class="container">
      <form class="form">
              编&nbsp;&nbsp;&nbsp; 号:<input type="text" name="id" id="id"><br>
          用户名:<input type="text" name="username" id="username"><br>
          密&nbsp;&nbsp;&nbsp; 码:<input type="password" name="password" id="password"><br>
        <input type="button" value="添加" class="btn btn-primary" onclick="add()"><br>
      </form>
    </div>
   
</body>
</html>

后端:

    /*
    * 接受Restful风格的请求,其接受方式为put----添加操作
    */
    @PutMapping(value="/user")
    @ResponseBody
    public User addUser(@RequestBody User user) 
    {
        Integer id = user.getId();
        String username = user.getUsername();
        String password = user.getPassword();
        //查看数据接收
        System.out.println("成功添加了id="+id+",username="+username+",password"+password+"的用户");
        //创建新用户
        
        return user;        
    }

前端结果显示:

  控制台信息:

相关推荐

  1. rest_framework_mongoengine实现后端增删

    2024-04-26 10:44:03       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 10:44:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 10:44:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 10:44:03       82 阅读
  4. Python语言-面向对象

    2024-04-26 10:44:03       91 阅读

热门阅读

  1. 理解彩虹攻击:颜色缤纷的威胁

    2024-04-26 10:44:03       32 阅读
  2. hanoi塔

    hanoi塔

    2024-04-26 10:44:03      42 阅读
  3. 市场投放用户获取方面如何做数据分析

    2024-04-26 10:44:03       34 阅读
  4. Cache缓存

    2024-04-26 10:44:03       32 阅读
  5. C语言——const

    2024-04-26 10:44:03       29 阅读
  6. Python类方法装饰器

    2024-04-26 10:44:03       34 阅读
  7. 若依-禁用本地定时任务

    2024-04-26 10:44:03       40 阅读
  8. HTML中datalist的用法

    2024-04-26 10:44:03       30 阅读
  9. 2014NOIP普及组真题 2. 比例简化

    2024-04-26 10:44:03       28 阅读
  10. 采用状态转移矩阵方式的快速哈夫曼解码算法

    2024-04-26 10:44:03       33 阅读
  11. 【QT进阶】Qt线程与并发之QtConcurrent的简单介绍

    2024-04-26 10:44:03       40 阅读