7. Using the Spring MVC Service Web content

Source: Internet
Author: User

This guide introduces you to the process of creating a "Hello World" site using spring. Read the original: Serving Web Content with Spring MVC

1. What will you build?

You will build an application with a static home page and will also accept HTTP GET requests at the following location:

http://localhost:8080/greeting

and responds with a webpage that displays HTML. The body of the HTML contains a greeting:

"Hello, world!."

You can customize the greeting by using the 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!."
2. What do you need to prepare?
    • About 15 minutes

    • A favorite text editor or IDE

    • JDK 1.8 or higher

    • Gradle 4+ or Maven 3.2+

    • You can also import code into your IDE

      • Spring Tool Suite (STS)

      • IntelliJ idea

3. How do I implement this guide?

Like most spring getting started guides, you can start from scratch and complete each step, or you can bypass the basic setup steps you're already familiar with. Either way, you end up getting the work code.

1. Open sts,new ———— > Import Spring Getting Started Content

2. Enter servi, search to find serving Web Content

Tips:build Type Select maven, Code sets all tick, because this can be generated at the same time after the completion of the point and empty items, so that we learn.

3. Create a Web Controller

In spring's method of building a Web site, the HTTP request is handled by the controller.

You can easily identify these requests with @controller annotations. In the following example, Greetingcontroller processes/Greeting a GET request by returning the name of the view (in this case, "greeting"). The 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.GetMapping;ImportOrg.springframework.web.bind.annotation.RequestParam; @Controller Public classGreetingcontroller {@GetMapping ("/greeting")     PublicString Greeting (@RequestParam (name= "name", required=false, defaultvalue= "World"String name, model model) {Model.addattribute ("Name", name); return"Greeting"; }}

The controller is simple and straightforward, but there are a lot of things to do. Let's break it down one step at a-step.

@GetMapping Note to ensure that HTTP GET requests for/get are mapped to the greeting () method.

The @RequestParam binds the value of the query string parameter name to the greeting () method in name parameter. This query string parameter is not required; If missing in the request, the default value of "World" is used. The value of the name parameter is added to the model object, which can eventually be accessed by the view template.

The implementation of the method body relies on the view technique, in this case the Thymeleaf, which performs the server-side rendering of the HTML. Thymeleaf parses the following greeting.html template and evaluates the Th:text expression to render the value of the $ {name} parameter set in the controller.

Src/main/resources/templates/greeting.html

<! DOCTYPE html>

4. Developing Web Applications

A common feature of developing Web applications is to encode changes, restart the application, and refresh the browser to see the changes. The whole process can take a lot of time. To speed things up, Spring boot comes with a handy module called Spring-boot-devtools.

Enable hot swapping

Toggle the template engine to disable caching

Enables livereload to automatically refresh the browser

Other reasonable defaults based on development rather than production

5. Making the application executable

Although this service can be packaged as a traditional war file for deployment to an external application server, the simpler approach shown below creates a standalone application. You package everything into a separate, executable jar file, driven by a good old Java main () method. Along the journey, you use spring's support to embed the Tomcat servlet container as an 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 {    publicstaticvoid  main (string[] args) {        Springapplication.run (Application. class , args);}    }

@SpringBootApplication is a handy comment that adds all of the following:

    • @Configuration to mark the class as the source of the bean definition for the application context.
    • @EnableAutoConfiguration notifies spring boot to start adding beans based on the classpath setting, and other beans and various property settings.
    • Typically you will add @enablewebmvc to the Spring MVC application, but spring boot will be added automatically when you see Spring-webmvc in the classpath. This marks the application as a Web application and activates key behaviors, such as setting Dispatcherservlet.
    • @ComponentScan tell spring to look for additional components, configurations, and services in the Hello package to locate the controller.

The main () method launches the application using the Spring Boot Springapplication.run () method. Have you noticed that there is not a single line of XML? No web. xml file. This Web application is 100% pure Java, and you do not have to deal with configuring any pipelines or infrastructure.

6. Compile an executable jar

You can use Gradle or maven to run the application from the command line. Or you can build an executable jar file that contains all of the required dependencies, classes, and resources, and run the file. This makes it easy to publish, release, and deploy services as applications across different environments throughout the development lifecycle.

If you are using Gradle, you can use the./gradlew Bootrun to run the application. Or you can build a build jar file using./gradlew. 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 use the./MVN Spring-boot:run to run the application. Or you can use the./MVN clean package to build the jar file. Then you can run the jar file:

Java-jar Target/gs-serving-web-content-0.1.0.jar

The above procedure creates a runnable jar. You can also choose to build a classic war file.

7. Test the App

now that the site is running, please visit http://localhost:8080/greeting and you will see:
"Hello, world!."
:

Provides a name for the query string parameter through Http://localhost:8080/greeting?name=User.

Now you notice that the message has been changed from "Hello, world!" to "Hello, user!."

"Hello, user!."

This change demonstrates that the @requestparam arrangement in Greetingcontroller works as expected. The name parameter has been given the default value of "World", but can always be explicitly overridden by a query string.

Add a home page

Static resources such as HTML or JavaScript or CSS can be easily provided from the spring boot application by simply placing them in the correct location of the source code. By default, Spring boot provides static content to resources in the classpath of "/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 provided as a root resource, that is, http://localhost:8080//In our example. So create this file:

Src/main/resources/static/index.html

<! DOCTYPE html>

Then when you restart your app you will see this page at this URL http://localhost:8080/

Congratulations! You have just developed a Web page with spring.
Source: Click to view

7. Using the Spring MVC Service Web content

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.