I have n number of text fields named in the form \"Question.....\". How can I get all the parameters which starts with \"question\" from the JSP page to the Action?
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
The fastest way should be:
<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
if (entry.getKey().startsWith("question")) {
String[] values = entry.getValue();
// etc.
Note that you can't do:
for (Map.Entry<String, String[]> entry :
request.getParameterMap().entrySet()) { // WRONG!
for reasons explained here.
This should print out all Parameters that start with "Question".
<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
Enumeration parameterList = request.getParameterNames();
while( parameterList.hasMoreElements() )
{
String sName = parameterList.nextElement().toString();
if(sName.toLowerCase.startsWith("question")){
String[] sMultiple = request.getParameterValues( sName );
if( 1 >= sMultiple.length )
// parameter has a single value. print it.
out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
else
for( int i=0; i<sMultiple.length; i++ )
// if a paramater contains multiple values, print all of them
out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
}
}
%>
</body></html>
HTML or Jsp Page
<input type="text" name="1UserName">
<input type="text" name="2Password">
<Input type="text" name="3MobileNo">
<input type="text" name="4country">
and so on...
in java Code
SortedSet ss = new TreeSet();
Enumeration<String> enm=request.getParameterNames();
while(enm.hasMoreElements())
{
String pname = enm.nextElement();
ss.add(pname);
}
Iterator i=ss.iterator();
while(i.hasNext())
{
String param=(String)i.next();
String value=request.getParameter(param);
}
Even though this is an old question, I had to do something similar today but I prefer JSTL:
<c:forEach var="par" items="${paramValues}">
<c:if test="${fn:startsWith(par.key, 'question')}">
${par.key} = ${par.value[0]}; //whatever
</c:if>
</c:forEach>
localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3
<%@page import="java.util.Enumeration"%>
<%
Enumeration in = request.getParameterNames();
while(in.hasMoreElements()) {
String paramName = in.nextElement().toString();
out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
}
%>
key = datr
key2 = datr2
key3 = datr3