SpringBoot系列(五)---- Web开发(二)

项目地址:
链接:https://pan.baidu.com/s/15qQUTPeQ4mpg59Q_RgA6bQ
提取码:re3p
复制这段内容后打开百度网盘手机App,操作更方便哦

国际化

编写国际化配置文件,在SpringBoot中使用ResouceBundleMessageSource管理国际化配置文件,如果在放在以前的SpringMVC中,我们使用了ResouceBundleMessageSource之后,需要在页面中使用fmt:message取出国际化配置文件,我们我们在SpringBoot中就当然不需要这样来写啦,在SpringBoot中怎么使用呢,具体步骤如下:

  • 在Resources目录下,创建一个i18n的包,然后创建三个国际化的properties配置文件
    在这里插入图片描述

  • 创建了三个国际化的properties配置文件之后,Idea会检测到我们是创建了国际化配置文件,会自动帮我们创建国际化配置文件视图。

  • 接下来我们随便点进一个国际化配置文件,这里我点击进入login.properties中,然后可以点击Resources Bundle进入,如下

在这里插入图片描述

  • SpringBoot自动配置好了管理国际化资源的文件的组件,即ResourceBundleMessageSource,所以我们只要在properties配置文件中启用指定国际化文件就可以了,配置如下
spring.messages.basename=i18n.login
  • 接下来去页面获取国际化的值,我们在HTML中使用Thymeleaf语法进行获取(这里贴出的是最后的完整代码,下面讲到什么我会截图框出来)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta name="description" content="">
	<meta name="author" content="">
	<title>Signin Template for Bootstrap</title>
	<!-- Bootstrap core CSS -->
	<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
	<!-- Custom styles for this template -->
	<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
	<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
	<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
	<!--判断-->
	<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
	<label class="sr-only" th:text="#{login.username}">Username</label>
	<input type="text"  name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
	<label class="sr-only" th:text="#{login.password}">Password</label>
	<input type="password" name="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
	<div class="checkbox mb-3">
		<label>
			<input type="checkbox" value="remember-me"/> [[#{login.remember}]]
		</label>
	</div>
	<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
	<p class="mt-5 mb-3 text-muted">©2021</p>
	<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
	<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>

在这里插入图片描述
如果出现了乱码,是因为properties默认是ASCII编码,我们Idea是UTF-8编码,所以会乱码,设置如下:

在这里插入图片描述
在这里插入图片描述

  • 编写MyMvcConfig
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        // super.addViewControllers(registry);
        //浏览器发送 /cz 请求来到 success
        registry.addViewController("/cz").setViewName("success");
    }

    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
    
    
        WebMvcConfigurer adapter = new WebMvcConfigurer() {
    
    
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
    
    
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.xml").setViewName("login");
                //下面这个是登陆的时候重定向的
                registry.addViewController("/main.html").setViewName("dashboard");
            }
        };
        return adapter;
    }
  • 这样就可以成功运行了,如果页面出现不能加载静态资源的情况,可以去看看我的这篇文章

  • 在我们已经设置好了国际化,怎么测试呢?根据浏览器语言设置的信息切换了国际化;项目会自动检测浏览器语言环境,然后更换,我这里使用Chrome举例,点开Chrome的设置->高级,然后更换,如下:
    在这里插入图片描述

为什么会自动检测呢?我们啥都没有配置,我这里简单的说一下按原理:
SpringBoot有一个国际化Locale(区域信息对象)以及一个LocaleResolver(获取区域信息对象),这个就是默认的根据请求头里面的,会根据请求头里面的Accept-language的值进行读取配置值。

  • 如果我们不想让浏览器自动检测,而是通过我们点击按钮进行更换语言。
    我们可以自己写一个实现LocaleResolver接口的类,我们就可以在链接上携带区域语言信息,不过要注意了,如果我们自己实现了LocaleResolver接口,默认的检测浏览器语言就不生效了,就算我们更换浏览器语言也没有用,我们自己编写的国际化解析器如下:
/**
 * 可以在连接上携带区域信息
 */
