[JAVA] Passing parameters from JSP with Servlet

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.

Execution environment

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.

Recommended Posts

Passing parameters from JSP with Servlet
Getting Started with JSP & Servlet
JSP error display from Servlet
Hello World with GlassFish 5.1 + Servlet + JSP
About [servlet] [JSP] [tomcat]
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode
Until you create a Web application with Servlet / JSP (Part 1)
Java Servlet / JSP View drawing
Set @Max parameters from properties
Validate path parameters with @RequestMapping
Comparison of WEB application development with Rails and Java Servlet + JSP
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
Try passing values from Java Servlet to iPhone app using JSON
[Introduction to JSP + Servlet] I played with it for a while ♬
Get weather forecasts from Watson Weather Company Data with a simple JSP