Reputation: 1846
I have a simple select tag
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>
now when the user selects a option i want to send the data to a servlet dopost method?
The above code resides in abc.jsp and the name of servlet file is pqr.java
How to perform the above action?
I have read something like
<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>
and this i mapped to login servlet by
WebServlet("/login")
so when the user presses submit then the data is sent to this servlet. Now i want to achieve the same functionality with the select statement?
This is the scheduleMeet.jsp file ` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="important.businessService.dto.Employee" %> Insert title here
</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>`
and this is the ScheduleMeetServlet.java ` package important;
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);
}
}
`
Upvotes: 1
Views: 26557
Reputation: 4609
You can do it by using name of the select
Your select must be inside the form
<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>
In your Login servlet, in your servlet post method just use the request.getparameter to get that value
eg
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
String selectedvalue = request.getparameter("jobCat");
// you will get that value in the string selectedvalue
}
Upvotes: 5