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

前端结果显示:

  控制台信息:

  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值