I'm trying to learn how to build web applications using Java EE 6, but I'm struggling to understand the best way to pass information between the components of a typical MVC2 design.
The way I understand it, the MVC2 pattern using Java EE would be: the data is the model, the controller would be a servlet, and the view would be a JSP. This is just one example of course.
So I've written the following three pieces and I know how to install them in the server I'm using (Tomcat 7), and the entry point would be the html file below. I'm struggling with how the servlet forwards it's response to the JSP, and how that JSP gets sent back to the client browser.
The HTML file (demo.html):
<html>
<head>
<title>MVC2 Demo</title>
</head>
<body>
<form method='post' action='/mvc2-demo/DemoServlet'>
<h1> MVC2 Demo </h1>
Name: <input type='text' name='input_name' size='50'>
<br><br>
Age: <input type='text' name='input_age' size='10'>
<br><br>
<input type='submit' value='SUBMIT INFO'>
</form>
</body>
</html>
The servlet (DemoServlet.java):
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
try {
PrintWriter pw = response.getWriter();
String name = request.getParameter("input_name");
String age = request.getParameter("input_age");
pw.println("Information received by Servlet: " + name + " : " + age);
// forward this response to Demo.jsp...
pw.close();
} catch (Exception e) {
System.out.println("Cannot get writer: " + e);
}
}
}
The JSP (Demo.jsp):
<html>
<head><title> JSP Demo </title></head>
<body>
<h1>JSP Demo</h1>
<ul>
<%= get response forwarded from servlet.. %>
</ul>
</body>
</html>
The entry point is an HTML page which displays a simple form with two input fields (one for someone's name, the other for their age) and a submit button. When the user hits Submit, the form sends it data to the DemoServlet. The servlet then pulls the data from the HTTP request payload and saves it in some local String variables. The part I commented out is where I'd like to somehow forward this information to the JSP. And once I do that, does the JSP automatically get sent to the client? What triggers that?
Thanks for your help.