今天给大家介绍一下spring boot mvc,让我们学习一下如何利用spring boot快速的搭建一个简单的web应用。
环境准备
1.一个称手的文本编辑器(例如vim、emacs、sublime text)或者ide(eclipse、idea intellij)
2.java环境(jdk 1.7或以上版本)
3.maven 3.0+(eclipse和idea intellij内置,如果使用ide并且不使用命令行工具可以不安装)
一个最简单的web应用
使用spring boot框架可以大大加速web应用的开发过程,首先在maven项目依赖中引入spring-boot-starter-web:
pom.xml
《?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》
《groupid》com.tianmaying《/groupid》
《artifactid》spring-web-demo《/artifactid》
《version》0.0.1-snapshot《/version》
《packaging》jar《/packaging》
《name》spring-web-demo《/name》
《description》demo project for spring webmvc《/description》
《parent》
《groupid》org.springframework.boot《/groupid》
《artifactid》spring-boot-starter-parent《/artifactid》
《version》1.2.5.release《/version》
《relativepath/》
《/parent》
《properties》
《project.build.sourceencoding》utf-8《/project.build.sourceencoding》
《java.version》1.8《/java.version》
《/properties》
《dependencies》
《dependency》
《groupid》org.springframework.boot《/groupid》
《artifactid》spring-boot-starter-web《/artifactid》
《/dependency》
《/dependencies》
《build》
《plugins》
《plugin》
《groupid》org.springframework.boot《/groupid》
《artifactid》spring-boot-maven-plugin《/artifactid》
《/plugin》
《/plugins》
《/build》
《/project》
接下来创建src/main/java/application.java:
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@springbootapplication
@restcontroller
public class application {
@requestmapping(“/”)
public string greeting() {
return “hello world!”;
}
public static void main(string[] args) {
springapplication.run(application.class, args);
}
}
运行应用:mvn spring-boot:run或在ide中运行main()方法,在浏览器中访问http://localhost:8080,hello world!就出现在了页面中。只用了区区十几行java代码,一个hello world应用就可以正确运行了,那么这段代码究竟做了什么呢?我们从程序的入口springapplication.run(application.class, args);开始分析:
springapplication是spring boot框架中描述spring应用的类,它的run()方法会创建一个spring应用上下文(application context)。另一方面它会扫描当前应用类路径上的依赖,例如本例中发现spring-webmvc(由 spring-boot-starter-web传递引入)在类路径中,那么spring boot会判断这是一个web应用,并启动一个内嵌的servlet容器(默认是tomcat)用于处理http请求。
spring webmvc框架会将servlet容器里收到的http请求根据路径分发给对应的@controller类进行处理,@restcontroller是一类特殊的@controller,它的返回值直接作为http response的body部分返回给浏览器。
@requestmapping注解表明该方法处理那些url对应的http请求,也就是我们常说的url路由(routing),请求的分发工作是有spring完成的。例如上面的代码中http://localhost:8080/根路径就被路由至greeting()方法进行处理。如果访问http://localhost:8080/hello,则会出现404 not found错误,因为我们并没有编写任何方法来处理/hello请求。
使用@controller实现url路由
现代web应用往往包括很多页面,不同的页面也对应着不同的url。对于不同的url,通常需要不同的方法进行处理并返回不同的内容。
匹配多个url
@restcontroller
public class application {
@requestmapping(“/”)
public string index() {
return “index page”;
}
@requestmapping(“/hello”)
public string hello() {
return “hello world!”;
}
}
@requestmapping可以注解@controller类:
@restcontroller
@requestmapping(“/classpath”)
public class application {
@requestmapping(“/methodpath”)
public string method() {
return “mapping url is /classpath/methodpath”;
}
}
method方法匹配的url是/classpath/methodpath“。
提示
可以定义多个@controller将不同url的处理方法分散在不同的类中
url中的变量——pathvariable
在web应用中url通常不是一成不变的,例如微博两个不同用户的个人主页对应两个不同的url:http://weibo.com/user1,http://weibo.com/user2。我们不可能对于每一个用户都编写一个被@requestmapping注解的方法来处理其请求,spring mvc提供了一套机制来处理这种情况:
@requestmapping(”/users/{username}“)
public string userprofile(@pathvariable(”username“) string username) {
return string.format(”user %s“, username);
}
@requestmapping(”/posts/{id}“)
public string post(@pathvariable(”id“) int id) {
return string.format(”post %d“, id);
}
在上述例子中,url中的变量可以用{variablename}来表示,同时在方法的参数中加上@pathvariable(”variablename“),那么当请求被转发给该方法处理时,对应的url中的变量会被自动赋值给被@pathvariable注解的参数(能够自动根据参数类型赋值,例如上例中的int)。
支持http方法
对于http请求除了其url,还需要注意它的方法(method)。例如我们在浏览器中访问一个页面通常是get方法,而表单的提交一般是post方法。@controller中的方法同样需要对其进行区分:
@requestmapping(value = ”/login“, method = requestmethod.get)
public string loginget() {
return ”login page“;
}
@requestmapping(value = ”/login“, method = requestmethod.post)
public string loginpost() {
return ”login post request“;
}
模板渲染
在之前所有的@requestmapping注解的方法中,返回值字符串都被直接传送到浏览器端并显示给用户。但是为了能够呈现更加丰富、美观的页面,我们需要将html代码返回给浏览器,浏览器再进行页面的渲染、显示。
一种很直观的方法是在处理请求的方法中,直接返回html代码,但是这样做的问题在于——一个复杂的页面html代码往往也非常复杂,并且嵌入在java代码中十分不利于维护。更好的做法是将页面的html代码写在模板文件中,渲染后再返回给用户。为了能够进行模板渲染,需要将@restcontroller改成@controller:
import org.springframework.ui.model;
@controller
public class hellocontroller {
@requestmapping(”/hello/{name}“)
public string hello(@pathvariable(”name“) string name, model model) {
model.addattribute(”name“, name);
return ”hello“
}
}
在上述例子中,返回值”hello“并非直接将字符串返回给浏览器,而是寻找名字为hello的模板进行渲染,我们使用thymeleaf模板引擎进行模板渲染,需要引入依赖:
《dependency》
《groupid》org.springframework.boot《/groupid》
《artifactid》spring-boot-starter-thymeleaf《/artifactid》
《/dependency》
接下来需要在默认的模板文件夹src/main/resources/templates/目录下添加一个模板文件hello.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》
th:text=”‘hello, ’ + ${name} + ‘!’“也就是将我们之前在@controller方法里添加至model的属性name进行渲染,并放入《p》标签中(因为th:text是《p》标签的属性)。模板渲染还有更多的用法,请参考thymeleaf官方文档。
处理静态文件
浏览器页面使用html作为描述语言,那么必然也脱离不了css以及javascript。为了能够浏览器能够正确加载类似/css/style.css, /js/main.js等资源,默认情况下我们只需要在src/main/resources/static目录下添加css/style.css和js/main.js文件后,spring mvc能够自动将他们发布,通过访问/css/style.css, /js/main.js也就可以正确加载这些资源。
输入输出接口的类型和功能特点
云栖大会人脸识别闸机【技术亮点篇3】--人脸识别闸机摆闸可达500万次
C51单片机串口的使用方法解析
微软鼠标走向人体工程学 带你赏析微软精准鼠标的ID设计
全球首款最轻的助行器,为行动不便的人士带来帮助
spring boot入门篇
农机蓄电池冬季如何防冻
国产AI芯片如何助力车路协同突破落地瓶颈?
循环队列在网络摄像头项目中处理多则消息的运用
Samsung Terrace推出一款智能电视,具有高端三星QLED电视所能提供的所有功能
物业小区高校水电抄表充值管理系统简介
很可能这就是诺基亚8将搭载骁龙835,但依然延迟
5G 不仅对消费者有利,物联网也将受益
i.MX6ULL|字符设备驱动流程深究
韩国正在接收40架F-35A战斗机
微雪电子M24LR-DISCOVERY开发板简介
具有快速瞬态响应的极低压差稳压电路
储能逆变器关键技术参数解读
格创东智出席《财富》中国500强峰会 助力企业实现高质量发展
如何在Microsoft Word中制作高质量的小册子