public class MyLocaleResolver implements LocaleResolver {
    
    
    
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
    
    
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
    
    
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
    

    }
}
  • 写完了之后记得在主配置文件MyMvcConfig中注册一下我们编写的国际化解析器组件
   @Bean
    public LocaleResolver localeResolver(){
    
    
        return new MyLocaleResolver();
    }
  • HTML的按钮发出相关请求,在请求后面带上标记属性,如下:
    在这里插入图片描述
    然后现在就可以重启测试了,我们点击按钮之后,就会在连接上出现属性值,然后更换语言http://localhost:8080/index.html?l=zh_CNhttp://localhost:8080/index.html?l=en_US

登录进入主页

  • 我们在登录页面的内容如下,有几个输入框,用来输入账号和密码的,然后我们写入之后发送请求,请求的接口是/user/login

在这里插入图片描述

  • 创建一个LoginCofig类:
@Controller
public class LoginController {
    
    

    @PostMapping(value = "/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String, Object> map){
    
    
        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
    
    
            //登陆成功,防止表单重复提交,可以重定向到主页
            return "redirect:/main.html";
        }else {
    
    
            //登陆失败
            map.put("msg","用户名密码错误");
            return "login";
        }
    }
}
  • 在开发中可能会遇到缓存影响我们刷新页面开发的情况,我们在可以在配置文件中将Thymeleaf的默认缓存给关掉
    在这里插入图片描述

  • 现在就可以重新启动我们的项目了,输入账号密码之后就可以进入到主页了
    在这里插入图片描述

拦截器进行登陆检查

  • 我们弄好了登录,这个时候就会想,如果我们不通过正常的登录,而是直接通过主页的连接进入到主页,这样子我们的登录界面还有什么意义呢?所以这里我们需要对所有请求进行拦截,写一个LoginHandlerInterceptor实现HandlerInterceptor的接口的拦截器
/**
 * @Author: zhang
 * @Descripetion: 拦截器进行登陆检查
 **/

public class LoginHandlerInterceptor implements HandlerInterceptor {
    
    

    //目标方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        //判断session中是否存在loginUser的值,没有的话跳转到登陆界面,有的话就放行
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null){
    
    
            //未登录,返回登陆界面
            request.setAttribute("msg","没有权限请先登陆!");
            request.getRequestDispatcher("index.html").forward(request,response);
            return false;
        }else {
    
    
            //已登录
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
    }
}

  • 编写了自己的拦截器之后呢,我们还是需要在主配置文件中进行注册我们的拦截器组件,顺便设置一些我们不需要进行拦截的请求路径
//注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
    
    
                //设置相关拦截
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.xml","/","/user/login");
            }

CRUD-员工列表

  • 用户列表的功能,我们可以显示用户的信息,然后进行增删改查的基本操作,如下:
    在这里插入图片描述

  • 所以我们需要创建Dao层和实体类,代码内容如下:


@Repository
public class DepartmentDao {
    
    

	private static Map<Integer, Department> departments = null;

	static{
    
    
		departments = new HashMap<Integer, Department>();

		departments.put(101, new Department(101, "D-AA"));
		departments.put(102, new Department(102, "D-BB"));
		departments.put(103, new Department(103, "D-CC"));
		departments.put(104, new Department(104, "D-DD"));
		departments.put(105, new Department(105, "D-EE"));
	}

	public Collection<Department> getDepartments(){
    
    
		return departments.values();
	}

	public Department getDepartment(Integer id){
    
    
		return departments.get(id);
	}

}

@Repository
public class EmployeeDao {
    
    

	private static Map<Integer, Employee> employees = null;

	@Autowired
	private DepartmentDao departmentDao;

	static{
    
    
		employees = new HashMap<Integer, Employee>();

		employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
		employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
		employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
		employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
		employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
	}

	private static Integer initId = 1006;

	public void save(Employee employee){
    
    
		if(employee.getId() == null){
    
    
			employee.setId(initId++);
		}

		employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
		employees.put(employee.getId(), employee);
	}

	//查询所有员工
	public Collection<Employee> getAll(){
    
    
		return employees.values();
	}

	public Employee get(Integer id){
    
    
		return employees.get(id);
	}

	public void delete(Integer id){
    
    
		employees.remove(id);
	}
}

