在接收到HTTP请求后,DispatcherServlet会查询HandlerMapping
以调用相应的Controller接受请求并根据使用的GET(@GetMapping("/greeting"))调用方法
基于定义的业务逻辑设置模型数据,并将视图名称返回给DispatcherServlet
DispatcherServlet将从ViewResolver获取请求的定义视图,将模型数据传递到最终的视图,并在浏览器上呈现
控制器
@Controller //HTTP请求由控制器@Controller处理
public class GreetingController {
@GetMapping("/greeting")//该@GetMapping将HTTP GET请求/greeting映射到该greeting()方法
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);//@RequestParam将查询字符串参数的值绑定Model对象name
return "greeting";
}
视图
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'Hello, ' + ${name} + '!'" /> //th:text表达式以呈现${name}在控制器中设置的参数值
</body>
入口
@SpringBootApplication
//相当于:
//@Configuration//可理解为xml里面的<beans>标签
//@EnableAutoConfiguration //告诉Spring Boot添加基于类路径设置,各种属性设置的bean
//@EnableWebMvc//在类路径中看到spring-webmvc时自动添加它
//@ComponentScan//找到@Controller
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
//要配合使用才不会访问html的时候提示404,Thymeleaf类似JSP,能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
@RequestMapping("/addlogin")
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
老的SpringMVC
访问首页流程:访问localhost:8080/project/index.html
--->web.xml中名为的baobaotao的servlet截获
---->转到baobaotao-servlet.xml
--->com.baobaotao.web的loginController类,方法有注明@RequestMapping(value="/index.html")
---->匹配返回"login"
---->baobaotao-servlet.xml跳转到WEB-INF/jsp/login.jsp(表单提交页面,登录页面)
表单提交(登录)流程:输入用户名密码,点击登录
--->因为表单的action设为loginCheck.html
---->com.baobaotao.web的loginController类的loginCheck方法有注明@RequestMapping(value="/loginCheck.html")
---->方法返回"main"
--->baobaotao-servlet.xml跳转到WEB-INF/jsp/main.jsp(主页面)
web.xml
加载ApplicationContext.xml
<servlet-mapping> 相关-servlet.xml 必须在web-inf下提供
loginController类: 被SpringMVC自己的配置文件扫描
@Controller
@RequestMapping(value=/"index.html")