Servlet – Get URL Parameters in doGet()

This post shows you how to get URL parameters in Java Servlet doGet method.

To do this, we simply use HttpServletRequest.getParameter method like this:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String value = request.getParameter("parameter-name");
}

Here is the full Servlet example.

PostServlet.java
package com.bytenota;

import java.io.IOException;
import java.io.PrintWriter;
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(name = "PostServlet", urlPatterns = {"/post"})
public class PostServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = response.getWriter();

        // get post name value from url
        String value = request.getParameter("name");

        // print the result to view
        if (value != null) {
            out.write(value);
        }
    }

}

Assuming that, we run this Servlet page under the following URL: http://localhost:8080/WebApp/post?name=hello-world-program

The ouput result we should get is:

hello-world-program

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x