Springboot初始配置
1.主程序代替了原先的Tomcat的作用
@SpringBootApplication
public class SpringbootWeb01Application
{
public static void main(String[] args)
{
SpringApplication.run(SpringbootWeb01Application.class, args);
}
}
2.对springboot的配置可以在resources下的application.properties里可以更改,比如加入server.port=8081
就是把端口改为8081.
SpringBoot注解
1.返回的一般是json数据,所以一般返回的是字符串而不是跳转页面,要在方法或类前加上@ResponseBody
才返回的是字符串。
2.@RestController
是@ResponseBody
和@Controller
的合写,加在controller类上面。
3.resources下的static,templates等是静态资源的存放处。
4.@PostMapping
即为@RequestMapping(method=RequestMethod.POST)
,同理还有@GetMapping
,@PutMapping
,@DeleteMapping
。
SpringBoot拦截器
1.和SpringMvc一样,SpringBoot可以通过配置类和注解@Configuration
的方式进行mvc的配置。
2.和SpringMVC不同的是,Springboot无需xml,所以拦截器直接可以在@Configuration
下的类进行配置。
该配置类可直接实现WebMvcConfigurer
接口,再实现其中方法。
3.拦截器类的编写,只要该类实现HandlerInterceptor
接口,再实现其中preHandle
,postHandle
,afterCompletion
方法即可。其具体写的方法见SpringMVC。
4.写完了拦截器类若不配置那么它只是一个普通的类,还需在配置类中进行配置,如下:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer
{
//添加拦截器的方法
@Override
public void addInterceptors(InterceptorRegistry registry)
{
// addInterceptor内写你已经写好的拦截器类
// addPathPatterns是对哪些请求使用拦截器
// excludePathPatterns是哪些页面不用拦截器
registry.addInterceptor(new LoginHandlerInterceptor()).
addPathPatterns("/**").
excludePathPatterns("/index.html","/user/login","/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
// 浏览器发送的/请求将被视为index请求
registry.addViewController("/").setViewName("index");
// 浏览器发送的/main.html将被视为dashboard请求
registry.addViewController("/main.html").setViewName("dashboard");
}
}