When you develop web applications under Java EE, your JSP files do not route to your Java files. You have several options:
Encode everything in JSP and have embedded Java code inside your JSP. Your JSP acts as the viewer and controller of your pages. This is achieved through scriptlets, there you can import Java classes and use their members (methods, attributes). It is only useful for learning topics. It is not recommended to do this in production environments.
Use the architectural pattern Model View Controller (MVC for your acronym), where the JSP files make up the V ista, you use Servlets to handle HTTP requests and they make up the C ontrolador (they also provide router functionality) and rely on other Java classes (POJOs, dao, etc) that make up the M odelo.
Use the MVC pattern using Front Controller , where you have only one central Servlet (single controller) that captures all the requests to your application and delegates the behavior to other classes (model). The JSP files are the view of the application. This model is used in several frameworks such as Spring MVC, JSF, Struts 2, among others.
For learning topics, I will add an example of option 2 (option 1 is general culture only and is not recommended, therefore I do not explain it). It is assumed that you work with Java EE 7 and at least one servlet container version 3.0 such as Tomcat 7 or higher.
We define the view.
Web Pages
+ index.html
- WEB-INF
+ index.jsp
+ web.xml
As you can see, the JSP files are not found in web pages but within WEB-INF. The advantage of this is that the files contained in WEB-INF can not be accessed directly by users, so to access them a controller will always be used, that is, a servlet.
The web.xml file is defined as follows:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--
Desde Servlets 3.0 los servlets pueden ser decorados
con la anotación @WebServlet y no necesitan
configurarse en el XML.
-->
<!--
Se define el archivo de entrada de la aplicación.
-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
The index.html file is only for the application to work. It must not have content, its weight is 0 bytes.
The index.jsp file:
<!DOCTYPE html>
<html>
<head>
<title>Hola a servlets</title>
</head>
<body>
<!--
Esas cosas entre ${} hacen referencia a variables
almacenadas como atributos del request (entre otros)
Más de esto adelante.
-->
<h1>Hola ${nombre}. ¡Bienvenido a tu primer Servlet!</h1>
<form method="POST" action="index.html">
Ingresa tu nombre:
<input type="text" name="nombre" id="nombre" value="${nombrePorDefecto}" />
</form>
</body>
</html>
You define a Servlet for index.jsp:
@WebServlet("index.html") //se indica la ruta sobre la cual leerá las peticiones
public class IndexServlet extends HttpServlet {
private static final String NOMBRE_POR_DEFECTO = "Missael";
/*
doGet se utiliza para pre procesar la vista, es decir para
cargar información que se deberá visualizar en la vista.
En este caso, se agregará un valor por defecto al nombre.
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setAttribute("nombrePorDefecto", NOMBRE_POR_DEFECTO);
//se muestra el contenido de la vista
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(request, response);
}
/*
doPost es para procesar una acción. En este caso
solo se procesa el nombre ingresado por el usuario
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
/*
El método HttpServletRequest#getParameter permite
obtener un parámetro por su nombre (<input name="nombre" />)
no confundir con el id (<input id="nombre" />).
*/
String nombreIngresado = request.getParameter("nombre");
//se agrega información a visualizar en el resultado de la vista
request.setAttribute("nombre", nombreIngresado);
//se vuelve a agregar el nombre por defecto.
request.setAttribute("nombrePorDefecto", NOMBRE_POR_DEFECTO);
//se muestra el contenido de la vista
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(request, response);
/*
Cuidado. El hecho de que los métodos doGet y doPost
tengan código similar en ambos es solo una coincidencia.
No siempre puede suceder este caso.
*/
}
}