Brian Var
Brian Var

Reputation: 6227

How to pass form input value from jsp page to java class?

I've set up a dynamic web project using Eclipse EE and added a jsp page.

The page is set as the welcome page when the project is run on a server and shows an input box along with a submit button.

My question is how can I pass the value entered into the input box to my HelloServlet class on button click?

Does anyone have any advice on how I could about this?

The hello jsp page layout is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Fibonacci Sequence</title>
</head>
<body>
<form action="HelloServlet">            
             <b>Fibonacci Sequence Length </b>  <br>
             <input type="text" name="fibNum"size="20px" style="font-size:30pt;height:60px" >

        </form>     
</body>
</html>

And this is the servlet class set up which extends HttpServlet:

public class HelloServlet extends HttpServlet {

    int fibNum;

    //parse input from hello.jsp input box 
    //and assign to fibNum variable


}

Upvotes: 0

Views: 9515

Answers (1)

Jerome Anthony
Jerome Anthony

Reputation: 8041

Define a the http method in your html form as 'GET' or 'POST'. I would set it to 'POST'. Then in your servlet class implement the doPost() method. The method signature will be like below;

doPost(HttpServletRequest req, HttpServletResponse resp) 

You would be able to retrieve the parameters from the req object(ServletRequest class) using the methods like

getParameter(java.lang.String name) 
getParameterMap() 

Read the linked javadoc to see the methods available to retrieve the parameters.

In your case you could extract the parameters like;

String fibNum = req.getParameter("fibNum");

You could use Integer.valueOf(fibNum) to convert to integer if you want.

Upvotes: 1

Related Questions