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"> </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?
Related
I have created a webpage (JSP & AngularJS) that contains a form allowing the user to attach a file and send it to the server (Java Servlet). The server will then take that file and forward it to an API by attaching it to a HTTP POST request.
The code I have at the moment within the JSP File and the AngularJS Controller appears to be working correctly. Once the file is sent from the webpage to the server, I can then access some of the file details (field name and size but not content type or file name) in the Java Servlet and print them out via System.out.println().
The problem I am facing at the moment is trying to find a way how to attach the FileItem (attachment) to the HttpPost (postRequest).
I have read a number of examples online on how files are uploaded, however these examples always assume the file will be stored on a disk on the server instead of being forwarded elsewhere.
This is my current code (the problem seems to be in the Java Servlet section):
JSP File:
<form name="issueForm">
<input id="attachment" class="form-control" type="file" data-ng-model="attachment"/>
<button type="submit" data-ng-click="setAttachment()">Create Issue</button>
</form>
AngularJS Controller:
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
$scope.setAttachment = function()
{
var attachment = $scope.attachment;
var fd = new FormData();
fd.append('attachment', attachment);
$http({
url: 'IssueAttachment',
method: 'POST',
transformRequest: function(data, headersGetterFunction) { return data; },
headers: { 'Content-Type': undefined },
data: fd
})
.success(function(data, status) { alert("Success: " + status); })
.error(function(data, status) { alert("Error: " + status); });
}
Java Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItem attachment = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) { System.out.println("Not Multipart Content!"); }
else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(new ServletRequestContext(request));
} catch (FileUploadException e) { e.printStackTrace(); }
try {
//Get attachment and print details
//This section prints "attachment", 9, null, null in that order).
attachment = (FileItem) items.get(0);
System.out.println("Field Name: " + attachment.getFieldName());
System.out.println("Size: " + attachment.getSize());
System.out.println("Content Type: " + attachment.getContentType());
System.out.println("File Name: " + attachment.getName());
} catch (Exception e) { e.printStackTrace(); }
//Create a HTTP POST and send the attachment.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(API_URL);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addPart("attachment", new FileBody(attachment)); //THE ERROR OCCURS HERE.
postRequest.setEntity(entity.build());
try {
HttpResponse response = httpClient.execute(postRequest);
} catch (IOException e) { e.printStackTrace(); }
}
}
Ended up using the following:
FileItem file = (FileItem)items.get(0);
//Create a temporary file.
File myFile = File.createTempFile(base, extension);
//Write contents to temporary file.
file.write(myFile);
/**
* Do whatever you want with the temporary file here...
*/
//Delete the temporary file.
myFile.delete(); //-OR- myFile.deleteOnExit();
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();
}
I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute() and request.getParameter() and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
and my processRequest() code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
Can you please help me to process this request and finally return this poor JSON!
BTW, Servlet doesn't recognize command parameter. It gets null. But there is such parameter in AngularJS function.
Try using the javax.json.JsonObject as follow:
JsonObject jo=Json.createObjectBuilder()
.add("id", testcaseId)
.add("title", testcase.getTestcaseName())
.add("testscenario", testcase.getTestcaseDescription()).build();
Then set the response content type to json and send your json object in the response:
response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();
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);
});
my ajax some how looks like this :
function getXMLHttpRequest() {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "http://abc.com:8080/someservletServlet/", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler(xmlHttpRequest) {
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("xml").value = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
} but somehow the servlet is not bringing the response it should bring. can you help. what could be the possible error.
Ajax is the way to go.Because if you submit the request, page will refresh whether its same page or different.
If you still want to achieve it using without using ajax and refresh of page is fine with you then see if you have this kind of code in your servlet which is causing to forward it to some other page
String nextJSP = "nextPage.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
If you need to load some data from some other URL you'll need to send an AJAX request (explain where to get data from) and handle the AJAX response (explain what to do with the fetched data). To provide for a browser-compatible solution you'd better use some well-known JS library. For example, you could use jQuery in which case your script could look like:
$.ajax({
url: "servletURL",//servlet URL to post data to
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {id : idOfData},//data to be sent to the server
dataType: "xml"//type of data returned
}).done(function(data) {
//do something with XML data returned from server
});
With this approach you need to call the above JS code, probably wrapped in a JS function, on some JS event, i.e. click, and handle response data, for example, by appending its contents to your text area.