美文网首页
拦截器-问题详情-登陆问题-编辑功能-(5)

拦截器-问题详情-登陆问题-编辑功能-(5)

作者: 弹钢琴的崽崽 | 来源:发表于2020-03-07 08:59 被阅读0次

1. 拦截器配置

1.1 WebConfig

package life.guohui.community.interceptor;
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private SessionInterceptor sessionInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor).addPathPatterns("/**");
    }
}

1.2 自定义拦截器

package life.guohui.community.interceptor;
@Service
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    User user = userMapper.findByToken(token);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                    }
                    break;
                }
            }
        }
        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 {

    }
}

1.3 修改之前代码

2. 问题详情功能

2.1 QuestionController

2.2 service

2.3 mapper

@Select("select * from question where id = #{id}")
Question getById(@Param("id") Integer id);

2.4 复制profile.html到question.html

a. 初始页面

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title th:text="${question.title}"></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <link rel="stylesheet" href="/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="/css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" href="/css/community.css"/>
        <script src="/js/jquery-3.4.1.min.js"></script>
        <script src="/js/bootstrap.min.js" type="application/javascript"></script>

    </head>
    <body>

        <div th:insert="~{navigation :: nav}"></div>
        <div class="container-fluid main profile">
            <div class="row">
                <div class="col-lg-9 col-md-12 col-sm-12 col-xs-12">
                    <h3><span th:text="${question.title}"></span></h3>
                    <hr>

                </div>

                <div class="col-lg-3 col-md-12 col-sm-12 col-xs-12">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <h3>发起人</h3>
                    </div>
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <h3>相关问题</h3>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

2.5 index.html添加连接

<a th:href="@{'question'+${question.id}" th:text="${question.title}"></a>

2.6 给编辑按钮自定义css

头像变成圆的样式

2.7 页面效果

