SpringBoot采坑指南
没耐心学ssh,ssm,只是粗略的过了一遍。很早就听闻了springboot的强大,今日,终于迎来了实战
prom.xml配置
springboot自带dependency:
1
2
3
4
5
6
7
8
9
10
| <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
|
此处配置我们需要用到的依赖
1
2
3
4
5
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
|
1
2
3
4
5
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
|
静态文件目录结构
thymeleaf语法的应用
thymeleaf提供 StringUtils 工具集,有点好用
Controller使用
- springboot提供 @PostMapping(value = “) 等方式代替 @Mapping
springMVC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| //@EnableWebMvc 完全接管
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
}
@Bean
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer config = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/user/login").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//已经做好了静态界面拦截
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/asserts/**"); //还需要放行静态文件
}
};
return config;
}
}
|
拦截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//登录状态拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor{
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if (user == null){
//未登录
request.setAttribute("msg","没有权限请先登录");
request.getRequestDispatcher("/").forward(request,response);
return false;
}else{
//已登录
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
|