该登录页面的实现主要用到了SpringBoot的静态资源访问、国际化、thymeleaf模板引擎、
登录拦截器、SpringBoot与Swagger整合、SpringBoot与Mybatis整合访问数据库。
关于SpringBoot与Mybatis整合
的请查看这篇:SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】)
下面主要介绍的是:关于登录页面的一些实现过程。
一、登录页面的访问。(templates/login.html)
方法一:
@Controller
public class LoginController {
@RequestMapping(value = {
"/login","/"})
public String login(){
return "login";
}
}
都会访问到:templates/login.html页面
方法二:
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("login").setViewName("login");
registry.addViewController("login.html").setViewName("login");
}
};
return adapter;
}
另外还可以在配置文件中配置访问项目的名称:
#配置项目的访问名
server.servlet.context-path=/blog
进行上面的配置后,这样访问登录页面:
http://127.0.0.1:8081/blog/login.html
二、国际化配置。
创建国际化配置文件:
查看源码发现SpringBoot已经自动配置了管理国际化资源文件的组件:(MessageSourceAutoConfiguration.java)
注:我们需要配置指定读取国际化配置文件的路径:
#配置读取国际化配置文件的路径
spring.messages.basename=i18n.login
运行测试效果:
(中文状态)
浏览器切换成英文状态:
实现的原理:
SpringBoot 配置了默认的 LocalResolve(获取区域信息对象)
,我们可以查看代码:
WebMvcAutoConfiguration.java
根据请求头带来的区域信息获取Locale(区域信息对象)
进行国际化:
用点击链接的方式来实现中英文切换主要实现代码:
public class MyLocaleResolver implements LocaleResolver {
//解析区域信息
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String param = httpServletRequest.getParameter("param");
Locale local = Locale.getDefault();
if (!StringUtils.isEmpty(param)) {
String[] split = param.split("_");
//split[0] 语言信息 split[1]国家信息
local = new Locale(split[0],split[1]);
}
return local;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
在配置类中添加该组件(注意:方法的名字必须为localeResolver)。
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
登录拦截器主要实现代码:
创建类LoginHandlerInterceptor.java
并且实现HandlerInterceptor接口
,重写preHandle、postHandle、afterCompletion方法。
public class LoginHandlerInterceptor implements HandlerInterceptor {
/**
* 方法执行之前
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String username = (String) request.getSession().getAttribute("loginAfterName");
if (username!= null) {
//登录
return true;
}
request.setAttribute("resultMsg", "没有权限");
request.getRequestDispatcher("/login.html").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@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 {
}
在自定义配置类中添加addInterceptors方法:注册拦截器,把自己写好的拦截器需要通过这里添加注册才能生效。
@Override
public void addInterceptors(InterceptorRegistry registry) {
// /**:拦截所有请求;除了/ 、login、/user/login请求
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/login.html","/user/login", "/**/*.css", "/**/*.js", "/**/*.png",
"/**/*.jpg","/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg","/**/*.ico","/**/*.map","/swagger-resources/**","/swagger-ui.html/**");
}
进行测试:登录成功后地址为:http://127.0.0.1:8082/blog/main.html
在没有登录的情况下,访问:
Spring Boot整合 Swagger2 展现在线用户登录接口文档
Swagger官网:https://swagger.io/
整合步骤:
(1)引入jar包:
<!--引入Swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
(2)创建Swagger配置类。Spring Boot 中对 Swagger2 的配置非常方便,新建一个配置类,Swagger2 的配置类上除了添加必要的 @Configuration 注解外,还需要添加 @EnableSwagger2 注解。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger2构建api文档")
.description("API 描述")
.termsOfServiceUrl("http://www.baidu.com")
.version("1.0")
.build();
}
}
注意:由于前面使用了拦截器,要对swagger进行放行操作:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/login.html","/user/login", "/**/*.css", "/**/*.js", "/**/*.png",
"/**/*.jpg","/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg","/**/*.ico","/**/*.map","/swagger-resources/**","/swagger-ui.html/**");
}
// 重写addResourceHandlers方法映射文件路径,使能够访问静态资源
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
(3)在UserController类中使用相关注解
@Api(value = "UserController",description = "用户接口")
@Controller
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "用户登录", notes = "用户登录接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String"),
@ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String")
})
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public String login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session){
Map<String,Object> map = new HashMap<String,Object>();
User resultUser = userService.selectByName(username);
if (null ==resultUser) {
model.addAttribute("resultMsg", "该用户还没注册");
return "login";
}
if (!resultUser.getPassWord().equals(Md5Util.MD5(password))) {
model.addAttribute("resultMsg","密码错误,重新输入");
return "login";
}else {
session.setAttribute("loginAfterName", username);
return "redirect:/index.html";
}
}
}
(4)进行测试配置有没有生效,启动项目,在浏览器中输入http://127.0.0.1:8080/blog/swagger-ui.html
若文章中有错误的地方欢迎大家反馈或者留言,十分感谢!!!