In the MVC architecture, Java classes are developed as models, servlets play as controllers and JSP are views. In this tutorial, we will develop a simple MVC application based on Java servlet and JSP.
public int square (int x){ return x*x; } public int factorial (int x) { if (x<0) return 0; int fact=1; for (int i=1; i<=x; i++) fact*=i; return fact; }
int num = Integer.parseInt(request.getParameter("value")); String method = request.getParameter("method"); Model m = new Model(); RequestDispatcher dispatcher; HttpSession session = request.getSession(); if (method.equals("square")){ session.setAttribute("square", m.square(num)); dispatcher = request.getRequestDispatcher("square.jsp"); } else{ session.setAttribute("factorial", m.factorial(num)); dispatcher = request.getRequestDispatcher("factorial.jsp"); } dispatcher.forward(request, response);
<form action="Controller" method="GET"> Input an integer: <input type="text" name="value"> <br> <input type="radio" name="method" value="square" checked> Square <br> <input type="radio" name="method" value="factorial"> Factorial<br> <input type="submit" value="Calculate"> </form>
Square result: <%= session.getAttribute("square") %>
Factorial result: <%= session.getAttribute("factorial") %>