2.8 页面代码

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
......
    <body>
        <div th:insert="~{navigation :: nav}"></div>
        <div class="container-fluid main profile">
            <div class="row">
                <div class="col-lg-9 col-md-12 col-sm-12 col-xs-12">
                    <h4><span th:text="${question.title}"></span></h4>
                    <span class="text-desc">
                        作者:[[${question.user.name}]] |
                        发布时间:[[${#dates.format(question.gmtCreate,'yyyy-MM-dd HH:mm')}]] |
                        阅读数:[[${question.viewCount}]]
                    </span><div></div>
                    <hr class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" th:text="${question.description}"></div>
                    <hr class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

                    <a th:href="@{'/publish/'+${question.id}}" class="community-menu">
                        <span class="glyphicon glyphicon-pencil">编辑</span>
                    </a>

                </div>

                <div class="col-lg-3 col-md-12 col-sm-12 col-xs-12">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <h4>发起人</h4>
                        <div class="media-left">
                            <a href="">
                                <img th:src="${question.user.getAvatarUrl()}" class="media-object img-circle">
                            </a>
                        </div>
                        <div class="media-body">
                            <h5 class="media-heading" >
                                <span  th:text="${question.user.name}"></span>
                            </h5>
                        </div>
                    </div>
                    <hr class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <h4>相关问题</h4>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

3. 登陆问题

3.1 显示编辑按钮的条件

question.html

<a th:href="@{'/publish/'+${question.id}}" class="community-menu" th:if="${session.user != null && session.user.id == question.creator}">
    <span class="glyphicon glyphicon-pencil">编辑</span>
</a>

3.2 登陆需要修改

a. 用户登陆时需要判断AccountId是否存在

b. 创建UserService

创建时间放到service

package life.guohui.community.service;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public void createOrUpdate(User user) {
        User dbUser = userMapper.findByAccountId(user.getAccountId());
        if(dbUser == null){
            //插入
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userMapper.insert(user);
        }else{
            dbUser.setGmtModified(System.currentTimeMillis());
            dbUser.setAvatarUrl(user.getAvatarUrl());
            dbUser.setName(user.getName());
            dbUser.setToken(user.getToken());
            userMapper.update(dbUser);
        }
    }
}

c. UserMapper

@Select("select * from user where account_id = #{accountId}")
User findByAccountId(@Param("accountId") String accountId);
@Update("update user set name=#{name},token=#{token},gmt_modified=#{gmtModified},avatar_url=#{avatarUrl} where id = #{id}")
void update(User user);

3.3 退出登陆

@GetMapping("/logout")
public String logout(HttpServletRequest request,
                     HttpServletResponse response){
    request.getSession().removeAttribute("user");
    Cookie cookie = new Cookie("token",null);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    return "redirect:/";
}

4. 编辑功能实现

4.1 controller路径

package life.guohui.community.controller;
@Controller
public class PublishController {

    @Autowired
    private QuestionService questionService;

    @GetMapping("/publish/{id}")
    public String edit(@PathVariable(name = "id") Integer id,
                       Model model){
        QuestionDTO question = questionService.getById(id);
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        model.addAttribute("id",question.getId());
        return "publish";
    }
......
}

4.2 service中getById

public QuestionDTO getById(Integer id) {
    Question question = questionMapper.getById(id);
    QuestionDTO questionDTO = new QuestionDTO();
    BeanUtils.copyProperties(question,questionDTO);
    User user = userMapper.findById(question.getCreator());
    questionDTO.setUser(user);
    return questionDTO;
}

4.3 给表单中添加id属性

4.4 在service中判断修改还是添加

时间的创建移动到service

public void createOrUpdate(Question question) {
    if(question.getId() == null){
        question.setGmtCreate(System.currentTimeMillis());
        question.setGmtModified(question.getGmtCreate());
        questionMapper.create(question);
    }else {
        //更新
        question.setGmtModified(question.getGmtCreate());
        questionMapper.update(question);
    }

}

4.5 Mapper中的方法

@Select("select * from question where id = #{id}")
Question getById(@Param("id") Integer id);
@Update({"update question set title = #{title},description=#{description},gmt_modified= #{gmtModified},tag = #{tag} where id = #{id}"})
void update(Question question);

相关文章

  • 拦截器-问题详情-登陆问题-编辑功能-(5)

    1. 拦截器配置 1.1 WebConfig 1.2 自定义拦截器 1.3 修改之前代码 2. 问题详情功能 2....

  • bug

    问题1 车型图片详情页编辑页渲染问题2详情页启用禁用 渲染问题

  • springmvc 拦截器做登陆验证

    springmvc提供了强大的拦截器,可以自定义拦截功能,现在我们做一个登陆拦截器,实现验证用户登陆ticket并...

  • spring中拦截器的实现

    前言 web项目开发中拦截器是常用的功能,帮我们实现登陆验证,设置数据,统计时效等功能 。spring中拦截器一...

  • 小程序scroll-view嵌套swiper高度不能完全展示

    前两天写商品详情页功能时,遇到这个问题,在最上面的swiper轮播图设置固定高度,没有问题,下面遇到图文详情,规格...

  • Panda8zDiary--2018-08-31

    第三方登陆功能了逻辑,绑定手机账号功能逻辑Facebook登陆的接口联调.WeChat因为sdk问题搁置.多语言脚...

  • 通过Zuul来反向代理Kibana

    项目中使用ELK来收集日志,问题是Kibana没有登陆功能,登陆功能被放在X-Pack中了,而X-Pack是收费的...

  • SpringMVC拦截器

    SpringMVC拦截器的应用场景: 1.解决乱码问题 2.解决权限验证问题 拦截器的实现 拦截器的实现主要分为3...

  • okHttp源码分析(2)-拦截器

    拦截器详情 一、重试及重定向拦截器 第一个拦截器:RetryAndFollowUpInterceptor,主要就是...

  • php学习路(八) --Tp项目web工程总结

    这一章,我们总结下项目中遇到的问题,以便以后使用: 问题目录: php中类似拦截器的功能实现权限管理 项目中的静态...

网友评论

      本文标题:拦截器-问题详情-登陆问题-编辑功能-(5)

      本文链接:https://www.haomeiwen.com/subject/qrnirhtx.html