Oi Otávio, segue código da forma que estou utilizando e funciona.
Neste exemplo, gostaria de alterar de "forward:loginform.jsp" para "redirect:loginform.jsp", porém recebo 404
Ex. Classe de Login:
public class LoginForm implements Actions {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
return "forward:loginform.jsp";
}
}
MainServlet
@WebServlet(urlPatterns = "/main")
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String actionParameter = req.getParameter("action");
String className;
className = "br.com.testinguniversity.controller.action.".concat(actionParameter);
Actions action;
try {
action = (Actions) Class.forName(className).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new ServletException(e);
}
String redirectType = action.execute(req, resp);
String[] typeAndAddress = redirectType.split(":");
if(typeAndAddress[0].equals("forward")) {
RequestDispatcher dispatcher = req.getRequestDispatcher("WEB-INF/views/".concat(typeAndAddress[1]));
dispatcher.forward(req, resp);
} else {
resp.sendRedirect(typeAndAddress[1]);
}
}
}
Filter
@WebFilter("/main")
public class AutenticationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String actionParameter = req.getParameter("action");
if (actionParameter == null) {
resp.sendRedirect("main?action=LoginForm");
return;
}
boolean isLoginRequired = !(actionParameter.equals("LoginForm") || actionParameter.equals("Login")
|| actionParameter.equals("CreateAccountForm") || actionParameter.equals("CreateAccount"));
boolean isLogged = false;
HttpSession session = req.getSession();
if ((session.getAttribute("isLogged") != null)) {
isLogged = (Boolean) session.getAttribute("isLogged");
}
if (isLoginRequired && !isLogged) {
resp.sendRedirect("main?action=LoginForm");
return;
}
chain.doFilter(req, resp);
}
}