【javaEE】(5)SpringBoot Web开发

本文详细介绍了如何使用AJAX实现前后端异步交互,包括新闻数据获取示例,以及解决跨域问题的方法。通过Controller层的@RequestMapping和@ResponseBody,配合HTML中jQuery的ajax调用,展示了前后端分离的现代开发模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:ajax请求页面数据

1:准备工作

(1)Controller层增加
@RequestMapping("getjson")
@ResponseBody
public News getjson(){
    News news = new News();
    news.setTitle("新闻标题");
    news.setContent("新闻内容");
    return news;
}
(2)html页面修改
JavaEE  Spring ajax 3

此时html完整代码如下

test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body onload="getnews()">
<!--一点开就会自动调用-->
<script>
    function getnews(){
        $.ajax({
            type:'post',
            url:'http://localhost:8080/getjson',
            contentType:'application/json',
            success:function (res){
                console.log(res)
                //把数据绑定到页面
                document.getElementById("title").innerHTML = res.title;
                document.getElementById("content").innerHTML = res.content;

            }
        })
    }
</script>

<h1 th:text="${message}">hello world</h1>
<h2>这是一个html文件</h2>

<div id="title">title</div>
<div id="content">content</div>
<button onclick="getnews()">获取新闻</button>


<!--<div th:each="news:${newsList}">-->
<!--&lt;!&ndash;    取别名 给newsList取名为news&ndash;&gt;-->
<!--    <div th:text="${news.title}"></div>-->
<!--    <div th:text="${news.content}"></div>-->
<!--</div>-->

</body>
</html>

2:ajax和常规方法访问的区别

最主要的区别是访问的 先后顺序

(1)常规方法进行访问

浏览器会先访问Controller层,然后Controller层处理后把数据传给Web层并填充好返回html给浏览器

JavaEE ajax 前后端分离1
(2)ajax方法进行访问

使用ajax方法访问会先获得html页面的静态资源放回给浏览器,然后再访问Controller层获得数据进行填充。

JavaEE ajax 前后端分离2

ajax这种工作方式使得前后端分离,被称为 前后端分离技术 前端和后台可以存在于 不同的服务器

也是目前主流的工作模式。

但这种工作方式会出现Access-Control-Allow-Origin的问题(跨域问题)

就是访问后台时,服务器发现域名不一致(不同的服务器),禁止访问里面的方法来获得数据,所以浏览器只会得到静态页面而不会获得数据。

解决方法是在Controller层添加注解,解除跨域的限制

JavaEE ajax 前后端分离3

然后就可以跨域进行访问了

(3)ajaxa实际案例

在Controller层添加语句

@RequestMapping("commit")
@ResponseBody
public Map<String,Object> commit(String username, String password){
    System.out.println("username");
    System.out.println("password");
    Map<String,Object>result = new HashMap<>();
    if(username.equals("admin")&&password.equals("123456")){
        result.put("code",0);
    }else {
        result.put("code",-1);
        result.put("msg","登陆失败");
    }
    return result;
}

编写html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body">
<!--一点开就会自动调用-->
<script>
    function getnews(){
        $.ajax({
            type:'post',
            url:'http://localhost:8080/commit',
			data:$('form').serialize(),
            // contentType:'application/json',
            success:function (res){
                console.log(res)
				if(res.code == 0){
					window.location.href = 'success.html'
				}else{
					window.location.href = 'fail.html'
				}
            }
        })
    }
</script>

<form id="form" action="##" onsubmit="return false" method="post">
	<div>用户名:<input name="username"/></div>
	<div>密码:<input name="password"/></div>
	<div><input type="submit" value="提交" onclick="getnews()"/></div>
</form>
</body>
</html>

success.html和fail.html自行编写,只是用来做显示而已。

### JavaEE项目中使用Spring Boot的教程和资源 #### 使用Spring Boot构建JavaEE应用的优势 在Maven项目中集成Spring Boot的最佳实践是从`spring-boot-starter-parent`项目继承并声明依赖于Spring Boot启动器。这使得项目能够重用Spring Boot的默认设置,简化开发流程[^1]。 #### 创建基于Spring Boot的Web应用程序 对于希望快速搭建具有图形界面的应用程序开发者来说,可以参考一个关于如何利用PrimeFaces框架创建Spring Web MVC应用程序的教学指南[^2]。此教程不仅涵盖了基础架构的建立还涉及前端组件的选择与运用。 #### 应用程序入口配置解析 当深入研究Spring Boot项目的初始化过程时,会发现`@SpringBootApplication`注解扮演着至关重要的角色。它内部包含了几个核心组成部分用于完成自动化的包导入以及整体环境设定等工作[^3]。 #### 支持多种类型的企业级服务实现 除了微服务之外,Spring Boot同样适用于传统单体结构下的企业解决方案建设。例如通过整合JSF(JavaServer Faces),可以轻松实现在保留原有技术栈的同时引入现代化特性支持的能力[^4]。 #### SOAP协议的支持方式介绍 针对特定场景下需要处理SOAP消息的情况,在Spring Boot中有专门的设计模式来应对这类需求。不同于RESTful API依靠URL路径匹配请求的方法,这里采用的是依据XML文档中的命名空间URI及本地部分来进行路由决策的方式[@PayloadRoot][^5]. ```java // 示例代码片段展示了一个简单的Spring Boot控制器定义 import org.springframework.web.bind.annotation.RestController; @RestController public class ExampleController { public String helloWorld() { return "Hello from Spring Boot!"; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值