学习java语言的朋友们对Spring Boot并不陌生,Spring Boot是Spring家族下的一个全新开发框架,其设计目的主要是用来简化Spring应用的创建及开发过程。Spring Boot对JSP页面也是兼容的,java程序员们有时候会使用到,这篇文章来介绍Spring Boot使用JSP步骤,感兴趣的小伙伴们一起来学习吧。
在Spring boot使用jsp,按如下步骤进行:
1、在 pom.xml文件中配置依赖项
<!--引入 Spring Boot 内嵌的 Tomcat 对 JSP 的解析包-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet 依赖的 jar 包 start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- servlet 依赖的 jar 包 start -->
<!-- jsp 依赖 jar 包 start -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jsp 依赖 jar 包 end -->
<!--jstl 标签依赖的 jar 包 start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--jstl标签依赖的jar包end -->
2、在application.properties文件配置spring mvc视图展示为jsp:
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
3、在src/main下创建webapp目录,并在该目录下新建 jsp页面;
在spring boot工程中若要创建jsp文件,一般是需要在src/main下创建webapp目录,然后在该目录下创建jsp文件。但通过Alt + Insert发现没有创建jsp文件的选项。此时,需要打开Project Structrue窗口,将webapp目录指定为web资源目录,然后才可以创建jsp文件。
指定后便可看到下面的窗口情况。
此时,便可在webapp中找到jsp的创建选项了。
4、创建index.jsp页面与welcome.jsp页面
5、配置pom.xml 的resources:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
6、修改HelloController类
修改HelloController,把本来的@RestController 改为@Controller。这时返回"hello"就不再是字符串,而是根据application.properties 中的视图重定向,到/WEB-INF/jsp目录下去寻找hello.jsp文件
package cn.xdf.springboot.web;
import java.text.DateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model m){
m.addAttribute("now",DateFormat.getDateTimeInstance().format(new Date()));
return "hello"; //视图重定向hello.jsp
}
}
7、创建hello.jsp文件
在main目录下,新建--> webapp/WEB-INF/jsp 目录。随后新建hello.jsp 文件,在其中使用EL 表达式显示放在HelloController的model中的当前时间。
8、最后启动测试就可以了
上面就是在Spring Boot使用JSP步骤介绍,希望这篇教程可以帮助到大家,学会了的朋友们可以自己在电脑上练习一遍,真正掌握在Spring Boot中使用JSP的操作。
HelloWorld10-31 08:24
军哥08-12 23:29
江湖人称小李白12-10 10:41
IT逐梦者08-17 21:43
HelloWorld11-06 11:19