how to pass a value from servlet in javascript - java

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);
});

Related

JAVA - get response from system to the UI

I'm new to java and I have servlet which connect to some system and get data, while debug the code I see that I was able to connect and get the data, ( I dont get any error) . I use the following code :
try {
urlConnection.connect();
} catch (IOException e) {
String messagePrefix = "Connection error: ";
LOGGER.error(messagePrefix, e);
}
OutputStream clientOutStream = responseToClient.getOutputStream();
copyStream(backendInStream, clientOutStream);
responseToClient.setStatus(backendResponseCode);
int backendResponseCode = urlConnection.getResponseCode();
InputStream backendInStream = null;
try {
if (backendResponseCode < 400) {
backendInStream = urlConnection.getInputStream();
}
} catch (IOException e) {
String messagePrefix = "Input stream error: ";
LOGGER.error(messagePrefix, e);
}
Now I have this simple index.html and my question how should I print the data back to the browser ?
( I wasnt able to copy the html file as code :(
Any idea how to pass the response to the UI , I try to add response tag and put the variable as global without success...
Yes you can send the response using dispatcher or httpsession and use jsp to get the response in UI
in your back end simply use
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("backendresponse",backendresponse))
}
and in your jsp you can get and store that data in an arraylist as
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
Now you can use this list to populate data in any tag using <%= %> as this is equivalent to a print statement as any expression say
<%for(int i=0;i<list.size();i++)
{%>
<%=list.get(i).getData() %>
<%}%>
will print the response in your browser
UPDATE
in your servlet you can get the parameters as
String url=request.getParameter("url")
Class obj=new Class(url)
session.setAttribute("obj",obj);
response.sendredirect("disp.jsp")
in your disp.jsp
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
<html>
<head>
</head>
<body>
<%for(int i=0;i<list.size();i++)
{%>
<h1> <%=list.get(i).getData() %></h1>
<%}%>
</body>
</html>
You should have doGet method which has PrintWriter taking each line of the HTML:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
.
.
.
}

Getting parameter from a doGet in Servlet using Ajax

I want to get the parameter from a input form which is set on my index.html:
GET:<br>
<input type="text" size="20" id="name2" onblur="validate2()"
onFocus = "document.getElementById('msg2').innerHTML = ' '">
<div id = "msg">&nbsp</div>
On my servlet I want to get this parameter by request.getparameter("name2")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Get");
System.out.println(request.getParameter("name2"));
if(!request.getParameter("name2").equals("")) {
numer = request.getParameter("name2");
serviceConnection(request, response);
}
}
but when I am starting my application the system.out.println is just printing the null variable.
On my ajaxvalidator javascript file I wrote this:
function validate2() {
var idField = document.getElementById("name2");
var data = "name2=" + encodeURIComponent(idField.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("GET", url, true);
req.onreadystatechange = inserter2
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
function inserter2() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("msg").innerHTML = "<div style=\"color:red\">Wadliwa nazwa</div>";
document.getElementById("org").value = '';
} else {
document.getElementById("org").value = msg1;
}
}
}
How to solve this problem?
Your mistake is here:
req.open("GET", url, true);
// ...
req.send(data);
In HTTP GET, the data needs to go in request URL query string, not in request body. Sending data in request body works for POST only. The request URL query string is the part after ? in request URL.
So, this should do:
req.open("GET", url + "?" + data, true);
// ...
req.send();
Note that you can remove the request body content type header.
See also:
doGet and doPost in Servlets
Using java.net.URLConnection to fire and handle HTTP requests
How to use Servlets and Ajax?

How do I return a string from a servlet without leaving the page?

Here's the picuture:
I have a html/jsp page with a form on it.
<div id = "divAttributes">
<form id = 'fid' method = "post" action = "RunQuery">
Id Number: <input type= "text" name = "foo" id = "txtFoo"/><br/>
<input type = "checkbox" id = "chboxZap" value = "zap"/>Foo<br/>
<input type = "checkbox" id = "chboxBar" value = "bar"/>Bar<br/>
<input type= "submit" id = "btnSubmit" value = "submit" onclick = "setDisabled('divAttributes', true)"/><br/>
</form>
</div>
When the user presses the submit button, I want to send the information contained in the form to a servlet, which will then do some processing and return a string.
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
ReturnCode rc = world.hello.MyMainClass.wait(request.getParameter("foo"));
/*I want to return the RC, which is a bool, a string, and another object, which in this case is a string*/
}
That string should then be sent to a different servlet, which then saves a file.
I already have the servlet to the file saving:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
String s = new String(request.getParameter("data"));
InputStream is = new ByteArrayInputStream(s.getBytes());
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
I have two questions:
The second servlet, when called, doesn't redirect to a new page. It just instantly provides the download dialog box. However, when I call the first servlet, it provides a blank html page. Why?
How do I return values from the servlet to the HTML page that called it, and access them from there?
JavaScript and more specifically, Ajax will help you. If you include a library with good Ajax support -- such as jQuery -- in the HTML, you can call your servlet(s) while staying on the same page.
So, instead of submitting the form from the button, you can invoke a JavaScript function that uses nested Ajax posts to the two servlets:
function submitForm() {
$.post( 'url/to/firstServlet', { text: $('#txtFoo').val() }, function(dataFromFirst) {
$.post( 'url/to/secondServlet', { data: dataFromFirst }, function(dataFromSecond) {
// handle response from second servlet
});
});
}
Use AJAX!
AJAX allows you to create an Ajax Javascript object, and return the HttpResponse to that object.
eg.
function myAjaxRequest()
{
var xmlhttp; /*our ajax object*/
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
setVisible('loading', true) ;
/*this function called when ajax state changes*/
xmlhttp.onreadystatechange=function()
{
/*when the query has completed successfully*/
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
/*now you can do what you want with your response text!*/
var mystring= xmlhttp.responseText;
alert(mystring);
}
}
/*the URL query we want to run*/
var query = "RunQuery?foo="+$('#txtFoo').val();
alert(query);
/*AJAX object runs the query*/
xmlhttp.open("GET", query, true);
xmlhttp.send();
}

Java Servlet nullPointerException login logout sessions

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.

Getting information from servlet created html

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>");
}
}
}

Categories