If you want a super simple web application where a JSP
page would be used as view technology and Servlet
would supply the business logic, following example might help you:
Step 1: Create following sample.jsp
in /WebContent/WEB-INF/templates
of Eclipse's Dynamic Web Project
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Page</title>
</head>
<body>
<b>Time Now:</b> ${requestScope["time"]}
</body>
</html>
Step 2: Create following Servlet
to supply the business logic for the JSP
page:
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test")
public class MyApp extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyApp() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("time", new Date()); // 'time' would be shown on JSP page
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/templates/sample.jsp");
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Step 3: Call the above Servlet
by hitting following URL:
http://localhost:8080/mywebapp/test
The output is as shown below:
