springboot Serving Web Content with Spring MVC

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

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:

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

package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        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>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th: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

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p>Get your greeting <a href="/greeting">here</a></p>
</body>
</html>

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

时间: 2024-08-25 13:52:21

springboot Serving Web Content with Spring MVC的相关文章

Spring Boot——Serving Web Content with Spring MVC

来自官方文档:https://spring.io/guides/gs/serving-web-content/ This guide walks you through the process of creating a “Hello, World” web site with Spring. What You Will Build You will build an application that has a static home page and that will also accep

Java Web系列:Spring MVC 基础

1.Web MVC基础 MVC的本质是表现层模式,我们以视图模型为中心,将视图和控制器分离出来.就如同分层模式一样,我们以业务逻辑为中心,把表现层和数据访问层代码分离出来是一样的方法.框架只能在技术层面上给我们帮助,无法在思考和过程上帮助我们,而我们很多人都不喜欢思考和尝试. 2.实现Web MVC的基础 实现Web MVC基础可以概括为1个前段控制器和2个映射. (1)前端控制器FrontController ASP.NET和JSP都是以Page路径和URL一一对应,Web MVC要通过URL

web工程使用spring mvc+shiro进行权限控制

第1步:引入shiro相关jar包 ehcache-core-2.5.0.jar shiro-ehcache-1.2.3.jar shiro-core-1.2.3.jar shiro-web-1.2.3.jar shiro-spring-1.2.3.jar 第二步:web.xml配置 <!-- shiro的filter --> <!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 --> <fi

【WEB】初探Spring MVC框架

Spring MVC框架算是当下比较流行的Java开源框架.但实话实说,做了几年WEB项目,完全没有SpringMVC实战经验,乃至在某些交流场合下被同行严重鄙视“奥特曼”了.“心塞”的同时,只好默默的打开IDE从HelloWorld开始. 初步认识 宏观视野决定微观实现的质量,首先对Spring MVC框架组件及其流程做一个简单的认识.以下是从互联网中某Spring MVC教材扣来一张介绍图(懒得重复造轮子了): 从上图可以看出,Spring MVC框架的核心组件有DispatcherServ

二十、MVC的WEB框架(Spring MVC)

一.Spring MVC 1.同样还是导入相应的jar包,将用到的jar包,导入到项目的WebContent/WEB-INF/lib目录下. 2.web.xml文件 在WEB-INF目录下创建一个web.xml文件,用来配置Spring MVC的入口DispatcherServlet(类似structs2配置的StructsPrepareAndExecuteFilter过滤器),目的就是把所有的请求都提交给DispatcherServlet处理. 注:<servlet-name>springm

基于Spring Boot构建的Spring MVC快速入门

原文地址:http://tianmaying.com/tutorial/spring-mvc-quickstart 环境准备 一个称手的文本编辑器(例如Vim.Emacs.Sublime Text)或者IDE(Eclipse.Idea Intellij) Java环境(JDK 1.7或以上版本) Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装) 一个最简单的Web应用 使用Spring Boot框架可以大大加速Web应用的开发过

Spring MVC 基础

Spring MVC 基础 1.Web MVC基础 MVC的本质是表现层模式,我们以视图模型为中心,将视图和控制器分离出来.就如同分层模式一样,我们以业务逻辑为中心,把表现层和数据访问层代码分离出来是一样的方法.框架只能在技术层面上给我们帮助,无法在思考和过程上帮助我们,而我们很多人都不喜欢思考和尝试. 2.实现Web MVC的基础 实现Web MVC基础可以概括为1个前段控制器和2个映射. (1)前端控制器FrontController ASP.NET和JSP都是以Page路径和URL一一对应

Java Web系列:Spring Security 基础

Spring Security虽然比JAAS进步很大,但还是先天不足,达不到ASP.NET中的认证和授权的方便快捷.这里演示登录.注销.记住我的常规功能,认证上自定义提供程序避免对数据库的依赖,授权上自定义提供程序消除从缓存加载角色信息造成的角色变更无效副作用. 1.基于java config的Spring Security基础配置 (1)使用AbstractSecurityWebApplicationInitializer集成到Spring MVC 1 public class Securit

通过eclipse配置Spring MVC项目

上一篇刚建立了一个简单的Spring项目,其实Spring MVC是一个和Struts2一样的基于MVC设计模式的web框架,并且继承了MVC的优点,是基于请求驱动的轻量级的web框架,spring mvc可以认为是spring其中的一个web扩展,小巧灵活,但是功能强大,可以直接传入ServletAPI使用起来开发会比较简单顺手,并且通过配置注解的方式,很轻松的对web资源进行管理,提高了开发的速度和应用程序的可维护性 使用spring mvc可以设计出干净的web层和薄薄的web层:目前非常