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;        
    }

前端结果显示:

控制台信息:

相关推荐
码爸2 分钟前
java 执行es中的sql
java·sql·elasticsearch
微尘813 分钟前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
VaporGas15 分钟前
idea集成和使用Git指南
java·git·intellij-idea
计算机学姐20 分钟前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
阿乾之铭37 分钟前
spring MVC 拦截器
java·spring·mvc
码爸40 分钟前
flink 批量写clickhouse
java·clickhouse·flink
djgxfc42 分钟前
简单了解Maven与安装
java·maven
中文很快乐1 小时前
springboot结合p6spy进行SQL监控
java·数据库·sql
丶白泽1 小时前
重修设计模式-概览
java·设计模式
小电玩1 小时前
谈谈你对Spring的理解
java·数据库·spring