[Java] Passing parameters from JSP with Servlet

1 minute read

Introduction

This time, we will continue from Creating a Servlet program in Eclipse.
The aim this time is to get the value entered in JSP with Servlet and pass it to JSP.

  • It is easier to implement using JSTL, but this time it is a simple process and will not be used.

Execution environment

  • Eclipse4.16
  • Tomcat9
  • Java11

Passing from JSP to Servlet

First, edit the JSP.

sample.jsp


<form action="/SampleTest" method="post">
  <input type="text" name="param">
  <input type="submit" value="Registration">
</form>

Set the name to be received by Servlet in the name attribute of the input tag.

Then edit the Servlet’s doPost method.

SampleTest.java


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); //Set the character code so that the characters are not garbled.
		String param = request.getParameter("param"); //Get the input value with the name attribute of JSP set.
		request.setAttribute("param", param); //Set in a variable called param to pass to JSP
		request.getRequestDispatcher("/WEB-INF/view/sample.jsp").forward(request, response);
	}

Now you are ready to hand it over to JSP.

Finally, describe the process received by JSP.

sample.jsp


<form action="/SampleTest" method="post">
  <input type="text" name="param">
  <input type="submit" value="Registration">
</form>
<%= request.getAttribute("param")%>

Scriptlet (<% Java code;%>) can use Java code in JSP files
Output variables, method return values, etc. using script expression (<% = Java code%>).

Run

If you can do this, start the server.
When you enter the input value and press the registration button
** Success if the input value is displayed below! ** **

Finally

Now you have learned the basics of Servlet together with the last time.
I will create a web application from the next time.