搭建 springboot 项目,web页面用 jsp 模板
我把自己遇到的问题和解决方法罗列了一下,看看你们会不会也遇到这些问题
一、IDEA 创建 springboot 项目
二、创建 jsp 视图
三、创建控制器 controller
四、启动springboot 项目
一、IDEA 创建 springboot 项目
step1:打开IDEA,new 一个 project

step2:选择 Spring Initializr ,设置 jdk(本机先安装java jdk)

step3:设置项目 Group 和 Artifact,选择 Packaging 打包方式
Group 和 Artifact 被称为“坐标”,为了保证项目唯一性
Group分为多个段,一般可设成两段,第一段为域,例如org、com、cn,org为非营利组织,com为商业组织;第二段为公司名称
Artifact 为项目名称

step4:选择 Web -> Web , 添加项目web starter
其他的可根据自己的需求选择对应的 starter 进行依赖,或者可后期在pom.xml 中配置

step5:点击 next,然后 finish,通过第一步创建出 springboot ,项目目录如下:

问题一:在创建 springboot 后,会加载 Maven 的 jar 包,如果没有更换成本地安装的的 Maven 仓库,会加载很慢
解决方法:配置本地 maven 仓库(提前在本地安装好Maven,可参考本人整理的maven安装过程:https://www.jianshu.com/p/123892b1661d)
1)点击菜单栏 File -> Settings ,搜索 maven
2)修改 Maven home directory :为已安装的 Maven 的路径
3)修改 User setting file:选择 Maven 安装目录下的 \ conf \ settings.xml, Local repository 会自动加载

二、创建 jsp 视图
问题二:刚开始在 templates目录下想要创建 jsp 文件,想要 new 一个 jsp ,但一直找不到 jsp 模板,原来 springboot 默认不推荐使用 jsp文件作为视图!
解决方法:引入 jsp 依赖包,创建 webapp 目录来进行创建 jsp 文件
step6: 在 main 下 新增 webapp 目录、WEB-INF 目录、 jsp 目录, 创建 jsp 文件
在 main 下新增 webapp 目录, 在 webapp 目录下新增 WEB-INF 目录和 jsp 目录,则将 jsp 文件创建在 jsp 目录下
右击 jsp 目录 -> new -> JSP/JSPX page 创建 jsp 文件,例如本文创建 index.jsp

step7:在 WEB_INF 目录下新增 web.xml
首先,右击 项目 -> Open Module Settings

选择Modules -> 选择Web -> 点击 + 号 -> 点击 web.xml

选择 main\webapp\WEB-INF 目录,在后面添加上 web.xml,点击ok

web.xml 内容如下:


问题三:在根据其他人创建 webapp目录教程中,都把 jsp目录放在 WEB-INF目录下,结果我运行的时候一直报错
解决方法:将 jsp 文件夹放在 webapp 目录下,与 WEB-INF 目录平级,运行成功

step8:在 pom.xml 文件中新增 JSP 和 JSTL 的 Maven 依赖配置
添加 org.apache.tomcat.embed 的 tomcat-embed-jasper 依赖包和 javax.servlet 的 jstl 依赖包

问题四:添加以上两个依赖包,发现引入报错,说没有找到
解决方法:项目中还没有加载这两个依赖包,所以需要重新 import maven
1)点击菜单栏 View -> 选择 Tool Window -> 选择 Maven Project
2)点击 刷新图标,reimport maven

step9:在 application.properties 文件中定义视图前后缀
配置tomcat端口(默认值为8080),可以选择不配置
spring.mvc.view.prefix 和 spring.mvc.view.suffix 是 Spring Boot 约定的视图前缀和后缀的配置,意思是找到 /jsp/ 目录下以 .jsp 为后缀的 JSP 文件

三、创建控制器 controller
step10:在 main / java / com.spring.demo 目录下,创建 controller 类
右击 com.spring.demo 目录 -> new -> 选择 pakage,新增 controller 包
右击 controller 目录 -> new -> 选择 Java Class,创建 Controller 类 ,本人创建为 IndexController 类
引入注解 @Controller 和 @RequestMapping,返回 jsp 页面

问题五: @Controller 和 @ RestController 的区别
@Controller:表明该类内的所有方法默认返回页面路径,加 @ResponseBody的方法可返回数据
@ RestController :是 @ResponseBody 和 @Controller 的组合注解,返回 json 数据,;原先返回 json 数据需要 @ResponseBody 和 @Controller 配合
在本项目demo中,如果使用 @ RestController ,则页面返回的是 index() 函数返回的字符串 index,结果如下图:

四、启动springboot 项目
step11:运行项目的启动类,启动项目

step12:在浏览中输入 http:localhost:8090/index,返回 index.jsp 页面

springboot 小 demo 搭建完毕 ^_^
网友评论