Reputation: 41
I have the following page in JSP:
<%String a= request.getParameter("Test");
System.out.println(a);%>
<form >
<input type="text" name="Test" value= "Whatever" >
</form>
If I start, it shows me on the consule "null" why? Sorry for this very basic question!
Upvotes: 2
Views: 6832
Reputation: 3008
If I start, it shows me on the consule "null" why?
Everyone else has answered, how to do the right thing. Let me tell, why it is doing what it is doing. Since, there is nothing in the request and everything is just plain GET request, so request.getParameter("Test");
resolves nothing and returns null
in response.
You can probably try to invoke this page as:
http://whatever.com:PORT_IF_ANY/CONTEXT?Test=Whatever
You will then see your page printing Whatever
instead of null. So, long story short, since your request doesn't has the parameter named as Test
, it evaluates to null
and you print that null
.
Upvotes: 2
Reputation: 10174
You need to have this code distributed in two different JSPs:
First JSP:
<form >
<input type="text" name="Test" value= "Whatever" >
</form>
Then you need to submit this form from your browser. In your servlet doPost handler, you need to dispatch the second JSP which will have the following code:
<%String a= request.getParameter("Test");
System.out.println(a);%>
Update:
As one of the fellow reviewers notate, you can always use the same JSP before and after the form submission. In this case, the first one will still print null while the second one will print the desired output. The key is that the form must be submitted in order for the form parameters to be populated to the request context automatically.
Upvotes: 2
Reputation: 141
I think you should do as follow code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%String a= request.getParameter("Test");
System.out.println(a);%>
<form action="#">
<input type="text" name="Test" value= "Whatever" >
<input type="submit" value="submit">
</form>
</body>
</html>
When you click submit the console will print Whatever。But when you first visit the page, the console is printed as null
Upvotes: 1