✅P230_商城业务-认证服务-页面效果完成

gong_yz大约 4 分钟谷粒商城

一、用户名密码登录成功时存储session

1.1 介绍

此时我们手动输入 http://auth.cfmall.com/login.htmlopen in new window 仍然可以进入到登录页面再次进行登录,就需要在进入登录页面时进行判断用户是否登录

  • 如果用户已经登录直接重定向到首页
  • 用户未登录才允许用户登录

1.2 逻辑实现

编写一个可修改的属性keycfmall-common/src/main/java/com/gyz/common/constant/AuthServerConstant.java

public class AuthServerConstant {

    //省略代码...
    public static final String LOGIN_USER = "loginUser";

}

用户信息也保存到session中

cfmall-member/src/main/java/com/gyz/cfmall/member/controller/MemberController.java

@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

	@PostMapping(value = "/login")
    public R login(@RequestBody MemberUserLoginVo userLoginVo) {
        MemberEntity memberEntity = memberService.login(userLoginVo);
        if (memberEntity != null) {
            return R.ok().put("data", memberEntity);
        } else {
            return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(), BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
        }
    }
}

cfmall-auth-server/src/main/java/com/gyz/cfmall/controller/LoginController.java#login

@Controller
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private MemberFeignService memberFeignService;

	@PostMapping("/login")
    public String login(@RequestBody UserLoginVo userLoginVo, RedirectAttributes attributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if (r.getCode() == 0) {
            log.info("账号密码登录成功");
            MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://cfmall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.cfmall.com/login.html";
        }
    }
}

设置默认的昵称

cfmall-member/src/main/java/com/gyz/cfmall/member/service/impl/MemberServiceImpl.java#register

首页页面优化

cfmall-product/src/main/resources/templates/index.html

<li>
    <a href="http://auth.cfmall.com/login.html" th:if="${session.loginUser==null}">你好,请登录</a>
    <a th:else style="width: 100px;">[[${session.loginUser==null?'':session.loginUser.nickname}]]</a>
</li>
<li>
    <a href="http://auth.cfmall.com/reg.html" th:if="${session.loginUser==null}" class="li_2">免费注册</a>
</li>

二、用户已登录直接重定向到首页

视图映射是没有任何逻辑的,只要是这个请求就会跳到指定的视图(html),但是我们现在的登录页面是有逻辑判断的,需要在controller中新增对应接口。

1、将页面自动映射注释

2、编写接口

cfmall-auth-server/src/main/java/com/gyz/cfmall/controller/LoginController.java#loginPage

    /**
     * 判断session是否有loginUser,没有就跳转登录页面,有就跳转首页
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息,判断用户是否已经登录过了
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://cfmall.com";
        }
    }

三、商品详情页-用户昵称显示

cfmall-product/src/main/resources/templates/item.html

<li style="border: 0;">
    <a href="http://auth.cfmall.com/login.html" th:if="${session.loginUser==null}">你好,请登录</a>
    <a th:if="${session.loginUser != null}">欢迎, [[${session.loginUser.nickname}]]</a>
</li>
<li><a href="http://auth.cfmall.com/reg.html" th:if="${session.loginUser==null}" style="color: red;">免费注册</a> |</li>
<div class="nav_top_one"><a href="http://cfmall.com"><img src="/static/item/img/111.png"/></a></div>

四、搜索页-用户昵称显示

4.1 导入依赖

cfmall-search/pom.xml

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

4.2 application.properties配置

cfmall-search/src/main/resources/application.properties

spring.redis.host=192.168.17.130
spring.redis.port=6379
spring.session.store-type=redis

4.3 开启共享session功能

cfmall-search/src/main/java/com/gyz/cfmall/search/CfmallSearchApplication.java

4.4 自定义Spring Session

cfmall-search/src/main/java/com/gyz/cfmall/search/config/CfMalllSessionConfig.java

package com.gyz.cfmall.search.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * @author gong_yz
 * @Description
 */
@Configuration
public class CfMalllSessionConfig {

    /**
     * 方法作用域,解决子域共享问题
     *
     * @return
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("CFMALLSESSION");
        serializer.setDomainName("cfmall.com");
        return serializer;
    }

    /**
     * 使用json序列化将对象序列化存储到redis中
     *
     * @return
     */
    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}

4.5 搜索页面昵称获取

cfmall-search/src/main/resources/templates/list.html

<li>
    <a href="http://auth.cfmall.com/login.html" class="li_2" th:if="${session.loginUser==null}">你好,请登录</a>
    <a th:if="${session.loginUser != null}">欢迎, [[${session.loginUser.nickname}]]</a>
</li>
<li>
    <a href="http://auth.cfmall.com/reg.html" th:if="${session.loginUser==null}" class="li_2">免费注册</a>
</li>

五、测试

首页用户名称显示

搜索页用户名称显示

详情页用户名称显示