user2221016
user2221016

Reputation: 95

How to redirect to a JSP file from Servlet

I'm a beginner and am trying to understand how to re-direct to a JSP file from a Servlet. My Servlet "generates" a result after receiving replies from a current JSP file and with that I result I want to pass it to a different JSP file. I understand that there is a line of code:

request.getRequestDispatcher("/upload.jsp").forward(request, response);

But do I create a separate method for that and call it in the doGET?

Upvotes: 2

Views: 6597

Answers (2)

monika
monika

Reputation: 499

If you're using version 3.0 with annotations the redirects are very simple.

Suppose you have a User class (Strings fullname and Username with setters and getters) and UserDAO class that deals with database manipulation . Suppose this is your controller:

@RequestMapping(value = "/user_list")
public String users(HttpServletResponse response, HttpServletRequest request)
{
    //some function to verify access
    boolean authorized = client.getAccess(); 
    request.setAttribute("authorized", authorized);

    if (authorized)
    {
        List<User> users = UserDAO.geUsers();

        request.setAttribute("users", users);
        return "user_list";
    }
    else
    {
        return "access_denied";
    }
}

Then you can redirect from any location using the following syntax

@RequestMapping(value = "/create_user", method = RequestMethod.POST)
public String add_user(HttpServletResponse response, HttpServletRequest request)
{

    boolean authorized = client.getAccess();
    if (authorized)
    {
        User user = new User();

            user.setUserName(request.getParameter("username"));
            user.setFullName(request.getParameter("fullname"));

        if (UserDAO.saveUser(user))
        {
            return "redirect:/user_list";
        }
        else
        {
            return "error";
        }
    }
    else
    {
        return "access_denied";
    }
}

The redirect:/user_list will return updated user_list (eg if you were inserting to db your changes will be reflected).

Btw: you can drop the .jsp and path in your controller if you add few lines to your xml:

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/

Have a look at those tutorials:

http://www.javatpoint.com/spring-3-mvc-tutorial

http://www.javatpoint.com/servlet-tutorial

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

you can do

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      request.getRequestDispatcher("/upload.jsp").forward(request, response);
    } 

even though you created a method seperately you need the request and response object to the method.

I am heavily recommending the official docs:

http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html

and the pictorial

Upvotes: 4

Related Questions