SpringBoot总结(⼗⼆)——登录界⾯的实现
该登录页⾯的实现主要⽤到了SpringBoot的静态资源访问、国际化、thymeleaf模板引擎、
登录、SpringBoot与Swagger整合、SpringBoot与Mybatis整合访问数据库。
关于SpringBoot与Mybatis整合的请查看这篇:
下⾯主要介绍的是:关于登录页⾯的⼀些实现过程。
⼀、登录页⾯的访问。(templates/login.html)
⽅法⼀:
@Controller
public class LoginController {
@RequestMapping(value ={"/login","/"})
public String login(){
return"login";
}
}
都会访问到:templates/login.html页⾯
127.0.0.1:8081/login
127.0.0.1:8081/
⽅法⼆:
@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;
}
另外还可以在配置⽂件中配置访问项⽬的名称:
#配置项⽬的访问名
t-path=/blog
进⾏上⾯的配置后,这样访问登录页⾯:
127.0.0.1:8081/blog/login.html
⼆、国际化配置。
创建国际化配置⽂件:
login.properties
login_en_US.properties
login_zh_CN.properties
配置内容如下:
查看源码发现SpringBoot已经⾃动配置了管理国际化资源⽂件的组件:(MessageSourceAutoConfiguration.java)
注:我们需要配置指定读取国际化配置⽂件的路径:
#配置读取国际化配置⽂件的路径
接下来,在login.html页⾯中进⾏获取国际化的值。
运⾏测试效果:
(中⽂状态)
浏览器切换成英⽂状态:
实现的原理:
SpringBoot 配置了默认的 LocalResolve(获取区域信息对象),我们可以查看代码:
WebMvcAutoConfiguration.java
根据请求头带来的区域信息获取Locale(区域信息对象)进⾏国际化:
⽤点击链接的⽅式来实现中英⽂切换主要实现代码:
public class MyLocaleResolver implements LocaleResolver {
//解析区域信息
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest){
String param = Parameter("param");
Locale local = Default();
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) Session().getAttribute("loginAfterName");
if(username!= null){//登录
return true;
}
request.setAttribute("resultMsg","没有权限");
}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/**");
}
<!--引⼊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("ller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("springboot利⽤swagger2构建api⽂档")
.
description("API 描述")
.termsOfServiceUrl("www.baidu")
.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(!PassWord().equals(Md5Util.MD5(password))){
model.addAttribute("resultMsg","密码错误,重新输⼊");
return"login";
}else{
session.setAttribute("loginAfterName", username);
springboot中文return"redirect:/index.html";
}
}
}
若⽂章中有错误的地⽅欢迎⼤家反馈或者留⾔,⼗分感谢

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。