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.
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%>)
.
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! ** **
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