如何在SpringBoot在JSP中使用标签JSP

Spring&Boot添加JSP支持
&(1)创建Maven web project;
&(2)在pom.xml文件添加依赖;
&(3)配置application.properties支持jsp
&(4)编写测试Controller
&(5)编写JSP页面
&(6)编写启动类Main.java
&dependency&
&&&&&groupId&javax.servlet&/groupId&
&&&&&artifactId&javax.servlet-api&/artifactId&
&&&&&scope&provided&/scope&
&/dependency&
&dependency&
&&&&&groupId&javax.servlet&/groupId&
&&&&&artifactId&jstl&/artifactId&
&/dependency&
&dependency&
&&&&&groupId&org.springframework.boot&/groupId&
&&&&&artifactId&spring-boot-starter-tomcat&/artifactId&
&/dependency&
&dependency&
&&&&&groupId&org.apache.tomcat.embed&/groupId&
&&&&&artifactId&tomcat-embed-jasper&/artifactId&
&&&&&scope&provided&/scope&
&/dependency&&
application.properties
#页面默认的前缀目录
spring.mvc.view.prefix=/WEB-INF/show/
#响应页面默认后缀
spring.mvc.view.suffix=.jsp
#自定义属性,可以在Controller中读取
#application.hello=Hello
application&
特别注意:工程目录和传统的目录一致,如下图,必须用spring-boot:run运行项目,否则会报404错误。&
<img STYLE="width:389height:367px" ALT="图片" src="/blog7style/images/common/sg_trans.gif" real_src ="http://r.photo./psb?/V13UamH52n0b7j/2xdgG.Dzy3nS4EvM5Yf*9D2cQ1Lrug*kGmP5NVKzYOE!/o/dG4BAAAAAAAA&bo=hQFvAYUBbwEDEDU!"
TITLE="Spring&Boot添加JSP支持" />&
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。使用Spring Boot快速构建应用 - 重生の记忆 - ITeye博客
博客分类:
随着Spring 4新版本的发布,Spring Boot这个新的子项目得到了广泛的关注,因为不管是Spring 4官方发布的新闻稿还是针对首席架构师Adrian Colyer的专访,都对这个子项目所带来的生产率提升赞誉有加。
Spring Boot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于Spring MVC的Web应用和REST服务开发。
Spring 4倡导微服务的架构,针对这一理念,近来在微博上也有一些有价值的讨论,如这里和这里。微服务架构倡导将功能拆分到离散的服务中,独立地进行部署,Spring Boot能够很方便地将应用打包成独立可运行的JAR包,因此在开发模式上很契合这一理念。目前,Spring Boot依然是0.5.0的里程碑版本,因此相关的文档尚不完善,本文将会以一个简单的样例来介绍基于这个项目的开发过程。
要Spring Boot进行功能开发,需要使用Gradle或者Maven作为构建工具。在本例中,我们会使用Eclipse和Maven插件进行开发。要使用Spring Boot,首先创建一个Maven工程,并修改Maven主要的配置文件pom.xml,如下所示:
&properties&
&java.version&1.7&/java.version&
&start-class&com.test.springboot.Startup&/start-class&
&/properties&
&!-- Inherit defaults from Spring Boot --&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-parent&/artifactId&
&version&1.0.1.RELEASE&/version&
&!-- Add typical dependencies for a web application --&
&dependencies&
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-web&/artifactId&
&/dependency&
&/dependencies&
&pluginManagement&
&artifactId&maven-compiler-plugin&/artifactId&
&configuration&
&source&1.7&/source&
&target&1.7&/target&
&/configuration&
&/plugins&
&/pluginManagement&
&repositories&
&repository&
&id&spring-snapshots&/id&
&url&http://repo.spring.io/snapshot&/url&
&snapshots&
&enabled&true&/enabled&
&/snapshots&
&/repository&
&repository&
&id&spring-milestones&/id&
&url&http://repo.spring.io/milestone&/url&
&/repository&
&/repositories&
&pluginRepositories&
&pluginRepository&
&id&spring-snapshots&/id&
&url&http://repo.spring.io/snapshot&/url&
&/pluginRepository&
&pluginRepository&
&id&spring-milestones&/id&
&url&http://repo.spring.io/milestone&/url&
&/pluginRepository&
&/pluginRepositories&
在上面的配置中,需要将工程的parent设置为spring-boot-starter-parent,并添加对spring-boot-starter-web的依赖,这样我们就无需设置各个依赖项及其版本信息了。并且在构建中要声明使用spring-boot-maven-plugin这个插件,它会对Maven打包形成的JAR进行二次修改,最终产生符合我们要求的内容结构。
在我们的应用中将要发布一个REST服务,显示一个基本的用户信息,首先定义一个简单的模型类:
public class User {
public Long getId() {
public void setId(Long id) {
public String getName() {
public void setName(String name) {
this.name =
接下来,我们需要声明一个Spring MVC的Controller,响应对实体的请求:
//@EnableAutoConfiguration
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/{id}")
public User view(@PathVariable("id") Long id) {
User user = new User();
user.setId(id);
user.setName("zhang");
//public static void main(String[] args) {
SpringApplication.run(UserController.class);
这个类与我们在使用Spring MVC定义Controller时并无任何差别。接下来,我们需要声明一个主类启动这个应用程序:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Startup {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Startup.class);
app.setWebEnvironment(true);
app.setShowBanner(false);
Set&Object& set = new HashSet&Object&();
//set.add("classpath:applicationContext.xml");
app.setSources(set);
app.run(args);
这个类的main方法中使用了SpringApplication帮助类,并以Application这个类作为配置来启动Spring的应用上下文。在这个类中使用了ComponentScan以及EnableAutoConfiguration注解,其中ComponentScan注解会告知Spring扫描指定的包来初始化Spring Bean,这能够确保我们声明的Bean能够被发现。EnableAutoConfiguration将会启动自动配置模式,在我们的配置中会将对Tomcat的依赖级联进来,因此在应用启动时将会自动启动一个嵌入式的Tomcat,因为在样例中使用了Spring MVC,所以也会自动注册所需的DispatcherServlet,这都不需要类似web.xml这样的配置。在Eclipse中要运行这个应用的话,可以直接以Java Application的形式来运行这个main函数,此时会启动应用,我们在浏览器中可以看到如下的运行效果,这就是我们想要的REST服务:
在开发调试完成之后,可以将应用打成JAR包的形式,在Eclipse中可以直接使用Maven插件的package命令,最终会形成一个可运行的JAR包。我们使用java –jar命令就可以运行这个JAR包了。Myeclipse的Maven的package请参考( )所呈现出的效果与在调试期是一样的。现在看一下这个JAR包解压后的目录结构:
这个JAR包与传统JAR包的不同之处在于里面有一个名为lib的目录,在这个目录中包含了这个简单应用所依赖的其他JAR包,其中也包含内置的嵌入式Tomcat,正是使用它,才能发布服务和访问Web资源。除了我们编写的源码所编译形成的CLASS以外,在org目录下还有许多Spring所提供的CLASS,正是依赖这些CLASS,才能够加载位于lib目录下JAR中的类。这样的加载机制与在OSGi bundle中声明Bundle-Classpath很类似,不过在OSGi中会由容器来负责加载指定路径下的类。这大致阐述了这样一个JAR包能够发布服务的原因。
如果我们想要使用HTML、JSP等Web资源的话,在Controller中直接返回对应的视图就可以了。
如果我们想要将这个JAR包转换成可以在Servlet容器中部署的WAR的话,就不能依赖于Application的main函数了,而是要以类似于web.xml文件配置的方式来启动Spring应用上下文,此时我们需要声明这样一个类:
public class HelloWebXml extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
这个类的作用与在web.xml中配置负责初始化Spring应用上下文的监听器作用类似,只不过在这里不需要编写额外的XML文件了。
如果要将最终的打包形式改为WAR的话,还需要对pom.xml文件进行修改,除了需要将packaging的值修改为war以外,还需要对依赖进行适当的配置(这一部分在Spring Boot的样例和文档中均未提及,提醒大家注意):
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-web&/artifactId&
&exclusions&
&exclusion&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-tomcat&/artifactId&
&/exclusion&
&/exclusions&
&/dependency&
在这里需要移除对嵌入式Tomcat的依赖,这样打出的WAR包中,在lib目录下才不会包含Tomcat相关的JAR包,否则将会出现启动错误。另外,在移除对Tomcat的依赖后,为了保证编译正确,还需要添加对servlet-api的依赖,因此添加如下的配置:
&dependency&
&groupId&org.apache.tomcat&/groupId&
&artifactId&tomcat-servlet-api&/artifactId&
&version&7.0.42&/version&
&scope&provided&/scope&
&/dependency&
在这里将scope属性设置为provided,这样在最终形成的WAR中不会包含这个JAR包,因为Tomcat或Jetty等服务器在运行时将会提供相关的API类。此时,执行mvn package命令就会得到一个WAR文件,我们可以直接将其放到Tomcat下运行(需要7.0.42版本以上)。
以上介绍了基于Spring Boot开发应用的过程,目前它的文档尚不完善,但是在GitHub上有不少的样例,包括与Spring Data集成访问数据库(关系型以及非关系型)、安全、WebSocket等,读者感兴趣可以下载运行。
基于以上的介绍,希望读者能够对Spring Boot这个新项目有所了解。它简化了JAR包管理和相关基础设施环境的配置,能够帮助我们快速开发Web应用或构建REST服务,希望它能够尽快完善成熟,更多地用于实践,提升开发效率。
浏览 64374
浏览: 271275 次
来自: 北京
gradle+maven+springboot实战课程观看地址 ...
&artifactId&maven-compile ...
说明下&start-class&com.test. ...
学习了,感谢了
执行mvn clean install spring-boot ...Spring Boot开发Web应用 - 简书
Spring Boot开发Web应用
中我们完成了一个简单的RESTful Service,体验了快速开发的特性。在留言中也有朋友提到如何把处理结果渲染到页面上。那么本篇就在上篇基础上介绍一下如何进行Web应用的开发。
静态资源访问
在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
渲染Web页面
在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?
在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供了默认配置的模板引擎主要有以下几种:
FreeMarker
Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。
Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。
示例模板:
&th th:text="#{msgs.headers.name}"&Name&/td&
&th th:text="#{msgs.headers.price}"&Price&/td&
&tr th:each="prod : ${allProducts}"&
&td th:text="${prod.name}"&Oranges&/td&
&td th:text="${#numbers.formatDecimal(prod.price,1,2)}"&0.99&/td&
可以看到Thymeleaf主要以属性的方式加入到html标签中,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。
在Spring Boot中使用Thymeleaf,只需要引入下面依赖,并在默认的模板路径src/main/resources/templates下编写模板文件即可完成。
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-thymeleaf&/artifactId&
&/dependency&
在完成配置之后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来通过Thymeleaf渲染一个页面。
@Controller
public class HelloController {
@RequestMapping("/")
public String index(ModelMap map) {
// 加入一个属性,用来在模板中读取
map.addAttribute("host", "");
// return模板文件的名称,对应src/main/resources/templates/index.html
return "index";
&!DOCTYPE html&
&head lang="en"&
&meta charset="UTF-8" /&
&title&&/title&
&h1 th:text="${host}"&Hello World&/h1&
如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:,做到了不破坏HTML自身内容的数据逻辑分离。
更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。
Thymeleaf的默认参数配置
如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。
# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
支持JSP的配置
Spring Boot并不建议使用,但如果一定要使用,可以参考此工程作为脚手架:
会一些前端,懂一些后端,做过一些管理,弄过一些运维,搞过一些推广,我是一枚爱折腾的团队万金油……
微信订阅号:didispace
我的博客:
拥有最强Spring Cloud研究者阵容的社区:
Spring技术框架一网打尽!spring boot中访问jsp报404
spring boot中访问jsp报404,application.properties配置和代码结构如下,其中application.properties的配置如下,其中prefix中包含"WEB-INF",自己调试发现ResourceHttpRequestHandler.isInvalidPath中判断有"WEB-INF"返回true表示路径非法,直接跳转到错误页面了,哪位大神帮忙看看
application.properties配置:
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#logging.config=src/main/resources/logback.xml
logging.level.org.springframework.web = DEBUG
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
唉,两个问题,一个是pom中少了
&dependency& &groupId&org.apache.tomcat.embed&/groupId& &artifactId&tomcat-embed-jasper&/artifactId& &scope&provided&/scope& &/dependency& &dependency& &groupId&javax.servlet&/groupId& &artifactId&jstl&/artifactId& &/dependency&
另一个是必须用sping-boot:run启动
谢谢各位的回答
--- 共有 1 条评论 ---
我的项目也是要通过mvn spring-boot:run启动才可以访问页面,但是下面这个示例项目可以通过SampleWebJspApplication.java启动项目正常访问,
/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-jsp
看下官方是sample吧
--- 共有 1 条评论 ---
官方sample就是这样的结构和配置,我这样却找不到jsp文件。。。
SpringBoot官方文档写的很明确:“JSPs should be avoided if possible, there are several&&when using them with embedded servlet containers.”
不建议使用JSP当模板引擎,而且SpringBoot也不建议设置webapp这个目录,都应当放在resources目录中
--- 共有 1 条评论 ---
我知道不建议使用jsp,不过还是想搞清楚为什么有这个问题,是参考官方sample写的,但是找不到jsp文件
jsp确实是坑,我也困扰过好几次,demoApplication怎么写的
--- 共有 3 条评论 ---
坑的不是jsp 是springboot
: 要继承SpringBootServletInitializer
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
看配置你应该是1.3.3最新版,我昨晚刚升级了
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
这是我的配置,运行没问题,不要听楼上几个乱说jsp不行,用得好好的
对了,jdk8,tomcat&
引用来自“抓瓦工人”的评论
看配置你应该是1.3.3最新版,我昨晚刚升级了
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
这是我的配置,运行没问题,不要听楼上几个乱说jsp不行,用得好好的
对了,jdk8,tomcat&
这样以下校验会返回true表示校验不通过直接返回错误页面了啊
我想问题的原因可能是这样:
Spring boot 默认是将DispatcherServlet 映射在 / 路径的,也就是所有请求都被Spring MVC接管。启动完毕之后,应该能看到这句日志:
Mapping servlet: 'dispatcherServlet' to [/]
所以直接访问jsp是访问不到的,除非用Controller中中转,跳往指定View(jsp)或是添加ViewController:
继承WebMvcConfigurerAdapter,重写addViewControllers方法:
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/foo").setViewName("foo");
更新:日13:45:25
大致看了下Spring boot 文档。提到了一JSP的一些限制:
只能用tomcat并且pom中的package设为war,jetty没有支持。
引用来自“JohntoString”的评论 我想问题的原因可能是这样:
Spring boot 默认是将DispatcherServlet 映射在 / 路径的,也就是所有请求都被Spring MVC接管。启动完毕之后,应该能看到这句日志:
Mapping servlet: 'dispatcherServlet' to [/]
所以直接访问jsp是访问不到的,除非用Controller中中转,跳往指定View(jsp)或是添加ViewController:
继承WebMvcConfigurerAdapter,重写addViewControllers方法:
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/foo").setViewName("foo");
忘了说明一下,是通过访问的,以下是控制器代码,下面的index方法是可以进去正常返回的,返回之后去找jsp的时候根据application.properties配置的路径找不到welcome.jsp
public class UserController { private UserRepository userRepository; @Autowired
public UserController(UserRepository userRepository){ this.userRepository=userR
} @RequestMapping("/user") public ModelAndView getUser(){
List&User& users = (List&User&) userRepository.findAll();
ModelAndView modelAndView = new ModelAndView("users");
modelAndView.addObject("users",users); return modelAndV
} @Value("${application.message:Hello World}") private String message="Hello World"; @RequestMapping("/index") public String index(Map&String,Object& model){
model.put("time",new Date());
model.put("message",this.message); return "welcome";
--- 共有 1 条评论 ---
修改了回答,你再看看能否解决}

我要回帖

更多关于 JSP标签使用 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信