- @Controller
- public class LoginController {
-
- @RequestMapping("/login")
- public String Login(String username, String password, HttpServletResponse response){
-
- System.out.println(username);
- System.out.println(password);
-
- //判断账号密码 假数据
- if("mike".equals(username)&&"123".equals(password)){
- //从数据库里查出来的user信息
- User user = new User();
- user.setId(1);
- user.setName(username);
- user.setAge(20);
- user.setGender("男");
- user.setPassword("123");
-
- //转换user转换成JSON 字符串
- String value = JSON.toJSONString(user);
-
- RedisUtil.set(username,value);//将登录用户的信息存在redis中 key是用户名,value是登录对象
-
- //新建cookie 把用户名存进去
- Cookie cookie = new Cookie("LoginUser", username);
-
- response.addCookie(cookie);//将cookie从服务端发送给客户端浏览器保存
- return "ok";
- }else{
-
- return "redirect:/lg.html";
-
- }
-
-
-
- }
-
- }
- public class LoginInterceptor implements HandlerInterceptor {
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-
- //查到所有cookie
- Cookie[] cookies = request.getCookies();
- boolean flag=true;
- //遍历cookie 如果有 LoginUser 的 cookie的key
- for (Cookie cookie : cookies) {
- if("LoginUser".equals(cookie.getName())){
-
- //获得这个cookie值,在redis里面查询
- String key = cookie.getValue();
-
- //通过username查询到 user类
- User user = RedisUtil.getUser(key);
-
- //如果有这个user类 说明登录过了
- if(user!=null){//已经登录过了
- flag=false;
- return true;
-
- }
-
- }
- }
- if (flag){//如果flag等于true 去登录页面
-
- response.sendRedirect("lg.html");
- }
- return false;
- }
- }

- public class RedisUtil {
-
- public static void set(String key,String value){
-
- Jedis jedis = new Jedis("192.168.59.12",6379);
-
- jedis.set(key,value);
-
- jedis.close();
-
- }
-
- public static User getUser(String key){
-
- Jedis jedis = new Jedis("192.168.59.12", 6379);
-
- String s = jedis.get(key);
-
- return JSON.parseObject(s,User.class);
-
-
- }
-
-
- }
逻辑是访问index先登录,登录的用户名存在cookie中,返回给客户端,登录的用户具体信息存在redis中。
docker中创建 loginDemo1 和loginDemo2





如法炮制另一个loginDemo2 但是tomcat端口不一样 一个是8081 一个8082
在nginx 配置数据卷文件中如下配置

这个时候访问就会在两台服务器一下一下挨着访问

