SpringBoot Web开发(基于狂神)
在springboot的自动装配后进行web开发,
要解决的问题:
- 静态资源导入
- 首页定制
- JSP,模版引擎
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 中英文切换
静态资源导入
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());// 能访问./下的所有请求
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
以上是静态资源导入的java源码,解释了如何导入静态资源
结论:当你自定义资源路径后,默认路径失效,否者启动默认路径.
默认路径:在resources下面的静态资源都能够被访问,且相关同级资源的访问级别是resources文件夹下的最高,static其次,最后是public
在springboot中默认访问静态资源的路径有:
- webjars:localhost:8080/webjars/
- public,static,resources,/**:localhost:8080/
优先级:resources>static(默认)>public
首页
做一个名为index.html的文件,放入静态资源目录下即可实现首页.
如果需要中英文切换,要利用localeResolver类,我们可以写一个对应的类继承其方法,重写方法实现转变,放入容器中即可
thymeleaf模版引擎
thymeleaf是可以代替jsp的前端语句.
使用thymeleaf:导入对应的启动类.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
将html页面放入到template文件下即可使用
原因如下:
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
所有的html元素都可以被thymeleaf接管,前端可以获取到后端的数据,举例如图:
@Controller
public class HelloController {
@GetMapping("/test")
public String hello(Model model){
model.addAttribute("msg","aaaaa");
model.addAttribute("msg1","<h1>转义</h1>");
model.addAttribute("users", Arrays.asList("元素1","元素2"));
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
<div th:utext="${msg1}"></div>
<div th:utext="${msg}"></div>
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>
重写WebMvcConfig,配置springMVC
自己写了一个视图解析器,并交给bean(springboot)
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver MyViewResolver(){
return new MyViewResolver();
}
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}
结论:要扩展springMVC,在类名前加@Configuration注解.
在springboot中,有很多xxxConfiguration(用于扩展配置的),
在源码中出现了这种类,那么就要注意扩展了那些类.
理解:
继承了WebMvcConfigurer和有注解@Configuration的类属于springboot框架添加功能的地方,也是我们在springboot框架上实现业务的地方.比如你自己单独实现了直接的视图解析器,访问过滤器,区域解析器都可以在这个类上添加.
业务实现
1.登录和注销
@Controller
public class LoginController {
@RequestMapping("/user/login")
//@ResponseBody
public String login(@RequestParam("username") String username, @RequestParam("password") String password
, Model model, HttpSession session){
if(!StringUtils.isEmpty(username) && "123".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","no");
return "index";
}
}
@RequestMapping("/user/loogout")
public String logout(HttpSession session){
session.invalidate();
return "index";
}
}
2.拦截器
自己写一个拦截器(实现springboot提供的接口)
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录后的session
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser ==null){
request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
再将其放入WebMvcConfigurer类中,并配置拦截范围
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
}
3.中英切换
自己写一个地区解析器,用于从前端获取数据,处理后返回一个地区对象
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名
public class MyLoacleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request){
String language = request.getParameter("l");
Locale locale = Locale.getDefault();
//如果请求链接,携带l,就取出
if(!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);//参数为语言,国家
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
然后在WebMvcConfigurer类中添加此类,并注入容器
@Bean
public LocaleResolver localeResolver(){
return new MyLoacleResolver();
}
全部的WebMvcConfigurer类代码:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/main.html").setViewName("dashboard");
registry.addViewController("/toAdd").setViewName("emp/add");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLoacleResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
}
}
4.登录成功后页面展示
@RequestMapping("/user/login")
//@ResponseBody
public String login(@RequestParam("username") String username, @RequestParam("password") String password
, Model model, HttpSession session){
if(!StringUtils.isEmpty(username) && "123".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","no");
return "index";
}
}
5.员工列表跳转及显示
@RequestMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
6.员工添加
@GetMapping("/emp")
public String toAddPage(Model model){
Collection<Department> departments = departmentDao.getDepartment();
model.addAttribute("departments",departments);
return "emp/add";
}
@PostMapping("/emp")
public String addEmp(Employee employee){
//添加操作
employeeDao.save(employee);//保存员工信息
System.out.println(employee);
return "redirect:/emps";
}
7.员工修改
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
Employee employee = employeeDao.getEmployeeById(id);
model.addAttribute("emp",employee);
Collection<Department> departments = departmentDao.getDepartment();
model.addAttribute("departments",departments);
return "emp/update";
}
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeDao.save(employee);
System.out.println(employee);
return "redirect:/emps";
}
8.员工删除
@RequestMapping("/del/{id}")
public String deleteEmp(@PathVariable("id")Integer id){
System.out.println("delete:"+id);
employeeDao.delete(id);
System.out.println("delete:"+id);
return "redirect:/emps";
}