Understanding JSP and Servlets in Java EE
Table of Contents
- Fundamental Concepts
- What are Servlets?
- What are JSPs?
- Differences between Servlets and JSPs
- Usage Methods
- Creating and Running a Servlet
- Creating and Running a JSP
- Common Practices
- Handling Forms with Servlets and JSPs
- Using Session Management
- Database Connectivity
- Best Practices
- Separation of Concerns
- Error Handling
- Code Reusability
- Conclusion
- References
Fundamental Concepts
What are Servlets?
Servlets are Java classes that implement the javax.servlet.Servlet interface. They are used to handle client requests (usually HTTP requests) and generate responses. Servlets run on a web server, such as Apache Tomcat. When a client sends a request to a servlet, the web server creates a new thread to process the request. Servlets can perform a variety of tasks, such as reading form data, accessing databases, and generating HTML pages.
What are JSPs?
JSPs are text - based documents that combine HTML and Java code. They are used to create dynamic web pages. When a JSP page is requested, the web server translates it into a servlet, which is then compiled and executed. JSPs allow developers to embed Java code within HTML using special tags, making it easier to generate dynamic content.
Differences between Servlets and JSPs
- Syntax: Servlets are pure Java code, while JSPs combine HTML and Java code.
- Purpose: Servlets are mainly used for handling business logic, while JSPs are used for presenting data.
- Development: Servlets are more suitable for complex logic, while JSPs are easier for creating user interfaces.
Usage Methods
Creating and Running a Servlet
Here is a simple example of a servlet that responds with a “Hello, World!” message:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
To deploy and run this servlet, you need to configure it in the web.xml file:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Creating and Running a JSP
Here is a simple JSP example that displays a “Hello, World!” message:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Hello JSP</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
You can place this JSP file in the web directory of your web application. When you access the JSP page through a web browser, the server will generate the corresponding HTML page.
Common Practices
Handling Forms with Servlets and JSPs
Suppose you have an HTML form in a JSP page:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action="processForm" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
And a servlet to process the form data:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class FormServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
out.println("<html><body>");
out.println("<h1>Hello, " + name + "!</h1>");
out.println("</body></html>");
}
}
Using Session Management
Session management allows you to maintain state across multiple requests. Here is an example of using session management in a servlet:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
public class SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Integer visitCount = (Integer) session.getAttribute("visitCount");
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
}
session.setAttribute("visitCount", visitCount);
out.println("<html><body>");
out.println("<h1>You have visited this page " + visitCount + " times.</h1>");
out.println("</body></html>");
}
}
Database Connectivity
You can use JDBC to connect to a database from a servlet. Here is an example of querying a database in a servlet:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
out.println("<html><body>");
while (rs.next()) {
out.println("<p>" + rs.getString("name") + "</p>");
}
out.println("</body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Best Practices
Separation of Concerns
Separate the business logic from the presentation logic. Use servlets for handling business logic and JSPs for presenting data. This makes the code more maintainable and easier to understand.
Error Handling
Implement proper error handling in servlets and JSPs. Use try - catch blocks to catch exceptions and display meaningful error messages to the user.
Code Reusability
Use Java classes and methods to reuse code. For example, create utility classes for database operations or session management.
Conclusion
JSP and Servlets are powerful components in Java EE for building web applications. Servlets handle business logic, while JSPs are used for presenting data. By understanding their fundamental concepts, usage methods, common practices, and best practices, developers can create efficient and maintainable web applications. It is important to follow best practices such as separation of concerns, error handling, and code reusability to ensure the quality of the code.
References
- “Head First Servlets and JSP” by Bryan Basham, Kathy Sierra, and Bert Bates.
- Java EE official documentation: https://javaee.github.io/javaee-spec/
This blog post provides a solid foundation for understanding and using JSP and Servlets in Java EE. However, there are many more advanced topics and features that you can explore further.