Advertisement
ivana_andreevska

ThymeleafCategoryServlet

Nov 10th, 2022
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. package mk.ukim.finki.wpaud.web.servlet;
  2.  
  3. import mk.ukim.finki.wpaud.service.CategoryService;
  4. import org.thymeleaf.context.WebContext;
  5. import org.thymeleaf.spring5.SpringTemplateEngine;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13.  
  14. @WebServlet(name = "thymeleaf-category-servlet" , urlPatterns = "/servlet/thymeleaf/category")
  15. public class ThymeleafCategoryServlet extends HttpServlet {
  16.  
  17. private final SpringTemplateEngine springTemplateEngine;
  18. private final CategoryService categoryService;
  19.  
  20. public ThymeleafCategoryServlet(SpringTemplateEngine springTemplateEngine, CategoryService categoryService) {
  21. this.springTemplateEngine = springTemplateEngine;
  22. this.categoryService = categoryService;
  23. }
  24.  
  25. @Override
  26. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  27. WebContext context=new WebContext(req,resp, req.getServletContext());
  28. context.setVariable("ipAddress",req.getRemoteAddr());
  29. context.setVariable("clientAgent",req.getHeader("User-Agent"));
  30. context.setVariable("categories",this.categoryService.listCategories());
  31. this.springTemplateEngine.process("categories.html",context,resp.getWriter());
  32. }
  33.  
  34. @Override
  35. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  36. String categoryName=(String)req.getParameter("name");
  37. String categoryDec=(String) req.getParameter("description");
  38. categoryService.create(categoryName,categoryDec);
  39. resp.sendRedirect("/servlet/thymeleaf/category");
  40. }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement