VoidForum/src/main/java/ru/bvn13/voidforum/controllers/TagController.java

59 lines
1.9 KiB
Java

package ru.bvn13.voidforum.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.bvn13.voidforum.error.NotFoundException;
import ru.bvn13.voidforum.models.Post;
import ru.bvn13.voidforum.models.Tag;
import ru.bvn13.voidforum.services.AppSetting;
import ru.bvn13.voidforum.services.PostService;
import ru.bvn13.voidforum.services.TagService;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
/**
* bvn13 <mail4bvn@gmail.com>.
*/
@Controller
@RequestMapping("tags")
public class TagController {
@Autowired
private TagService tagService;
@Autowired
private PostService postService;
@Autowired
private AppSetting appSetting;
@RequestMapping(value = "", method = GET)
public String index(Model model){
model.addAttribute("tags", postService.countPostsByTags());
return "tags/index";
}
@RequestMapping(value = "{tagName}", method = GET)
public String showTag(@PathVariable String tagName, @RequestParam(defaultValue = "1") int page, Model model) {
Tag tag = tagService.getTag(tagName);
if (tag == null) {
throw new NotFoundException("Tag " + tagName + " is not found.");
}
page = page < 1 ? 0 : page - 1;
Page<Post> posts = postService.findPostsByTag(tagName, page, appSetting.getPageSize());
model.addAttribute("tag", tag);
model.addAttribute("posts", posts);
model.addAttribute("page", page + 1);
model.addAttribute("totalPages", posts.getTotalPages());
return "tags/show";
}
}