springboot怎么替代jsp_如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧...

做WEB项目,一定都用过JSP这个大牌。Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的。当你从一个传统的Spring MVC项目转入一个Spring Boot项目后,却发现JSP和view关联有些麻烦,因为官方不推荐JSP在Spring Boot中使用。在我看来,继续用这种繁杂的手续支持JSP仅仅只是为了简单兼容而已。

我们先来看看如何在SpringBoot中使用JSP ?

1. 在pom.xm中加入支持JSP的依赖

org.apache.tomcat.embed

tomcat-embed-jasper

provided

javax.servlet.jsp.jstl

jstl-api

1.2

2. 在src/main/resources/application.properties文件中配置JSP和传统Spring MVC中和view的关联

# MVC

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

3. 创建src/main/webapp/WEB-INF/views目录,JSP文件就放这里

Hello

4. 编写Controller

package com.chry.study;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

@Controller

@EnableAutoConfigurationpublic classSampleController {@RequestMapping("/hello")publicModelAndView getListaUtentiView(){

ModelMap model= newModelMap();

model.addAttribute("name", "Spring Boot"); return new ModelAndView("hello", model);

}}

5. 编写Application类

packagecom.chry.study;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.builder.SpringApplicationBuilder;importorg.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplicationpublic class WebApplication extendsSpringBootServletInitializer {

@OverrideprotectedSpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(WebApplication.class);

}public static void main(String[] args) throwsException {

SpringApplication.run(WebApplication.class, args);

}

}

6. 以java application方式运行后,就可以访问http://locahost:8080/hello

==================  分割线 ==================================

以上代码pom.xml中的javax.servlet.jsp.jstl是用于支持JSP标签库的,在Web2.5的容器中没有问题,单当你的容器是Web3.0或以上版本时,就会出问题。 这是个非常坑爹的问题。

javax.servlet.jsp.jstl会自动加载依赖servlet-api-2.5.jar, 而且会在实际运行时把支持Web3.0的3.1版本的javax.servlet-api覆盖掉。即使你在pom.xml显示的在加入3.1版本的javax.servlet-api也没用。导致SpringBoot应用抛出Runtime exception运行错误。

这是一个不可调和的矛盾,要吗不用javax.servlet.jsp.jstl,要吗不用Web3.0。

但绝大多数情况下,jstl标签库不是必须的,而Web3.0是必须的。替代方式就是不用JSP,改用Themeleaf吧

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值