Servlets · Lesson 11
JSP Basics and Integration
What JSP Adds
JSP, or JavaServer Pages, is a server-side view technology for rendering HTML from Java web applications. A servlet prepares view data, and the JSP displays that data with tags and expression language. This separation is easier to maintain than building large HTML strings in a servlet.
Passing Data to a JSP
A servlet can place values in request attributes and forward to a JSP under WEB-INF. The view reads the attributes with Expression Language and should avoid business logic.
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CourseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("courseTitle", "Servlet Fundamentals");
request.setAttribute("lessonCount", 12);
RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/course.jsp");
view.forward(request, response);
}
}
A JSP can render the attributes with expressions such as ${courseTitle} and ${lessonCount}. Standard tag libraries are preferable to scriptlets because they keep Java code out of the HTML view.
Servlet and JSP Roles
| Layer | Main responsibility | Example |
|---|---|---|
| Servlet | Handle HTTP and coordinate work | Load a course |
| Service | Apply business rules | Calculate progress |
| JSP | Render the view | Display course title |
| Repository | Access durable data | Query lessons |
Common Mistake and Practices
Common Mistake: Writing Java scriptlets and SQL directly inside a JSP. This mixes responsibilities, makes testing difficult, and can expose sensitive implementation details in a presentation file.
- Keep JSPs focused on presentation.
- Use Expression Language and tag libraries.
- Put JSP views under
WEB-INFwhen they require controller setup. - Escape user-generated output.
- Keep view models small and intentional.
Real-World Use Case
A course servlet loads a learner's progress and forwards a view model to a JSP. The JSP renders lesson links and progress indicators, while the service layer owns completion rules and the repository owns database access.
Quiz Check