Author: Enjoy learning Peter teacher

Create an MVC Web project using Springboot

Spring Boot is a great application development framework. Most people will probably use this framework to create Web-based applications – MVC applications or RESTFul API-based applications. These applications can be deployed into Docker containers and become microservices.

This tutorial will show students the process of creating a Web-based application using Spring Boot. It is a standalone Java application. An embedded Tomcat server is built in. Can handle various requests for Web pages. For beginners, the most difficult part of every new project is the configuration of the project environment. But following this tutorial, you’ll see how much easier it is to create web projects using Spring Boot than to create applications using Spring V3 / V4 MVC.

The project structure

To begin, show the directory and file structure of the project:

<base-dir>/src/main/java/org/hanbo/boot/app/controllers/HelloController.java

<base-dir>/src/main/java/org/hanbo/boot/app/App.java

<base-dir>/src/main/resources/application.properties

<base-dir>/src/main/resources/static/test.html

<base-dir>/src/main/resources/static/assets/css/index.css

<base-dir>/src/main/resources/static/assets/js/test.js

<base-dir>/src/main/webapp/WEB-INF/jsp/testme.jsp
Copy the code

Two Java files.One is the program entry class. The other one is the MVC controller.



A properties properties file,Inside are some project configuration values.



Three static files,It can be provided directly to the user upon request.



A JSP file,Used as a view template for MVC applications.

If we use the old springMVC approach to configure a Web project, we need to configure the Spring container and the Spring MVC container in the project web.xml, which requires at least two PRing XML configuration files. Here, everything is configured using Java annotations.

POM XML file

Let’s start with the POM XML file. The POM XML file is used for Maven builds. It specifies how to compile and package the project. Here’s what the file says:

<?xml version="1.0" encoding="UTF-8"? >

<project xmlns="http://maven.apache.org/POM/4.0.0"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xsi:schemaLocation="Http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<artifactId>boot-war</artifactId>

<packaging>war</packaging>

<name>Hanbo Boot War Sample App</name>

<description>An example of Spring Boot, JSP and WAR</description>

<version>1.0.0</version>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>At 2.0.5. RELEASE</version>

</parent>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-tomcat</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

<scope>provided</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>
Copy the code

This POM file has several important things. The first is to specify the line on which the Maven build will create the WAR archive:

<packaging>war</packaging>
Copy the code

The second is that POM files have parent POM dependencies. This allows many Spring and non-Spring dependencies to be downloaded and linked into this project:

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>At 2.0.5. RELEASE</version>

</parent>
Copy the code

Three is toJavaCompile set to useJDK 1.8Attribute definition of:

<properties>

<java.version>1.8</java.version>

</properties>
Copy the code

The last one is useSpring Boot mavenPlug-ins are compiled and packaged:

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>
Copy the code

The dependencies section defines the additional dependencies required by this application. What I need is Spring MVC running as a J2EE Web application. The added dependencies are used to compile the JSP view and run the embedded application server.

Main program entry

Next, let’s start coding. Spring Boot project, procedures must have an entry main class, the following is the complete source code of the main class:

package org.hanbo.boot.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class App extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder appBuilder) { return appBuilder.sources(App.class); } public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); }}Copy the code

The App class from SpringBootServletInitializer extension. It is recognized by the Spring Framework and initializes and executes the class App as a traditional WAR package. It also tells the Spring Framework that the WEB-INF folder and the resources in it will be available for use.

In the App class, there is a protected method called configure(). It is used to specify any application-specific configuration. It’s just one line, it takes the type of the App class and creates a SpringApplicationBuilder object and returns it. What this does is create a SpringApplicationBuilder object that automatically scans the App class, the package it’s in, and any subpackages of the annotated class, as well as annotations containing the Spring configuration. It then builds the Spring application based on these configurations. This is a classic example of integration by convention. And everything is coupled through dependency injection.

The static main method is a single line that passes the type of the class App and any other command-line arguments to SpringApplication.run(). Behind the scenes, this course does a lot. It implicitly performs a component scan of the current package and all subpackages. Developers can also add additional path packages as scan targets if desired. Developers can add additional comments for any other configuration they need. For this simple program, only the MVC controller class can handle user requests to the page.

MVC controller

Next up is our MVC controller class. This is a very simple class that has only one method to handle HTTP GET requests from users, with some query parameters. It responds by using JSP pages as views. Source code is as follows:

package org.hanbo.boot.app.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping(value = "/meow", method = RequestMethod.GET) public ModelAndView hello(@RequestParam("sayit") String sayit) { ModelAndView retVal = new ModelAndView(); retVal.setViewName("testme"); retVal.addObject("mymessage", sayit); return retVal; }}Copy the code

There is nothing new about the code in the class. That is, the definition of this controller class is the same as that of any Spring MVC controller. Let’s briefly walk through the class implementation:

The class is annotated with @controller to indicate that it is a controller class.

The class has only one method to handle HTTP GET requests. It is annotated with @requestMapping. An annotation defines the subpath of the request and the HTTP method GET requests it can handle.

Method creates a ModelAndView object and returns it. The view page is called testme. The data model is just a string that will be displayed on the page.

