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

2020-03-07  本文已影响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);
上一篇 下一篇

猜你喜欢

热点阅读