0

I'm new to JSP and Servlet and i want to develop a web app using MVC pattern I'm wondering if there is any way to create a Controller using a servlet which can handle many actions and views (like the one in ASP.NET MVC)

For example i have a Controller named "AccountController" what i want is : when a user request the url /Account/Login the AccountController process the request (get or post) and shows the LoginView.jsp

And the same for the Url /Account/Register the AccountController process the request (get or post) and shows the RegisterView.jsp

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Charaf
  • 177
  • 1
  • 2
  • 12

2 Answers2

1

Thank very much you sir

But i did it without using Spring framework :)

this is my code :

1 - AccountControler.java

public class AccountController extends HttpServlet {

   // GET
   protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
   { 
       String action = Helper.getAction(request);

       switch (action) {
       case "Login":
           // ToDo
           View.go(request, response, "../LoginView.jsp");
           break;

       case "Register":
           // ToDo 
           View.go(request, response, "../RegisterView.jsp");
           break;
       default:
           View.go(request, response, "../HomeView.jsp");
           break;
        }
    }
}

And this is the getAction() method

public static String getAction(HttpServletRequest request) {
    String act[] = request.getRequestURL().toString().split("/");
    return act[act.length-1];
}
Charaf
  • 177
  • 1
  • 2
  • 12
0

I suggest to use Spring MVC for this purpose http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/mvc.html

You will have something like this:

@Controller
@RequestMapping("/Account")
public class AccountController {

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login() {

    ...
}

@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register() {

    ...
}

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcome() {

    ...
}

}

Mafick
  • 1,128
  • 1
  • 12
  • 27
Igorock
  • 2,691
  • 6
  • 28
  • 39