@Controller
public class EmployeeController {
    
    
    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    //查询所有员工,返回列表页面
    // thymeleaf默认就会拼串
    // classpath:/templates/xxxx.html
    @GetMapping("/emps")
    public String list(Model model){
    
    
        Collection<Employee> employees = employeeDao.getAll();
        //放在请求域中
        model.addAttribute("emps",employees);
        return "emp/list";
    }
    //员工添加页面
    @GetMapping("/emp")
    public String toAddpage(Model model){
    
    
        //来到添加页面,查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    //员工添加功能
    @PostMapping("/emp")
    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定;
    // 要求请求参数的名字和javaBean入参的对象里面的属性名是一样的
    public String addEmp(Employee employee){
    
    
        //来到员工列表页面
        System.out.println("保存的员工信息:"+employee);
        //保存员工
        employeeDao.save(employee);
        // redirect: 表示重定向到一个地址  /代表当前项目路径
        // forward: 表示转发到一个地址
        return "redirect:/emps";
    }

    //来到修改页面,查出当前员工,在页面回显
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
    
    
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);
        //页面要显示所有的部门列表
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //回到修改页面(add是一个修改添加二合一的页面);
        return "emp/add";
    }
    //员工修改;需要提交员工id;
    @PutMapping("/emp")
    public String updateEmployee(Employee employee){
    
    
        System.out.println("修改的员工数据:"+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    //员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id){
    
    
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}

RestfulCRUD:CRUD满足Rest风格;
URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作

普通CRUD(uri来区分操作) RestfulCRUD
查询 getEmp emp—GET
添加 addEmp?xxx emp—POST
修改 updateEmp?id=xxx&xxx=xx emp/{id}—PUT
删除 deleteEmp?id=1 emp/{id}—DELETE

2)、实验的请求架构;

实验功能 请求URI 请求方式
查询所有员工 emps GET
查询某个员工(来到修改页面) emp/1 GET
来到添加页面 emp GET
添加员工 emp POST
来到修改页面(查出员工进行信息回显) emp/1 GET
修改员工 emp PUT
删除员工 emp/1 DELETE

thymeleaf公共页面元素抽取

1、抽取公共片段
<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名

3、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
  • 三种引入公共片段的th属性:

th:insert:将公共片段整个插入到声明引入的元素中

th:replace:将声明引入的元素替换为公共片段

th:include:将被引入的片段的内容包含进这个标签中

<footer th:fragment="copy">
&copy; hello 2021
</footer>

引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

效果
<div>
    <footer>
    &copy; hello 2021
    </footer>
</div>

<footer>
&copy; hello 2021
</footer>

<div>
&copy; hello 2021
</div>
  • 引入片段的时候传入参数:
    在这里插入图片描述

在这里插入图片描述

CRUD-员工添加

因篇幅问题,具体代码就不贴出来,说一下大概问题就好了,具体的可以去下载源码来看。

提交的数据格式不对:生日:日期;

2021-01-01;2021/01/01;2021.01.01;

日期的格式化;SpringMVC将页面提交的值需要转换为指定的类型;

2021-01-01—Date; 类型转换,格式化;

默认日期是按照/的方式;

  • 我们还是需要在主配置文件中设置日期格式的配置,如下
    在这里插入图片描述

CRUD-员工修改

  • HiddenHttpMethodFilter
    • SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
    • 页面创建一个post表单
    • 创建一个input项,name="_method";值就是我们指定的请求方式
      在这里插入图片描述
      在这里插入图片描述

路径虽然一样,但是处理的不同的请求方式

CRUD-员工删除

<tr th:each="emp:${emps}">
    <td th:text="${emp.id}"></td>
    <td>[[${emp.lastName}]]</td>
    <td th:text="${emp.email}"></td>
    <td th:text="${emp.gender}==0?'':''"></td>
    <td th:text="${emp.department.departmentName}"></td>
    <td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
    <td>
        <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
        <button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button>
    </td>
</tr>


<script>
    $(".deleteBtn").click(function(){
     
     
        //删除当前员工的
        $("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();
        return false;
    });
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43844418/article/details/114074423