springboot整合thymeleaf实现简单的登录功能-拦截器(一)

Thymeleaf是什么

Thymeleaf是用于Web和独立环境的现代服务器端Java模板引擎。Thymeleaf的主要目标是将优雅的自然模板带到您的开发工作流程中—HTML能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。

 

Thymeleaf简单入门

1、首先我们创建一个springboot项目,添加依赖

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个路径是可以自定义的,Thymeleaf的页面文件后缀是.html

2、新建模板

我们在src/main/resources/templates目录下新建一个html文档。

demo.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>thymeleaf demo</title>
</head>
<body>
<h7 th:text="${name}"/>
<h7>demo页面</h7>
</body>
</html>

3、创建一个controller

创建一个Controller对象,用于传递需要展示的参数

@RequestMapping(value = "/demo")
public ModelAndView demo(ModelAndView mv) {
	mv.addObject("name", 123);
	mv.setViewName("demo");
	return mv;
}

4、访问 http://localhost:8080/demo

这篇博客做了详细介绍:

https://www.jianshu.com/p/a842e5b5012e

 

简单的登录功能

1、controller层实现页面跳转,LoginController.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
	
	@RequestMapping(value = "/login")
	public ModelAndView login(ModelAndView mv) {
	    mv.setViewName("login");
	    return mv;
	}
	
	@RequestMapping(value = "/index")
	public ModelAndView index(ModelAndView mv) {
	    mv.setViewName("index");
	    return mv;
	}
	
	@RequestMapping(value = "/submit")
	public ModelAndView submit(@RequestParam("username") String username,
            @RequestParam("password") String password,HttpServletRequest request,ModelAndView mv) {
		HttpSession sessoin = request.getSession();
		if("user".equals(username) && "123".equals(password)){
			sessoin.setAttribute("loginUser", username);
			mv.setViewName("index");
		    mv.addObject("name","登录成功");
		}else{
			mv.setViewName("login");
			mv.addObject("name","登录失败,请检查用户名密码");
		}
	    return mv;
	}
}

2、添加拦截器 LoginHandlerInterceptor.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class LoginHandlerInterceptor implements HandlerInterceptor {
    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        // 如果获取的request的session中的loginUser参数为空(未登录),就返回登录页,否则放行访问
        if (user == null) {
            // 未登录,给出错误信息,
            request.setAttribute("name","无权限请先登录");
            // 获取request返回页面到登录页
            request.getRequestDispatcher("/login").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 {

    }
}

3、添加拦截器配置  WebConfig.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import cn.tit.interceptor.LoginHandlerInterceptor;


@Configuration
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{
    
    @SuppressWarnings("unused")
	private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截的请求,并排除几个不拦截的请求
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                 .excludePathPatterns("/login","/submit","/demo");
    }
    
}

4、添加页面

login.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>thymeleaf demo</title>
</head>
<body>
<h7 th:text="${name}"/>
<form action="submit" method="post" onsubmit="return beforeSubmit()">
    ID:<input id="username" type="text" name="username" />
    Password:<input id="password" type="password" name="password" />
    <input type="submit" value="Submit" />
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>index page</title>
</head>
<body>
<h7 th:text="${name}"/>
<h7>主页面</h7>
</body>
</html>

5、测试

直接访问页面被拦截

输入用户名密码错误提示

登录成功

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值