springboot与jsp或html交互数据

1. 新建一个springboot项目, 然后next, 改一改项目名, 然后next就好, 勾选web依赖.

2. 建好项目后springboot自带tomcat: 8080, 且取消了web.xml, 所以web项目直接启动springboot引导类然后开启服务.

3. 在resources下新建application.yml, 端口自己可以改, web视图的配置.

#服务器端口号
server.port=8081
#当前web名称
server.servlet.context-path=/

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

4. 新建controller包,然后写一个controller类

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String home(){
        System.out.println("123");
        return "hello";
    }
}

5. 创建jsp或html目录, html创建在resources下,static存放样式文件, templates存放html文件. webapp下存的是jsp文件.   (都需要添加依赖)

6. Pom文件依赖, 只能返回一种视图模式,两种依赖都添加会冲突,具体原因自己搜

<!--返回html的maven依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


<!--返回jsp的依赖,与html的相冲-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <version>8.5.45</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

7. 返回jsp页面, 只需要配置yml, 然后return jsp名字

8. 返回html页面, 用th表达式

@RequestMapping("/action")
public String index(Model model){
    System.out.println("action");
    model.addAttribute("aaa", "ok?");
    model.addAttribute("bbb", "ok");
    return "ccc.html";
}

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>测试: <span th:text="${aaa}"></span></p>
<p>响应测试: <span th:text="${bbb}"></span></p>
</body>
</html>

如果还是出现404, 打开, 将文件夹设置为你项目的文件夹目录

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值