[fc7ec52] | 1 | package com.example.demo.servlet;
|
---|
| 2 |
|
---|
| 3 | import com.example.demo.exceptions.InvalidArgumentsException;
|
---|
| 4 | import com.example.demo.exceptions.InvalidUserCredentialsException;
|
---|
| 5 | import com.example.demo.model.User;
|
---|
| 6 | import com.example.demo.service.AuthService;
|
---|
| 7 | import org.thymeleaf.context.WebContext;
|
---|
| 8 | import org.thymeleaf.spring5.SpringTemplateEngine;
|
---|
| 9 |
|
---|
| 10 | import javax.servlet.ServletException;
|
---|
| 11 | import javax.servlet.annotation.WebServlet;
|
---|
| 12 | import javax.servlet.http.HttpServlet;
|
---|
| 13 | import javax.servlet.http.HttpServletRequest;
|
---|
| 14 | import javax.servlet.http.HttpServletResponse;
|
---|
| 15 | import java.io.IOException;
|
---|
| 16 | import java.util.Optional;
|
---|
| 17 |
|
---|
| 18 | @WebServlet(name="LoginServlet", urlPatterns = "/servlet/login")
|
---|
| 19 | public class LoginServlet extends HttpServlet {
|
---|
| 20 |
|
---|
| 21 | private final SpringTemplateEngine springTemplateEngine;
|
---|
| 22 | private final AuthService authService;
|
---|
| 23 |
|
---|
| 24 | public LoginServlet(SpringTemplateEngine springTemplateEngine, AuthService authService) {
|
---|
| 25 | this.springTemplateEngine = springTemplateEngine;
|
---|
| 26 | this.authService = authService;
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | @Override
|
---|
| 30 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
---|
| 31 | WebContext context = new WebContext(req,resp,req.getServletContext());
|
---|
| 32 | springTemplateEngine.process("login.html",context,resp.getWriter());
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | @Override
|
---|
| 36 | protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
---|
| 37 | String username = req.getParameter("username");
|
---|
| 38 | String password = req.getParameter("password");
|
---|
| 39 |
|
---|
| 40 | Optional<User> user = null;
|
---|
| 41 | try {
|
---|
| 42 | user = authService.login(username,password);
|
---|
| 43 |
|
---|
| 44 | } catch (InvalidUserCredentialsException | InvalidArgumentsException ex ) {
|
---|
| 45 | WebContext context = new WebContext(req,resp,req.getServletContext());
|
---|
| 46 | context.setVariable("hasError",true);
|
---|
| 47 | context.setVariable("error",ex.getMessage());
|
---|
| 48 | springTemplateEngine.process("login.html",context,resp.getWriter());
|
---|
| 49 | return;
|
---|
| 50 | }
|
---|
| 51 | req.getSession().setAttribute("user",user);
|
---|
| 52 | resp.sendRedirect("/movies");
|
---|
| 53 | }
|
---|
| 54 | }
|
---|