Java Servlets are Java programs that run on a web server. They handle client requests and generate dynamic web content. Servlets are used to perform tasks such as processing form data, interacting with databases, and managing user sessions.
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 {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello, World!</h2>");
out.println("</body></html>");
}
}
JSP is a technology that allows you to embed Java code within HTML pages. It is used to generate dynamic web pages. JSP pages are pre - compiled into servlets, which are then executed on the server.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Example</title>
</head>
<body>
<h2>Welcome to JSP Page</h2>
<%
String message = "This is a JSP example.";
out.println("<p>" + message + "</p>");
%>
</body>
</html>
MVC is a software architectural pattern that separates an application into three main components: the Model, the View, and the Controller.
Popular IDEs for Java development include Eclipse, IntelliJ IDEA, and NetBeans. Download and install your preferred IDE.
Apache Tomcat is a popular open - source servlet container.
HttpServlet
.doGet
or doPost
method to handle HTTP requests..jsp
extension.In the web.xml
file (for older projects) or using annotations (for newer projects), map the URL pattern to your servlet.
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Hello from Servlet!</h2>");
out.println("</body></html>");
}
}
To connect to a database in a Java web application, you can use JDBC (Java Database Connectivity).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseConnectionExample {
public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// Create a statement
Statement stmt = conn.createStatement();
// Execute a query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("username"));
}
// Close the resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java servlets provide session management capabilities. You can use the HttpSession
object to manage user sessions.
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 {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String username = (String) session.getAttribute("username");
if (username == null) {
session.setAttribute("username", "Guest");
username = "Guest";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Welcome, " + username + "</h2>");
out.println("</body></html>");
}
}
You can handle errors in Java web applications by implementing custom error pages in the web.xml
file.
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
Building web applications with Java offers a wide range of features and capabilities. By understanding the fundamental concepts, setting up the development environment correctly, and following common and best practices, you can create robust, secure, and high - performance web applications. This hands - on tutorial has provided you with the necessary knowledge to get started with Java web development.