将值从一组单选按钮传递到servlet

时间:2013-04-17 13:03:52

标签: jsp servlets for-loop radio-button

当天的问候!!!

我创建了一个jsp文件,如下所示:

<%@ 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>Insert title here</title>
</head>
<body>
<form action="TestAms" method="post">
<%
    for(int i=0; i<5; i++){
        %>
            <input type="radio" name="<%= i%>" value="<%=i %>">
        <%
    }
%>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>

这个程序在循环中创建5个单选按钮,其名称和值与循环变量相同。现在我想获取servlet中单选按钮的值。我的servlet的代码如下:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestAms extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    for (int i=0; i<5; i++){
    String s[] = new String[5];
    s[i] = request.getParameter("<%= i%>"); 
    out.println(s[i]);
    }
}
}

但我结尾只有5个“null”值。我知道问题出在哪里。但我无法找到将循环变量传递给request.getParameter()方法的方法。请帮帮我..... Thnx提前!

1 个答案:

答案 0 :(得分:1)

在java中,你应该写:

s[i] = request.getParameter(Integer.toString(i));

&lt;%= ...%&gt;是JSP scriptlet,不适用于Java类。