使用springboot进行web项目开发1(含数据库连接,国际化,登录控制,拦截器)
springboot-web项目的开发过程
该项目使用了thymeleaf模板引擎,整合了mybatis,实现了CRUD,权限控制(拦截器)
1.准备工作
- 创建spring boot项目,在resources目录下的static目录下导入静态资源css,js,img
在resources目录下的templates目录下导入静态资源xxx.html
- 项目中使用了bootstrap的模板
2.连接数据库
pom文件中引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
在主配置文件application.properties文件中配置相关参数
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc
//localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
注意:serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8,需要添加时间地区和编码方式
- 启动idea的mysql连接,选择schemas(要使用到的数据库表),若连接失败,在advanced中配置serverTimezone=UTC
3.国际化(i18n)
页面支持中英文切换
pom.xml中引入thymeleaf引擎依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
在resources创建i18n目录,在该目录下创建login.properties
- 创建login_en_US.properties
- 创建login_zh_CN.properties
点击login.properties文件,点击下方的 Resource Bundle,然后页面内容进行中英文匹配
在主配置文件application.properties文件中配置i18n的配置
spring.thymeleaf.cache=false
spring.messages.basename=i18n.login
关闭thymeleaf引擎的缓存,设置国际化信息的来源为i18n目录下的login
依照thymeleaf语法修改index中的相关代码
<!DOCTYPE html>
<html lang="en_US" 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 th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
<img class="mb-4" th:src="@{/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>
<!--如果msg的值不为空才显示这个消息-->
<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" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" 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">[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</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>
小结:
- 引入thymeleaf的命名空间
根据thymeleaf的语法规则对原有的html代码进行修改
链接使用@
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
文本信息使用#
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
if等使用$
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
自定义mvcconfig
package com.cai.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.yaml.snakeyaml.events.Event;
import java.util.Locale;
@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");
}
@Bean
public LocaleResolver localeResolver(){
return new LocaleConfig();
}
}
自定义localeconfig
package com.cai.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class LocaleConfig implements LocaleResolver{
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l= httpServletRequest.getParameter("l");
//System.out.println("debug====================>"+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 httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
国际化总结:
国际化其实就是对原有页面中的内容进行中英文替换。在点击中文,英文切换时,携带参数传递给自定义的localeconfig,判断显示中文还是英文页面,然后将localeconfig注入到mvcconfig当中。当页面接收到显示中文或英文时,会通过th:text=”#{login.tip}“进行显示。
4.登录控制
输入用户名密码访问
编写logincontroller,接收index.html页面传来的账号和密码,进行判断
package com.cai.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;
import javax.lang.model.element.NestingKind;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/user/login")
//@Responsebody这个注解的作用是返回一个json格式
//@ResponseBody
//为了防止出现不必要的错误,需要加requestparam来保证参数的准确
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) {
//具体的业务
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
session.setAttribute("loginUser",username);
//登录成功的话重定向到main.html,隐藏用户名和密码
return "redirect:/main.html";
} else {
//登录失败的话,告诉用户登录失败,返回index页面
model.addAttribute("msg", "用户名或者密码错误");
return "index";
}
}
//注销
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();
return "redirect:/index.html";
}
}
2. 将判断结果返回给html页面进行显示,成功则进入,不成功则显示提示信息(index.html部分代码,完整代码同上)
<form class="form-signin" th:action="@{/user/login}">
<!--如果msg的值不为空才显示这个消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
通过页面路径访问需要拦截
自定义一个拦截器LoginHandlerinterceptor
package com.cai.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** * @BelongsProject:IntelliJ IDEA * @Package:com.cai.config * @Author:superman * @CreateTime:2021--01--14 10:58 * @Description:登录拦截器 */
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;
}
}
}
在自定义的mvcconfig配置拦截器,放行静态资源和首页
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerinterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
}
还没有评论,来说两句吧...