I have a servlet that creates an html text box and then redirects to another servlet on submit. How can I access the value of the html text box from the new servlet? I am able to access servlet variables from the new servlet but I am not aware of how to access the value of the html generated code.
thanks,
Here is the servlet that gets the text input
public class ServletB extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
String value = System.getProperty("card");
PrintWriter out = response.getWriter();
out.println("<center><h1>Your preffered method of payment is "+value+"</h1><br />");
out.println("Please Enter Card Number<input type =\"text\" name = \"number\"/><form action=\"http://codd.cs.gsu.edu:9999/cpereyra183/servlet/ServletC\"><input type =\"submit\" value=\"Continue\" /><input type=\"button\" value=\"Cancel\" /></center>");
}
}}
This is the servlet the first servlet redirects to all I do is try to do is output the text input
public class ServletC extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
String value = System.getProperty("card");
PrintWriter out = response.getWriter();
out.println(request.getParameter("number"));
}
}
If you give the input field a name
<input type="text" name="foo">
then you can access it in the postprocessing servlet as a request parameter by the input field's name.
String foo = request.getParameter("foo");
See also:
Servlets info page - contains a hello world
Unrelated to the concrete question, in contrary to what the majority of servlet tutorials want to let believe us, HTML actually belongs in JSP, not in a Servlet. I'd suggest to put that HTML in a JSP.
If your markup looks something like this...
<form action="anotherServlet">
<input name="myTextbox" />
</form>
...then you can get the value out of the HttpServletRequest object in the doGet() or doPost() method of anotherServlet like this:
String textboxValue = request.getParameter("myTextbox");
See: ServletRequest#getParameter().
public class Formvalid extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pr = response.getWriter();
boolean flag = true;
int count=0;
response.setContentType("text/html");
Enumeration enume;
enume = request.getParameterNames();
while (enume.hasMoreElements()) {
count++;
String name = (String) enume.nextElement();
String value = request.getParameter(name);
if (value == null || value.equals("")) {
pr.println("<h5 style='color:red;'>please enter manditory values :"
+ name + "</h5>");
flag = false;
}
}
pr.println("<h3>Employe Registation</h3>");
if (!flag || count==0) {
pr.println("<form method=\"get\" action=\"formvalid\"><br />EmpName *:<input type='text' name='Empname' ><br />"
+ "Age *:<input type='text' name='age' ><br /><tr><td>Qulification *:<input type='text' name='Qualification' ><br />Address<textarea> </textarea><br /><input type='submit' value='submit'><input type='reset' value='reset'></FORM>");
} else {
pr.println("<h3 style='color:green;'>submitted successfully</h3>");
}
}
}
Related
I have read the similar topics like this, and that one but it did not help with my problem.
I created a simple JavaEE mvc web app. The jsp page contains a form with two text fields and two buttons. The first text field to enter an Id, the second to enter a name. Depending on which button is clicked a Servlet routes to the appropriate method (Search by ID or Search by Name).
Search by id method works correctly. And I see the following path in the address bar: http://localhost:8080/employees_war_exploded/ControllerServlet?textEmployeeId=1&command=Search_ID&employeeName=
However there is a problem with a Search by name method. It does not show any results. Here is what I see in the address bar: http://localhost:8080/employees_war_exploded/ControllerServlet?textEmployeeId=&employeeName=ann&command=Search_Name
I guess the problem is that in both cases it gets the parameters of both text fields ("textEmployeeId" and "employeeName"). How can I make it process both inputs separately in the same form? Maybe there is some other reason for the problem that I do not see?
<form class="form-style" name="form1">
<label>ID:
<input type="text" name="textEmployeeId" value="${tempEmployee.id}" />
</label>
<input type="submit" name="command" value="Search_ID">
<br>
<br>
<label>Name:
<input type="text" name="employeeName" value="${tempEmployee.name}" />
</label>
<input type="submit" name="command" value="Search_Name">
<br>
<br>
</form>
ControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String theCommand = request.getParameter("command");
if (theCommand == null) {
theCommand = "EMPLOYEE_LIST";
}
// route to the appropriate method
switch (theCommand) {
case "EMPLOYEE_LIST":
listEmployees(request, response);
break;
case "Search_ID":
searchById(request, response);
break;
case "Search_Name":
searchByName(request, response);
break;
default:
listEmployees(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void searchByName(HttpServletRequest request, HttpServletResponse response) throws Exception {
String nameString = request.getParameter("employeeName");
List<Employee> namedEmployees = employeeDbUtil.searchEmployees(nameString);
request.setAttribute("EMPLOYEES", namedEmployees);
RequestDispatcher dispatcher = request.getRequestDispatcher("/search-by-name.jsp");
dispatcher.forward(request, response);
}
private void searchById(HttpServletRequest request, HttpServletResponse response) throws Exception {
String textString = request.getParameter("textEmployeeId");
Employee theEmployee = employeeDbUtil.getEmployeeById(textString);
request.setAttribute("THE_EMPLOYEE", theEmployee);
RequestDispatcher dispatcher = request.getRequestDispatcher("/show-employee.jsp");
dispatcher.forward(request, response);
}
}
Update: I'm getting a NullPointerException for the searchByName method. Could there be a problem with this method from a DAO class that is called from ControllerServlet?
public List<Employee> searchEmployees(String employeeName) throws Exception {
List<Employee> employeeList = new ArrayList();
Connection myConnection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
employeeName += "%";
preparedStatement = myConnection.prepareStatement("SELECT * FROM employees WHERE LOWER(name) like LOWER(?)");
preparedStatement.setString(1, employeeName);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Employee tempEmployee = resultSetToEmployee(resultSet);
employeeList.add(tempEmployee);
}
return employeeList;
}
finally {
DbExceptions.close(resultSet);
DbExceptions.close(preparedStatement);
DbExceptions.close(myConnection);
}
}
First of all, this might seem like a duplicate but I assure you I have tried many questions and still hasn't got a proper answer. So I'm asking this here.
I have an HTML form from which I would like to submit a query to a servlet and show the results in a different division.
My HTML code essentially consists of the following:
<form>
<input name="query" id="query" placeholder="Query">
<button id="searchDoc">Search</button>
</form>
<div id="search-results"></div>
I have the following jQuery in order to handle the ajax call.
$('#searchDoc').click(function() {
var q = $('#query').val();
$.ajax({
url: "QueryServlet",
data: {query:q},
success: function(data) {
alert("data: " + data);
$('#search-results').html(data);
}
});
});
My QueryServlet is:
#WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String query = request.getParameter("query");
QueryUtil qu = new QueryUtil();
String mySqlQuery = qu.buildMySQLSearchQuery(query);
System.out.println(mySqlQuery);
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = new DbConnection().getConnection();
st = con.createStatement();
rs = st.executeQuery(mySqlQuery);
if(rs != null) {
response.setStatus(HttpServletResponse.SC_OK);
while(rs.next()) {
out.println("" + rs.getString("fileName") + "");
}
} else {
// TODO add keywords to database
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Even when I submit a valid query, the div does not get loaded up with the data from the servlet. The data reaches the servlet and gets displayed in the console, but I am unable to retrieve that data from the script.
The <button> tag is equivalent to an <input type="submit"/>. If you in your form tag don't declare any action attribute, the standard action causes that the page is reloaded. This causes that, although the returned data are inserted in #search-results div, you'll never be able to see them, because the page is immediately reloaded.
You should deactivate the default "Submit" button this way:
$('#searchDoc').click(function(e) {
e.preventDefault();
[....]
});
This should fix your problem!
the issue seems related to context path, your path should look like this if servlet is not in context root :-
<host> / <context path>/ <servlet>
Thanks :)
Hi I'm new to Servlets probably easy question. After I've passed the data into forms and click on the submit button I get java.lang.NullPointerException LogOut.doPost(LogOut.java:45) any ideas how to pass through this exception?
Code doGet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
HttpSession session = request.getSession(false);
out.println("<form method='post' action='LogOut'>"
+ "usr <input type='text' id='username'/>"
+ "pass <input type='password'id='password'/>"
+ "<input type='submit' value='Login'></form>");
//If the username and password is correct
if (session != null) {
String username = (String) session.getAttribute("username");
out.println("Hi " + username + "sessioon is started with id " + session.getId());
out.println("<a id='logout' value='Logout' />");
}
}
code doPost
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html");
if (username.equals("usr") && password.equals("pass")) { //line 45
HttpSession sess = request.getSession();
sess.setAttribute("username", username);
} else {
out.println("Wrong input data");
}
}
I suggest you use try-catch and catch the exception and write could for when the exception is caught to deal with the problem. Like giving the user an error message. If the error message always occurs there might be a logical error in your code. What confuses me though is that there is no code at line 45. It seems as though you left a space.
I'm new to servlets and all this topic so sorry if it's a bit messy!
I'm trying to send a value from servlet to javascript or get value of a servlet method in java script.
I'm not sure about the doGet! am I doing it right ? getting the value of fields and sending the result to javascript?
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String passengerCount = request.getParameter("passengerCount");
String departureSchedule = request.getParameter("schedule");
String arrivalSchedule = request.getParameter("returnschedule");
HttpSession session = request.getSession(true);
int departureSID = 0;
int passengerCountInt = 0;
userID = 0;
int arrivalSID = 0;
try {
departureSID = Integer.parseInt(departureSchedule);
passengerCountInt = Integer.parseInt(passengerCount);
userID = Integer.parseInt(session.getAttribute("userID").toString());
arrivalSID = Integer.parseInt(arrivalSchedule);
} catch (Exception e) {
}
if (departureSID != 0) {
ScheduleBean departureSb = new ScheduleBean();
departureSb.selectSchedule(departureSID);
int departureRoute = departureSb.getRouteID();
RouteBean routeB1 = new RouteBean();
routeB1.selectRoute(departureRoute);
double routeCharge = routeB1.getCharge();
double totalDCharge = routeCharge * passengerCountInt;
ReservationBean rb = new ReservationBean();
UserBean us = new UserBean();
if (arrivalSchedule == null) {
rb.saveOneWayReservation(departureSID, userID, totalDCharge, passengerCountInt, "TICKET");
} else {
departureSb.selectSchedule(arrivalSID);
int arrivalRoute = departureSb.getRouteID();
routeB1.selectRoute(arrivalRoute);
double arrivalRouteCharge = routeB1.getCharge();
totalDCharge += arrivalRouteCharge * passengerCountInt;
rb.saveRoundReservation(departureSID, arrivalSID, userID, totalDCharge, passengerCountInt, "TICKET");
}
ScheduleBean sbb = new ScheduleBean();
sbb.selectSchedule(rb.scheduleID);
AirBean bbb = new AirBean();
bbb.selectAir(sbb.getAirID());
String AirCode = bbb.getAirCode();
String username = session.getAttribute("username").toString();
int referenceNumber = rb.reservationID + 100;
rb.updateTicketNumber(AirCode + "-" + username + "-" + String.valueOf(referenceNumber));
out.println("<html>");
out.println("<head>");
out.println("<title>Make payment</title>");
out.println("<script type='text/javascript' src='js/jquery-1.5.2.min.js'></script>");
out.println("<script type='text/javascript' src='js/payment.js'></script>");
out.println("<script src='http://code.jquery.com/jquery-latest.min.js'></script>");
out.println("<link type='text/css' href='css/style.css' rel='Stylesheet' />");
out.println("</head>");
out.println("<body>");
out.println("<div class='bg-light' style='width: 200px; height: 200px; position: absolute; left:50%; top:50%; margin:-100px 0 0 -100px; padding-top: 40px; padding-left: 10px;'>");
out.println("<input id='reservationID' style='display: none' value='" + rb.reservationID + "' />");
out.println("<div>Credit Card Number : </div>");
out.println("<div><input id='creditcard' onKeyPress='return checkIt(event);' type='text' name='creditcard' maxlength='16' /></div>");
out.println("<div>ExpirationDate : </div>");
out.println("<div><input id='expirationDate' type='text' onKeyPress='return checkIt(event);' name='expirationDate' maxlength='4' /></div>");
out.println("<input type='hidden' id='FormName' name='FormName' value='" + HiddenValue + "'>");
out.println("<div><input id='somebutton' type='button' name='buttonsave' value='Make Payment' onclick='makePayment(" + rb.reservationID + ");' /></div>");
out.println("<div><input type='button' name='buttoncancel' value='Cancel Payment' onclick='cancelPayment(" + rb.reservationID + ");' /></div>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
}
} finally {
out.close();
}
}
I'm trying to get the value of the two input fields process on them and send the result to javascript
Servlet doGet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
creditno = request.getParameter("creditcard"); //name of the input field, not id
expiration = request.getParameter("expirationDate"); //name of the input field should be expirationDate
UserBean us = new UserBean();
boolean check = us.checkCC(userID, creditno, expiration); // process the fields
if (check == true) {
CCA = "1";
} else {
CCA = "0";
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(CCA); // Write response body.
}
Servlet doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
Javascript:
var tempresp;
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('MakeReservation', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
alert(responseText);
tempresp=responseText;
});
});
});
Thanks In Advance!
you have your java right, it is request.getParameter(...). However your not sending any data using javascript. If you want to send a "GET" request then use the code you have but make the following change:
$.get('MakeReservation?creditcard=12345&expirationDate=11%2F14', ....);
I would look up some JQuery tutorials on using the get and post methods. Also you may want to comment out that code you have and just test sending across some variables to get the hang of things before you dive right into that java side of things.
You're not sending any parameters to the Servlet. Even if you do, you'll encounter an IllegalStateException. It is because you're writing to the response body, using out.println(), and then setting headers.
The statement
finally {
out.close();
}
also flushes the output stream, preventing you from writing any response headers.
Set any headers before writing to the response body and pass the required parameters in $.get
$.get('MakeReservation', {passengerCount: 2, arrivalSchedule: 123}, function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
alert(responseText);
});
I have a little bug that I hope someone can solve for me.
servlet1:
The story here is simple - I created a form and inside it an image. When you click this image information should be submitted to servlet2.
public void f1(HttpServletRequest request, HttpServletResponse response) throws
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html></br>");
out.print("<script language='javascript' type='text/javascript'
src='functions.js'></script></br>");
out.print("<body></br>");
out.print("<form method='post' name='mainForm' action='servlet2'><br/>");
out.print("<img id='someId' src='someSrc' onclick='submit()'/><br/>");
out.print("<label id='gameStatus'>Welcome!</label></br>");
out.print("</form></br>");
out.print("</body>\n</html></br>");
}
OK, I clicked the image and information is now submitted (I suppose)
servlet2:
Here I would just like to print out the parameters submitted earlier.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Enumeration parameters = request.getParameterNames();
while (parameters.hasMoreElements())
{
out.print((String)parameters.nextElement() + "<br/>");
}
}
unf. my output is null so i guess information was not submitted. The question is why? any typos? or a logical prob?
Thank you!
What information you are trying to pass? I don't see any input field in your form.
Kindly try to add input in your form. Let us see if it is displayed in your second servlet.
out.print("<form method='post' name='mainForm' action='servlet2'><br/>");
out.print("<input type='text' name='param1' value='test' /><br/>");
out.print("<img id='someId' src='someSrc' onclick='submit()'/><br/>");
out.print("<label id='gameStatus'>Welcome!</label></br>");
Check if param1 is displayed.