Monday, October 27, 2008

JSP: how to get form parameter values


As I have spent almost a day figuring out, how to get the values of html form's parameters and use them in a jsp code, I have decided to post my solution here.

One can argue, that there are lots of materials on the topic from JavaEE adepts. Well, I hope this message will be as well useful for a stranger in the Internet.

Note: this solution does not pretend to be general and suitable for any task you are solving. There is no WARRANTY for it as well. Do not kill your granny, if this code breaks your computer. Just get some JavaEE book and dive into all odds and ends.

So, if you need to have one html with embedded jsp code, go ahead and create one. Here is an example:

<%@ page contentType="text/html; charset=utf-8"
session="false" %>

* Allows you to post and see the value you have just posted
* @author Dmitry Kan
* get servlet version string
public String getServletVersion() {
ServletContext context=getServletConfig().getServletContext();
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
return Integer.toString(major) + '.' + Integer.toString(minor);

String lineSeparator = System.getProperty("line.separator");

// an important for this message code starts here
public void doGet(HttpServletRequest request, HttpServletResponse response)
Map paramMap = request.getParameterMap();
try {
PrintWriter out = response.getWriter();
String name = null;
String value[] = null;

Iterator iterator = paramMap.keySet().iterator();
while (iterator. hasNext()) {
name = (String);
value = (String[])paramMap.get(name);
out.print (name + "=" + value[0]);
} catch ( e) {

public void doPost(HttpServletRequest request, HttpServletResponse response)
doGet(request, response);


<title>SOAPPoster servlet, version <% out.print(getServletVersion()); %></title>
<h3>JSP POSTing machine</h3>
<form action="?" method="post" name="actionform">
<table border="0">
<td>Copy paste or type your message here:</td>
<td><textarea rows="10" cols="50" onclick="document.actionform.value=''" name="xmlTextArea"></textarea></td>
<td colspan="2"><input type="submit" value="post!" onclick=<% doPost(request,response); %> /></td>

That's it. Here are some screenshots:

1 comment:

Anonymous said... works fine.