1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package org.example.sweater.controller;
- import jakarta.servlet.http.HttpServletRequest;
- import org.example.sweater.domain.Message;
- import org.example.sweater.domain.User;
- import org.example.sweater.repos.MessagesRepository;
- import org.springframework.security.core.annotation.AuthenticationPrincipal;
- import org.springframework.security.web.csrf.CsrfToken;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import java.util.Map;
- @Controller
- public class MainController {
- public MainController(MessagesRepository messagesRepository) {
- this.messagesRepository = messagesRepository;
- }
- private final MessagesRepository messagesRepository;
- @ModelAttribute
- public void addCsrfToken(Model model, HttpServletRequest request) {
- CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
- model.addAttribute("_csrf", token);
- }
- @GetMapping("/")
- public String mainPage() {
- return "main";
- }
- @GetMapping("/feed")
- public String feed(
- @RequestParam(required = false)
- String tag,
- @RequestParam(required = false)
- String prefix,
- Model model
- ) {
- Iterable<Message> messages;
- if (prefix != null && !prefix.isEmpty()) {
- messages = messagesRepository.findByTextStartingWith(prefix);
- model.addAttribute("search", prefix);
- } else if (tag != null && !tag.isEmpty()) {
- messages = messagesRepository.findByTag(tag);
- model.addAttribute("tag", tag);
- } else {
- messages = messagesRepository.findAll();
- }
- model.addAttribute("messages", messages);
- return "feed";
- }
- @PostMapping("/feed")
- public String addMessage(
- @AuthenticationPrincipal User user,
- @RequestParam String text,
- @RequestParam String tag,
- Map<String, Object> model
- ) {
- Message createdMessage = new Message(text, tag, user);
- messagesRepository.save(createdMessage);
- Iterable<Message> allMessages = messagesRepository.findAll();
- model.put("messages", allMessages);
- return "feed";
- }
- @PostMapping("/feed/delete")
- public String removeMessageById(
- @RequestParam String id,
- Map<String, Object> model
- ) {
- Long idAsInt = Long.parseLong(id);
- messagesRepository.deleteById(idAsInt);
- Iterable<Message> foundMessages = messagesRepository.findAll();
- model.put("messages", foundMessages);
- return "feed";
- }
- }
|