springboot Serving Web Content with Spring MVC

2024-05-26 00:39:02

Serving Web Content with Spring MVC

This guide walks you through the process of creating a "hello world" web site with Spring.

What you’ll build

You’ll build an application that has a static home page, and also will accept HTTP GET requests at:

http://localhost:8080/greeting

and respond with a web page displaying HTML. The body of the HTML contains a greeting:

"Hello, World!"

You can customize the greeting with an optional name parameter in the query string:

http://localhost:8080/greeting?name=User

The name parameter value overrides the default value of "World" and is reflected in the response:

"Hello, User!"

What you’ll need

  • About 15 minutes

  • A favorite text editor or IDE

  • JDK 1.8 or later

  • Gradle 2.3+ or Maven 3.0+

  • You can also import the code from this guide as well as view the web page directly into Spring Tool Suite (STS) and work your way through it from there.

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Build with Gradle.

To skip the basics, do the following:

  • Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-serving-web-content.git

  • cd into gs-serving-web-content/initial

  • Jump ahead to Create a web controller.

When you’re finished, you can check your results against the code in gs-serving-web-content/complete.

Build with Gradle

Build with Maven

Build with your IDE

Create a web controller

In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify these requests by the @Controller annotation. In the following example, the GreetingController handles GET requests for /greeting by returning the name of a View, in this case, "greeting". A View is responsible for rendering the HTML content:

src/main/java/hello/GreetingController.java

packagehello;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;@ControllerpublicclassGreetingController{@RequestMapping("/greeting")publicStringgreeting(@RequestParam(value="name",required=false,defaultValue="World")Stringname,Modelmodel){model.addAttribute("name",name);return"greeting";}}

This controller is concise and simple, but there’s plenty going on. Let’s break it down step by step.

The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.

  The above example does not specify GET vs. PUTPOST, and so forth, because @RequestMapping maps all HTTP operations by default. Use @RequestMapping(method=GET) to narrow this mapping.

@RequestParam binds the value of the query String parameter name into the nameparameter of the greeting() method. This query String parameter is not required; if it is absent in the request, the defaultValue of "World" is used. The value of the name parameter is added to a Model object, ultimately making it accessible to the view template.

The implementation of the method body relies on a view technology, in this case Thymeleaf, to perform server-side rendering of the HTML. Thymeleaf parses the greeting.html template below and evaluates the th:text expression to render the value of the ${name} parameter that was set in the controller.

src/main/resources/templates/greeting.html

<!DOCTYPE HTML><htmlxmlns:th="http://www.thymeleaf.org"><head><title>Getting Started: Serving Web Content</title><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"/></head><body><pth:text="'Hello, ' + ${name} + '!'"/></body></html>

Developing web apps

A common feature of developing web apps is coding a change, restarting your app, and refreshing the browser to view the change. This entire process can eat up a lot of time. To speed up the cycle of things, Spring Boot comes with a handy module known as spring-boot-devtools.

  • Enable hot swapping

  • Switches template engines to disable caching

  • Enables LiveReload to refresh browser automatically

  • Other reasonable defaults based on development instead of production

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

src/main/java/hello/Application.java

packagehello;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}

@SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

  • @ComponentScan tells Spring to look for other components, configurations, and services in the the hello package, allowing it to find the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.

Build an executable JAR

You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build. Then you can run the JAR file:

java -jar build/libs/gs-serving-web-content-0.1.0.jar

If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:

java -jar target/gs-serving-web-content-0.1.0.jar

  The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.

Logging output is displayed. The app should be up and running within a few seconds.

Test the App

Now that the web site is running, visit http://localhost:8080/greeting, where you see:

"Hello, World!"

Provide a name query string parameter with http://localhost:8080/greeting?name=User. Notice how the message changes from "Hello, World!" to "Hello, User!":

"Hello, User!"

This change demonstrates that the @RequestParam arrangement in GreetingController is working as expected. The name parameter has been given a default value of "World", but can always be explicitly overridden through the query string.

Add a Home Page

Static resources, like HTML or JavaScript or CSS, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at "/static" (or "/public"). The index.html resource is special because it is used as a "welcome page" if it exists, which means it will be served up as the root resource, i.e. at http://localhost:8080/ in our example. So create this file:

src/main/resources/static/index.html

<!DOCTYPE HTML><html><head><title>Getting Started: Serving Web Content</title><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"/></head><body><p>Get your greeting <ahref="/greeting">here</a></p></body></html>

and when you restart the app you will see the HTML at http://localhost:8080/.

