war打包方式,添加web组件
添加web组件后,出现了ServletInitializer这个类,
package com.cxy;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(LessonjspApplication.class);
}
}
它继承了SpringBootServletInitializer这个父类,而SpringBootServletInitializer这个类是springboot提供的web程序初始化的入口,当我们使用外部容器(比如使用外部tomcat运行项目)运行项目时会自动加载并且装配。
实现了SpringBootServletInitializer的子类需要重写一个configure方法,方法内自动根据xxxxApplication.class的类型创建一个SpringApplicationBuilder交付给springboot框架来完成初始化运行配置。
2.pom中添加jsp,servlet容器,jstl标签的支持
springboot内部集成了tomcat组件,这里我们就不需要重复引入tomcat组件。
<!-- servlet依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- tomcat的支持.-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
3.配置视图
1. 在main目录下创建webapp文件夹
2. 在webapp下创建jsp文件夹,以及jsp
3. 修改application.properties文件让springmvc支持视图的跳转,配置preffix以及suffix路径转发规则,
目录指向为/main/webapp/jsp,
spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsp/
4.controller层
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello(Model m) {
m.addAttribute("now", DateFormat.getDateTimeInstance().format(new Date()));
return "hello";
}
}
可以看到上图我们在MyController配置文件内添加了hello()方法配置了@RequestMapping注解来描述hello()方法是一个可以被springmvc管理的请求视图。我们的hello()方法返回值这里是"hello"。
为什么我们返回"hello",还记得上述步骤中配置的application.properties文件的springmvc请求前缀以及后缀,那么当我们访问 /hello 时springmvc就会去找/webapp/WEB-INF/jsp/hello.jsp文件。