Spring MVC is one of the successful implementations of MVC design pattern, which is widely used in Java Web Development.
First Example of Spring MVC
Our goals
I will build an application that has a static home page, and also will accept HTTP GET requests at:
http://localhost:9001/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:9001/greeting?name=User
The name
parameter value overrides the default value of “World” and is reflected in the response:
"Hello, User!"
Prerequites
- About 15 minutes
- A favorite text editor or IDE
- JDK 1.8 or later
- Maven 3.2 +
Build with Maven
pom.xml
1 | <?xml version="1.0" encoding="UTF-8"?> |
Build with your IDE
Here I use VSCode - Java Delopment Pack extension with pressing Ctrl+Shift+P
to call Spring Initializer.
Checkout ‘Spring Web’ and ‘thymeleaf’ dependency.
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, “demo”. A View
is responsible for rendering the HTML content:
src/main/java/com/example/springmvc/DemoController.java
1 | package com.example.springmvc; |
This controller is concise and simple, but there’s plenty going on. Let’s break it down step by step.
The @GetMapping
annotation ensures that HTTP GET requests to /greeting are mapped to the greeting() method.
@RequestParam
binds the value of the query String parameter ‘name’ into the name
parameter 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 demo.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/demo.html
1 | <!DOCTYPE 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
- Enable 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 development to an external application server, the simpler approach demonstrated below creates a standalone application. You pakcage 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/com/example/springmvc/DemoApplication.java
1 | package com.example.springmvc; |
@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. For example, ifspring-webmvc
is on the classpath, this anootation flags the application as a web application and activates key behaviors, such as setting up aDispatcherServlet
.@ComponentScan
: Tells Spring to look for other components, configurations, and services in thehello
package, letting it find the controllers.
The main()
method uses Spring Boot’s SpringApplication.run()
method to launch an application. Did you notice that was not a single line of XML? There is no web.xml
file, either. This web application is 100% pure Java and you did not 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. You can also build a single executable JAR file that contains all the neccessary dependencies, classes and resources and run that. Building an executable jar so 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 use Maven, you can run the application by using ./mvnw spring-boot:run
. Alternatively, you can build the JAR file with ./mvnw clean package
and then run the JAR file, as follows:
java -jar target/springmvc-0.0.1-SNAPSHOT.jar
Test the App
Now that the web site is running, visit http://localhost:9001/greeting, where you see:
Provide a name
query string parameter with http://localhost:9001/greeting?name=User. Notice how the message changes from “Hello, World!” to “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 by 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:9001/ in our example. So create this file
src/main/resources/static/index.html
1 | <!DOCTYPE HTML> |
and when you restart the app you will see the HTML at http://localhost:9001/
Summary
Congradulations! You have just developed a web page using Spring.
Controller
In Spring, if you want a class to be a controller you can use the annotation @RestController
for this class. And in this class, use annotation @RequestMapping
to show this is an RESTful API function.
HTTP报文如何解析到Controller方法?
Spring MVC框架的底层是Servlet。Servlet是一个标准,主要规定了处理请求与响应的service
接口,在service
接口中只需要实现业务逻辑即可。而Servlet由Servlet容器负责管理与运行,常见的Servlet容器有Tomcat,Jetty等。以Tomcat中的Servlet接口定义为例,如下所示:
由于Servlet只规定了接口,所以通常情况下不会直接继承Servlet进行实现,而是通过继承HttpServlet抽象类来有选择地覆盖相应的方法。而MVC更加方便,甚至不会去手动实现Servlet,只需要通过注解标注出Controller、Service、Model类即可,更加提高了开发的效率。
View: JSP
JSP是动态执行文件,由Tomcat生成java servlet执行文件。jsp中的内容被放到 _jspService()
方法体的 try...catch
代码块里执行。一个JSP文件的例子如下所示:
status.jsp
1 | <li class="one"><a href="jsp/status.jsp">Home</a></li> |
那么,当前 Eureka Server 的 InstanceInfo 是如何获取的呢?
status.jsp
1 | 146 StatusInfo statusInfo = (new StatusUtil(serverContext)).getStatusInfo(); |
StatusUtil.java
1 | 29 this.instanceInfo = server.getApplicationInfoManager().getInfo(); |
ApplicationInfoManager.java
1 | 58 private static ApplicationInfoManager instance = new ApplicationInfoManager(null, null, null); |
调试后验证了,这里的instanceInfo一开始初始化是null,之后在BootStrap.java中才正式通过Builder初始化
@Deprecated
DiscoveryManager.java
1 | /** |
ApplicationInfoManager.java
1 | public void initComponent(EurekaInstanceConfig config) { |
EurekaBootStrap.java
1 | 161 EurekaInstanceConfig instanceConfig = isCloud(ConfigurationManager.getDeploymentContext()) |
EurekaConfigBasedInstanceInfoProvider.java
1 | builder.setNamespace(config.getNamespace()) |
于是我们在builder. 后面加入 .setAccountAddress(accountAddress)
在 InstanceInfo.java 中的 Builder 类中添加
1 | public Builder setAccountAddress(String accountAddress) { |
继续调试发现 EurekaBootStrap.java 这段代码速度很慢
1 | 214 // Copy registry from neighboring eureka node |
Comments
shortname
for Disqus. Please set it in_config.yml
.