Appearance
Servlet Parameters
Servlet Parameters are bits of information that you can attach to a URL or include in a form submission. They carry essential details, like your topping choices on that pizza order or your username and password when logging into a website.
Example
java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Get parameters from the request
String name = request.getParameter("name");
String message;
// Generate a personalized message
if (name != null && !name.isEmpty()) {
message = "Hello, " + name + "! Welcome to our website.";
} else {
message = "Welcome to our website!";
}
// Send the response
PrintWriter out = response.getWriter();
out.println("<html><head><title>Simple Get Servlet</title></head><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
}
And in your web.xml
file, you would define the servlet mapping like this:
xml
<servlet>
<servlet-name>SimpleGetServlet</servlet-name>
<servlet-class>com.example.SimpleGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleGetServlet</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
With this setup, the SimpleGetServlet
will be accessible at the URL http://yourdomain.com/yourcontextroot/greeting
.
So, when a user navigates to http://yourdomain.com/yourcontextroot/greeting?name=John
, the servlet will respond with a personalized greeting for John. If no name parameter is provided, a generic welcome message will be displayed.
This URL pattern helps organize your servlets and makes it easier for users to access specific functionality on your website. Ready to explore further? Let's continue our journey into servlets and web development!