springboot系列(一):初次使用與登入驗證實現
寫在前面:不逼自己一把,都不知道自己還有裝逼的潛能!
聽說過很多springboot如何流行,以及如何簡化了我們的應用開發,卻沒有真正使用過springboot,現在終於要動手了!打算自己動手的這個專案,結果不會是促成某個真正的專案,學習為主,把學習過程分享出來。開篇探索以以下兩個方面為主:
1、從mvc經典框架到springboot
2、最原始的方式實現登入驗證
一、建一個使用springboot的專案
springboot是建立在的spring生態的基礎上的,以前看spring的時候,有兩大概念是糾結了很久的,IOC(控制反轉)以及AOP(面向切面的程式設計)。其實控制反轉就是依賴注入,spring提供了一個IOC容器來初始化物件,解決物件間依賴管理和物件的使用,如@Bean、@Autowired等可以實現依賴注入,AOP目前理解是在一些日誌框架場景中用到。
平時我們常見的web專案開發,使用的mvc框架、maven管理在springboot依然使用到,springboot最明顯的好處是簡化了新建一個專案時的各種配置過程,就連tomcat都不用配置了。可以看到我新建一個maven專案大目錄結構是這樣的
跟著上圖目錄結構,我們來看看springboot是如何完成一個普通的web專案所需要做的事的
a.web容器:springboot內嵌了Tomcat,我們不需要手動配置tomcat以及以war包形式部署專案,啟動入口為目錄中App.java中的main函式,直接執行即可。
@SpringBootApplicationpublic class App {b.依賴管理:spring提供了一系列的starter pom來簡化Maven的依賴載入,如一個web專案pom.xm部分配置如下:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <dependencies> <!--Spring Boot的核心啟動器,包含了自動配置、日誌和YAML--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--支援全棧式Web開發,包括Tomcat和spring-webmvc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
c.配置管理:目錄中src/main/resource/application.properties為配置檔案,springboot可以自動讀取,或者使用java配置可以看到沒有web.xm,沒有spring相關的配置檔案,整個專案看起來非常的簡潔。
#資料庫配置 spring.datasource.url=jdbc:mysql://localhost:3306/world?characterEncoding=UTF-8&useUnicode=true spring.datasource.username=darren spring.datasource.password=darren123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update一個springboot web專案大概就包含這些
二、原始方式實現登入驗證
流程為:登入頁面發起請求-->攔截器攔截匹配的url判斷session-->後臺驗證/設定session-->返回
a、這裡主要通過自定義攔截器的方式,繼承WebMvcConfigurerAdapter和HandlerInterceptorAdapter來實現攔截器對登入請求進行攔截和session的判斷,我這裡都寫在WebSecurityConfig.java中
其中WebMvcConfigurerAdapter是Spring提供的基礎類,可以通過重寫 addInterceptors 方法添加註冊攔截器來組成一個攔截鏈,以及用於新增攔截規則和排除不用的攔截,如下:
public void addInterceptors(InterceptorRegistry registry){ InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); addInterceptor.excludePathPatterns("/error"); addInterceptor.excludePathPatterns("/login**"); addInterceptor.addPathPatterns("/**"); }
其中HandlerInterceptorAdapter是spring mvc提供的介面卡,繼承此類,可以非常方便的實現自己的攔截器,它有三個方法:preHandle、postHandle、afterCompletion。preHandle在業務處理器處理請求之前被呼叫。預處理,可以進行編碼、安全控制等處理;postHandle在業務處理器處理請求執行完成後,生成檢視之前執行。afterCompletion在DispatcherServlet完全處理完請求後被呼叫,可用於清理資源等。我專案中只重寫了preHandle,對請求進行session判斷和跳轉到自定義的頁面,如下:
private class SecurityInterceptor extends HandlerInterceptorAdapter{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException { HttpSession session = request.getSession(); // 判斷是否已有該使用者登入的session if(session.getAttribute(SESSION_KEY) != null){ return true; } // 跳轉到登入頁 String url = "/login"; response.sendRedirect(url); return false; } }b.controller中對登入請求進行驗證以及頁面的跳轉,如下
@Controller public class LoginController { @Autowired private LoginService loginService; @GetMapping("/") public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY)String account,Model model){ return "index"; } @GetMapping("/login") public String login(){ return "login"; } @PostMapping("/loginVerify") public String loginVerify(String username,String password,HttpSession session){ User user = new User(); user.setUsername(username); user.setPassword(password); boolean verify = loginService.verifyLogin(user); if (verify) { session.setAttribute(WebSecurityConfig.SESSION_KEY, username); return "index"; } else { return "redirect:/login"; } } @GetMapping("/logout") public String logout(HttpSession session){ session.removeAttribute(WebSecurityConfig.SESSION_KEY); return "redirect:/login"; }controller程式碼解釋:loginVerify是對登入請求到資料庫中進行驗證使用者名稱和密碼,驗證通過以後設定session,否則跳轉到登入頁面。@GetMapping是一個組合註解,是@RequestMapping(method = RequestMethod.GET)的縮寫,@PostMapping同理。
ps:實際專案登入驗證會使用登入驗證框架:spring security 、shiro等,以及登入過程密碼加密傳輸儲存等,這裡僅僅用於瞭解。