0

I want to do this. If someone log with this url http://localhost:8080/ url. he should redirect to login servlet. So I create a code for it as this

@WebServlet(name = "RootController", urlPatterns = {"/"})
public class RootController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

        }
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        RequestDispatcher out = request.getRequestDispatcher("/login");

        out.forward(request, response);


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

But when I link the CSS and js files as this

<link href="resources/css/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

those files not linked. But I changed the root servlet urlPatterns to /abc it works correctly. Why is that? the path of the resource folder is correct. What should I do to achieve my task?

top11
  • 13
  • 1
  • 7

2 Answers2

0

Try empty url pattern @WebServlet(name = "RootController", urlPatterns = {""})

Igorock
  • 2,691
  • 6
  • 28
  • 39
0

When you hit the url "http://localhost:8080/" it will redirect you to the default page you have defined in web.xml. For example in your web.xml if you have defined like the below. Your url will load the index.jsp when you hit "http://localhost:8080/"

<webapp>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>    
</webapp>

So in your "@WebServlet" annotation add the url pattern like this @WebServlet(name = "RootController", urlPatterns = {"/index.jsp"}) or take an empty urlpattern "" and write the below code in doGet

if(request.getServletPath().equals("/index.jsp")) {
    response.sendRedirect("login")
}
Aditya C S
  • 653
  • 1
  • 8
  • 17