The method takes one parameter from the query parameter, called “sayit.”

The entire function of this class is to respond when the user enters the following path in the browser address bar:

http://localhost:8080/meow?sayit=This+is+pretty+crazy
Copy the code

In order for this controller to work as expected, some additional configuration is required. This is done in the application.properties file.

Application.properties properties file

Application.properties requires specifying the prefix and suffix of the view template file.

If you do a spring MVC project, or you know, the web project need to create and configure a org. Springframework. Web. Servlet. The internalResourceViewResolver type of object, This object needs to specify two properties:

spring.mvc.view.prefix=/WEB-INF/jsp/

spring.mvc.view.suffix=.jsp
Copy the code

The application looks for the view template in the WEB-INF/JSP/ folder. The file extension is “.jsp “.

Ok, now we have the main program entry class, the controller class, and the internal resource view parser set up. The last piece is the view template.

JSP template

The view template for this tutorial is very simple, with a single JSP file showing how to display data in the view model:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"% > <! DOCTYPE html> <html lang="en">

<head>

<c:url value="/assets/css/index.css" var="jstlCss"/>

<link href="${jstlCss}" rel="stylesheet"/> </head> <body> <p>What did you say? </p> <p>I said: <span class="text-underline">"${mymessage}."</span></p>

<script type="text/javascript" src="/assets/js/test.js"></script>

</body>

</html>
Copy the code

In this JSP file, there are three things:

There are cascading style sheet files. It is a static file, added through the JSTL tag. This requires that the JSTL libraries have been properly introduced into the project.

The viewmodel has only one element, which is added to the view with $myMessage.

A javascript file is added to the end of the HTML content, which will be executed when loaded. This is to demonstrate the use of static files in this project.

It is important that the sample application provide static content. It provides an approach that goes beyond Spring MVC — static pages and javascript can be used for single-page Web applications. Also, it’s easy to get static content with Spring boot, as I’ll explain later.

Static files

Spring Boot provides a lot of convenience for developers to get started quickly.

These conveniences are made possible by a convention:

When the application you develop with Spring Boot is designated as web-based, all you need to do is create a folder named “static” under SRC /main/ Resources.

In this “static” folder, you can simply add any subfolders as needed and put any static content files into them to serve them. In this example, I have three files that are specified as static content:

  • Cascading style sheets (CSS) file, the SRC/resources/static/assets/CSS/index. The CSS

  • A javascript file – the SRC/resources/static/assets/js/test. The js

  • An HTML file, the SRC/resources/static/test. The HTML

So how does a user access this static content through a browser? It’s easy. Assuming the application is running, and assuming the URL of the web site where the application is running is http://localhost:8080/ (there is no specific application context here), the user can view the actual contents of these static content files using the following URL:

http://localhost:8080/assets/js/test.js


http://localhost:8080/assets/css/index.css.



http://localhost:8080/assets/test.html.

There are ways to configure Spring boot applications to find static content files in other locations, as well as web-INF and JSP locations, how the application is initialized, and many other aspects of how Spring boot applications work. These are not the topics discussed in this tutorial, but they are trivial if you know enough about Spring Boot. I may cover some of them in a future article.

Build and run the application

Before building the project, please go to the SRC/main/resources/static/assets/js folder, and the file “test. Sj” renamed “test. Js”.

To build this application, run the following command from the command line console:

mvn clean install
Copy the code

When you run the application for the first time, it will download all the dependencies used to build the application, which may take some time. After that, subsequent builds will take less time.

To run the Web application, you can also use the command line console:

Java jar target \ boot - war - 1.0.0. WarCopy the code

If all goes well and you can build the application, the execution will end up producing something like this:

/ \ \ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | | | (_ | |))))' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: 2018-10-14 22:51:11.356 INFO 6124 -- [main] org.hanbo.boot.app.App: Starting App V1.0.0 on u3Dtest-PC with PID 6124 (C:\Users\u3dadmin\workspace-mars8\SpringBootJspWar\target\boot-war-1.0.0.war Started by u3dadmin in C:\Users\u3dadmin\workspace-mars8\SpringBootJspWar) .... . . The 22:51:28 2018-10-14. 6124-730 the INFO [main] O.S.B.W.E mbedded. Tomcat. TomcatWebServer: tomcat started on the port (s) : 8080 (http) with context path '2018-10-14 22:51:28.745 INFO 6124 -- [main] org.hanbo.boot. App.App: 2018-10-14 22:51:28.745 INFO 6124 -- [main] org.hanbo.boot. Started App in 20.84 seconds (JVM running for 23.398)Copy the code

As I mentioned earlier, using Spring boot to create Web applications is simple and convenient. The key to this convenience is to get rid of all the clutter so that people can focus on the most important parts of the development process and design products that live up to the vision of the final product. One cool thing about Spring Boot is that it can be quickly deployed to a Docker VIRTUAL machine. Therefore, it is well suited to developing microservices.

The next step, then, is to write the more complex Spring work, such as data access, authentication, and authorization. Stay tuned.

END

Welcome to long click the picture below to pay attention to the public account: Enjoy learning class online!

Public account background reply [Java], get carefully prepared architecture learning materials (video + document + architecture notes)