引言
Spring Boot其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。
通過這種方式,springboot是一個快速整合第三方框架的,簡化了xml的配置,項目中再也不包含web.xml文件了,完全使用注解來完成操作的,並且內部自帶tomcat啟動。直接使用jar文件運行即可。
好了大概了解了springboot有啥用處,本章節主要目的就是仿造一個springboot整合jsp的小實戰。下面開始代碼演示了。
1.導入相關依賴
創建項目之后需要引入tomcat,springmvc,spring-web,jsp相關的jar包。
代碼如下:
<!-- tomcat相關jar -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.34</version>
</dependency>
<!-- tomcat對jsp支持 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>8.5.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.10.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- springmvc相關jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.10.RELEASE</version>
<scope>compile</scope>
</dependency>
2.加載spring mvc的相關配置信息
需要創建一個springmvc相關配置類繼承WebMvcConfigurationSupport ,這里只配置一個springmvc視圖解析器。
代碼如下:
//表示這是一個配置類,配置<beans></beans>
@Configuration
//表示配置視圖解析器,開啟注解的相關配置,以及<bean></bean>等等。
@EnableWebMvc
//表示包掃描
@ComponentScan(basePackages = {"springboot.controller"})
public class WebConfig extends WebMvcConfigurationSupport {
/**
* 配置springMVC視圖解析器
*/
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//配置前綴
viewResolver.setPrefix("/WEB-INF/views/");
//配置后綴
viewResolver.setSuffix(".jsp");
//可以在jsp頁面中通過${}訪問beans
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}
}
@Configuration:表示這是一個配置類,配置<beans></beans>。
@EnableWebMvc:開啟注解的相關配置(配置視圖解析器,以及<bean></bean>)等等。
@ComponentScan:表示包掃描。
viewResolver.setExposeContextBeansAsAttributes(true):jsp頁面可以使用el表達式。
3.加載spring容器相關配置信息
創建一個SpringBeanScanConfig配置類,這個類主要是掃描service和dao層的,代碼如下:
//表示配置類
@Configuration
//如果寫了dao層,那么這里也需要掃描一下dao層
@ComponentScan("springboot.service")
public class SpringBeanScanConfig{
}
這個類目前什么都不需要做。
4.加載springMVC的dispatcherservlet
創建一個加載SpringMVC的DispatcherServlet的類。
代碼如下:
public class DispatcherServletWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 加載spring容器配置信息
* @return
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {Service_DaoConfig.class};
}
/**
* 加載springmvc配置信息
* @return
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
/**
* springmvc映射 攔截url所有請求"/"
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
解釋:
getRootConfigClasses():表示加載spring容器配置信息
getServletConfigClasses():表示加載springmvc配置信息
getServletMappings():表示springmvc映射 攔截url所有請求"/"
下面代碼就容易理解了。
5.service層
在service層創建一個IndexService業務類
代碼如下:
@Service
public class IndexService {
public String show() {
return "我是service層";
}
}
controller層
代碼如下:
@Controller
public class IndexContrller {
@Autowired
private IndexService indexService;
/**
* value:訪問地址
* produces:解決亂碼問題
* @return
*
*/
@RequestMapping(value = "/index1", produces = "text/html;charset=UTF-8")
@ResponseBody
public String index1() {
return "手寫springboot。。。";
}
@RequestMapping(value = "/index2", produces = "text/html;charset=UTF-8")
public String index2(Model model) {
String str = indexService.show();
model.addAttribute("str",str);//返回到jsp頁面顯示數據
return "springboot";
}
}
這里我們寫了2個方法,index1()方法是返回json字符串形式,index2是跳轉jsp頁面並且帶了一個str參數返回在jsp頁面顯示的。
7.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>springboot</title>
</head>
<body>
<h1>這是一個手寫的springboot框架</h1>
這里顯示后台返回的數據為:【${str}】
</body>
</html>
${str}:這個表示后台帶了一個str參數返回到jsp頁面的,值應該為【我是service層】
8.啟動類
這里就直接貼代碼了,注釋都寫在代碼中了。
代碼如下:
public class SpringBootApp {
public static void main(String[] args) throws LifecycleException, ServletException {
// 創建Tomcat容器對象
Tomcat tomcatServer = new Tomcat();
// 設置端口號
tomcatServer.setPort(8080);
// 讀取項目路徑 加載靜態資源
StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/", new File("src/main").getAbsolutePath());
// 禁止重新載入
ctx.setReloadable(false);
// class文件讀取地址
File additionWebInfClasses = new File("target/classes");
// 創建WebRoot
WebResourceRoot resources = new StandardRoot(ctx);
// tomcat內部讀取Class執行(/WEB-INF/classes虛擬出來的路勁)
resources.addPreResources(
new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
tomcatServer.start();
// 異步等待請求執行
tomcatServer.getServer().await();
}
}
9.測試結果
啟動程序看控制台顯示加載情況:
以上創建的Service_DaoConfig和WebConfig2個配置類都加載成功。
輸入地址:http://localhost:8080/index1顯示為:“手寫springboot。。。”
如圖:
輸入地址:http://localhost:8080/index2顯示為:“這是一個手寫的springboot框架 這里顯示后台返回的數據為:【我是service層】”
如圖:
總結
springboot主要特點為:
1. 創建獨立的Spring應用程序
2. 嵌入的Tomcat,無需部署WAR文件
3. 簡化Maven配置
4. 自動配置Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6. 絕對沒有代碼生成並且對XML也沒有配置要求