springboot Serving Web Content with Spring MVC相关推荐

  1. Java Web系列:Spring MVC基础

    1.Web MVC基础 MVC的本质是表现层模式,我们以视图模型为中心,将视图和控制器分离出来.就如同分层模式一样,我们以业务逻辑为中心,把表现层和数据访问层代码分离出来是一样的方法.框架只能在技术层 ...

  2. springboot 入门教程(4)--web开发(spring mvc和Thymeleaf模板,带源码)

    2019独角兽企业重金招聘Python工程师标准>>> 首先回顾下前几篇的内容:springboot 入门教程(1),springboot 入门教程-Thymeleaf(2), sp ...

  3. java webpack web项目_spring + spring mvc + mybatis + react + reflux + webpack Web工程例子

    前言 最近写了个Java Web工程demo,使用maven构建: 后端使用spring + spring mvc + mybatis: 前端使用react + react-router+ webpa ...

  4. intellij idea 12 搭建maven web项目 freemarker + spring mvc

    配置spring mvc ,写这篇文章的时候spring已经出了4.0 这里还是用稳定的3.2.7.RELEASE,先把spring和freemarker配置好 1.spring mvc配置 在web ...

  5. 【Spring MVC】 maven pom.xml 错误: Cannot upgrade/downgrade to Dynamic Web Module 3.0 facet.

    2019独角兽企业重金招聘Python工程师标准>>> web.xml <?xml version="1.0" encoding="UTF-8&q ...

  6. Spring MVC快速入门

    今天给大家介绍一下Spring MVC,让我们学习一下如何利用Spring MVC快速的搭建一个简单的web应用. 环境准备 一个称手的文本编辑器(例如Vim.Emacs.Sublime Text)或 ...

  7. [Java] Maven 建立 Spring MVC 工程

    GIT: https://github.com/yangyxd/Maven.SpringMVC.Web 1. 建立 WebApp 工程 下一步: 下一步: 选择 maven-archetype-web ...

  8. Spring MVC 学习总结(一)——MVC概要与环境配置 转载自【张果】博客

    Spring MVC 学习总结(一)--MVC概要与环境配置 目录 一.MVC概要 二.Spring MVC介绍 三.第一个Spring MVC 项目:Hello World 3.1.通过Maven新 ...

  9. JavaEE进阶 - Spring MVC 程序开发 - 细节狂魔

    文章目录 什么是 Spring MVC? MVC 定义 MVC 和 Spring MVC 的关系 总结 为什么要学 Spring MVC? Spring MVC 项目的创建 学习 Spring MVC ...

最新文章

  1. webpack项目中使用vue
  2. javascript十个最常用的自定义函数
  3. jsp 中forward 和 Redirect 的用法区别
  4. ES6 数值的扩展
  5. python爬取酷狗音乐top500_Python爬取酷狗Top500的歌曲!够你吹个小牛皮了吧!
  6. vbs隐藏cmd命令窗口调用bat程序执行class
  7. 厦门大学计算机考研怎么样6,【图片】一战厦大计算机上岸,经验帖。慢更【考研吧】_百度贴吧...
  8. MySQL 优化 —— SQL优化概述(优化专题开篇词)
  9. CLion开发GTKmm界面应用的Cmake配置文件
  10. 读取图像到txt的程序
  11. python界面开发webview_Python+Appium学习篇之WebView处理
  12. QMessageBox::information 自定义按钮
  13. 过VMP加壳程序的自效验
  14. pyCharm报错your evaluation license has expired,每次使用三十分钟
  15. nodejs获取当前连接的网络ip
  16. c语言水果程序,C语言写的简易水果管理系统
  17. MySQL最佳基友之PHP入坑指南—白俊遥
  18. 智创万物,数赢未来——如何助推数智时代的发展浪潮
  19. 修改Recovery中的文字提示(二)
  20. [COI2007] Sabor

热门文章

  1. Flutter中的提示工具
  2. 2、Mysql 8.0.20最新版本修改密码
  3. 计算机专业考研英语二国家线,历年考研英语国家线汇总(2009-2020)
  4. 获取mysql所有用户权限_python 获取mysql数据库列表以及用户权限
  5. 大地发生了变化写具体_小学语文三年级下册期末检测卷 (2)
  6. 直播报名 | 大牛教你哔哩哔哩、亚马逊跨境电商用户画像实战真经
  7. 【参会指南】神策 2020 数据驱动用户大会,10 月 13 日将重磅开幕!
  8. 《CSS蝉意花园读书精记》(基础篇---------上.资料篇1)
  9. C# (类型、对象、线程栈和托管堆)在运行时的相互关系
  10. 《编程珠玑(第2版•修订版)》—第2章2.5节原理