ajax和springBoot完整的交互过程

1.0 创建项目

        1.1 创建后台springboot项目

        new project 创建一个springboot项目

创建web项目

点击 File -> Project Structure->module->点击+号->选择web-> 选择create Artifact

        1.2 启动springboot项目报错

Process finished with exit code 0

        解决方案 引入web依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

出现问题controller访问web-inf存在的jsp页面报404,网上找了各种解答,都没用,最后随便弄弄都成功了,没找到具体原因,将正确的附在下面

首先添加依赖

     <!-- 添加servlet依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 添加jstl标签库依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

配置文件配置

server:
  port: 8080

spring:
  mvc:
    view:
      suffix: .jsp
      prefix: /WEB-INF/

然后更改配置点击 File -> Project Structure->module->点击+号->选择web 将webapp放到main目录下即可

 项目基本已经搭建完成,开始测试ajax和后台交互!!!以登录界面为例子

2.0 ajax与后台交互测试

       2.1 前台首先导入jquery,前台代码

<%--
  Created by IntelliJ IDEA.
  User: 50373
  Date: 2023/4/3
  Time: 15:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>登录界面</title>
    <script src="../static/js/jquery-1.7.2.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        $(function () {
            var btn = $("#flush");
            btn.click(function () {
                $.ajax({
                    url: '/user/getCode',
                    type:'get',
                    data:'id=1',  //字符串
                    dataType:'text',
                    success:function (data) {
                        console.log(data);
                        alert("后台验证码:" + data);
                    }
                })
            })
        })
        $(function (){
            var userLogin = $("#login");
            userLogin.click(function () {
                $.ajax({
                    url: "/user/login",
                    type: "POST",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify({
                        'username': $("#username").val(),
                        'password': $("#password").val()
                    }),
                    dataType: 'json',
                    success: function (data) {
      /*                  if (data.code == "100") {
                            //登录成功,则跳转到成绩查询页面
                            window.location.href = "/suda/searchById/" + data.result;
                        } else {
                            //登录失败,则给出提示信息
                            var msg = $("#btn");
                            msg.after("<br><br><span style='color:red;'>提示:" + data.result + "</span>")
                        }*/
                        console.log(data)
                    }
                })
            })
            }

        )
    </script>

</head>
<body>
<div style="text-align: center;">
    <h2>用户登录</h2>
    <form>
        用户名:<input type="text" name="username" id="username"><br>
        密&emsp;码:<input type="password" name="password" id="password"><br>
        验证码:<input type="text" name="code"><br><br>
        <input type="button" id="login" value="登录">&emsp;<input type="button" id="flush" value="获取验证码">
    </form>
    </div>

</body>

<script type="text/javascript">

</script>
</html>

2.2 springboot后台接收请求并进行处理

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user){
        System.out.println(user);
        return user.toString();
    }
    //SpringBoot接收ajax请求的方式
    //方式一:使用HttpServletRequest request接收请求参数
    @GetMapping("/getCode")
    @ResponseBody
    public String getCode(HttpServletRequest request){
        String id = request.getParameter("id");
        System.out.println("AJAX传递的参数:" + id);
        //获取5位验证码
        return randomCodes();
    }

    public String randomCodes(){
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder code=new StringBuilder(5);
        for(int i=0;i<5;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            code.append(ch);
        }
        return code.toString();
    }
}

2.3 使用restfull风格需要导入mybatis依赖

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2.4 遇到的问题,请求的user数据为null

        2.4.1 没有输入数据,是浏览器保存之前的数据

        2.4.2 ajax 要携带  contentType: "application/json;charset=UTF-8"

        2.4.3 参数使用@RequestBody

之后就可以使用ajax请求与springboot交互了。

下一篇写拦截器相关的,尝试去自己走一遍代码,写一下看看能不能写出来,之前完全没有自己写过拦截器都是跟着视频,这次自己写一下,然后记录一下博客写的过程。


                
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值