将数据从select标签发送到servlet

时间:2015-01-23 09:59:27

标签: java javascript html jsp

我有一个简单的选择标记

Job Category:
    <select name="jobCat">
        <option value="tech">Technology</option>
        <option value="admin">Administration</option>
        <option value="biology">Biology</option>
        <option value="science">Science</option>
     </select>

现在当用户选择我想将数据发送到servlet dopost方法的选项时?

上面的代码位于abc.jsp中,servlet文件的名称是pqr.java

如何执行上述操作?

我读过类似

的内容
<form action="login" method="post">
    UserId  <input type="text/html" name="userId"/><br><br>
    Password <input type="password" name="password"/><br><br>
    <input type="submit"/>
</form>

这个我通过

映射到登录servlet
WebServlet("/login")

因此当用户按下提交时,数据将被发送到此servlet。现在我想用select语句实现相同的功能吗?

这是scheduleMeet.jsp文件 `&lt;%@ page language =“java”contentType =“text / html; charset = UTF-8”         的pageEncoding = “UTF-8” %GT;     &lt;%@ page import =“important.businessService.dto.Employee”%&gt;                         在此处插入标题

</head>
<body>

Job Category:
<form action="scheduleMeet" method="post">
<select name="jobCat">
    <option value="tech">Technology</option>
    <option value="admin">Administration</option>
    <option value="biology">Biology</option>
    <option value="science">Science</option>
</select>
</form>


</body>
</html>`

这是ScheduleMeetServlet.java `包重要;

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

/**
 * Servlet implementation class scheduleMeetServlet
 */
@WebServlet("/scheduleMeet")
public class scheduleMeetServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse     response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String jobCategory = request.getParameter("jobCat");
    System.out.println("Job category is: " + jobCategory);
}
}    

`

1 个答案:

答案 0 :(得分:4)

您可以使用选择

的名称来完成此操作

您的选择必须在表格

<form action="login" method="post">
<select name="jobCat">
        <option value="tech">Technology</option>
        <option value="admin">Administration</option>
        <option value="biology">Biology</option>
        <option value="science">Science</option>
     </select>

 UserId <input type="text/html" name="userId"/><br><br> Password <input type="password" name="password"/><br><br> <input type="submit"/> </form>

在您的登录servlet中, 在你的servlet post方法中,只需使用request.getparameter来获取该值

eg



  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String selectedvalue  =  request.getparameter("jobCat");
         // you will get that value in the string selectedvalue
        }