How to redirect the previous page in JSP via servlet

I have a form to create user in jsp. There are 2 buttons named for Save and Cancel While I click "Save" button, user is saved into the database.It works. My problem I want to mention is not to redirect to previous page(list_users.jsp). How can I do?

Here is my code shown below.

user_forum.jsp

<button type="reset" name="button" class="btn btn-danger" value="Cancel">Cancel</button> 

Servlet

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String button = request.getParameter("button");

        if("Save".equals(button)) {
            createUser(request, response);
        }
        else if("Cancel".equals(button)) {  --> not working 
            String page = "list_users.jsp"; 
            RequestDispatcher dispatcher = request.getRequestDispatcher(page);
            dispatcher.forward(request, response);
        }

    }

Upvotes: 1

Views: 2992

Answers (3)

My answer

<script type="text/javascript">

    $(document).ready(function() {

        $("#buttonCancel").click(function() {
            history.go(-1);
        });
    });

</script>   

Upvotes: 0

abhinavsinghvirsen
abhinavsinghvirsen

Reputation: 2014

i think when you click on rest button its not hitting servlet.

for that inside your form user No need of button , just use <a href="servletmappingurl?button=Cancel">rest</a> request with a simple anchor and a request parameter reset witch says that the button should be reset button=cancel.

and add the below code in your servlet it will resolve your problem

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String button = request.getParameter("button");

        if("Cancel".equals(button)) {  --> not working 
            String page = "list_users.jsp"; 
            RequestDispatcher dispatcher = request.getRequestDispatcher(page);
            dispatcher.forward(request, response);
        }

Upvotes: 1

lekanbaruwa
lekanbaruwa

Reputation: 177

Try this:

response.sendRedirect("list_users.jsp");

Upvotes: 1

Related Questions