I am making an application which would be able to count the numbers written in formulas. In html I have put this:
<input type="text" size="20" id="number2" onblur="validate2()"
onFocus = "document.getElementById('msg2').innerHTML = ' '">
<br>
<div id = "message1"> </div>
I have created a javascript which is firstly validating the datas and later inserts them into the 'answer-formula':
function validate2() {
var idField2 = document.getElementById("number2");
var data2 = "number2=" + encodeURIComponent(idField2.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(data2);
}
function inserter2() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("message1").innerHTML = "<div style=\"color:red\">Zła nazwa</div>";
document.getElementById("org").value = ''
}
else
document.getElementById("org").value = msg2
}
}
}
And here's my code in which is sending it as doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET");
response.setContentType("text/html");
Writer out = response.getWriter();
String num2 = request.getParameter("number2");
System.out.println(num2);
String org = new String();
if(num2.matches("[\\p{Punct}\\d]+")) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
org = engine.eval(num2).toString() + " (" + request.getMethod() + ")";
} catch (Exception e) {
e.printStackTrace();
}
}
out.write(org != null ? org : "");
}
If we change all these things into the Post, this code will work, but now as it is with GET, it doesn't work at all. Another strange situation is that the formula with POST can read the written things in formula, but as we are using GET, the program see formula source as null.
If you send it as get, you need to put formula into request. This expression:
req.send(data2);
doesn't make sense when you send GET request, as GET request cannot contain any payload except in request string. So you have to add payload to your url. Something like this:
var url = "Validator/?" + data2;
req.open("GET", url, true);
req.onreadystatechange = inserter2;
req.send();
Hope that helps.
Related
I am communicating through web view. My question is to send the pictures from the mobile phone to the web view.
I call API here. I don't know how to send it to the web view. I know how to send only the Key,Value,which consists of a string.
The code I'm taking pictures of phone.
let imagePicker: UIImagePickerController! = UIImagePickerController()
let imagePicker: UIImagePickerController! = UIImagePickerController()
var captureImage: UIImage!
var flagImageSave = false
#IBAction func btnLoadImageFromLibray(_ sender: UIButton) {
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
flagImageSave = false
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}else{
myAlert("photo album inaccessable", message: "application cannot access the photo album")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as NSString as String){
captureImage = info[UIImagePickerControllerOriginalImage] as! UIImage
if flagImageSave {
UIImageWriteToSavedPhotosAlbum(captureImage, self, nil, nil)
}
imgView.image = captureImage
}else if mediaType.isEqual(to: kUTTypeMovie as NSString as String){
if flagImageSave {
videoURL = (info[UIImagePickerControllerMediaURL] as! URL)
UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)
}
}
self.dismiss(animated: true, completion: nil)
}
API code being received by server on Sping Project
#RequestMapping(value="/sendimage", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> pr_image(HttpServletRequest webRequest
, #RequestParam(value="image", required=false) MultipartFile image
) {
Map<String, Object> param = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> validationMap = ValidationUtils.ValidationOfKeys(webRequest);
if (!validationMap.get("res").equals("sucess")) return validationMap;
String num = (webRequest.getParameter("num") != null) ? webRequest.getParameter("num") : "";
String imagePath = "";
if (image != null) {
String Extension = Config.USER_PROFILE_IMAGE_EXT;
String fileName = "_" + Utils.getCurrentTime("yyyyMMddHHmmssSSS");
imagePath = Define.CONTENTS_FILE_PATH_4 + fileName + Extension ;
File saveDir = new File(Define.CONTENTS_SAVE_PATH + Define.CONTENTS_FILE_PATH_4);
if (!saveDir.isFile()) saveDir.mkdirs();
image.transferTo(new File(Define.CONTENTS_SAVE_PATH + imagePath));
String fileName_thumbnail = fileName + "_thumb" + Extension;
File thumbnail = new File(Define.CONTENTS_SAVE_PATH + Define.CONTENTS_FILE_PATH_4 + fileName_thumbnail);
thumbnail.getParentFile().mkdirs();
Thumbnails.of(saveDir + "/" + fileName + Extension).size(Config.USER_PROFILE_IMAGE_WIDTH, Config.USER_PROFILE_IMAGE_HEIGHT).outputFormat("jpg").toFile(thumbnail);
}
...
How can I transfer pictures with my data to spring server?
I have to send not just images, but also numbers in strings. Look at my server code.
Thanks you in advance
You can solve this problem by using the Alamofire module.
You can add 'Alamofire', '~> 4.8.2' in podfile
pod install
I'm use Alamofire version 4.8.2
Usage
func ImageUpload(_ image: UIImage) {
guard image.jpegData(compressionQuality: 0.9) != nil else {
self.dismiss(animated: true, completion: nil)
return
}
let imagedata = image.jpegData(compressionQuality: 0.9)
let uploadDict = ["num": "123456789"] as [String:String]
let headers: HTTPHeaders = ["key":"val"] // Use this if you need to add api headers
Alamofire.upload(multipartFormData: { MultipartFormData in
MultipartFormData.append(imagedata!, withName: "image" , fileName: "image.jpg" , mimeType: "image/jpg")
for(key,value) in uploadDict{
MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)}
},to: "\(url)", headers: headers, encodingCompletion: {
EncodingResult in
switch EncodingResult{
case .success(let upload, _, _):
upload.responseJSON { response in
guard let json = response.result.value! as? [String: Any] else {
return
}
print(json)
}
case .failure(let encodingError):
print("ERROR RESPONSE: \(encodingError)")
}
})
}
use UIImageJPEGRepresentation to convert UIImage to NSData, and upload use
guard let data = UIImageJPEGRepresentation(image, 0.8) else {
return
}
Alamofire.upload(multipartFormData: { (form) in
form.append(data, withName: "image", mimeType: "image/jpg")
}, to: url) { (result) in
}
Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String s = request.getAttribute("stopName").toString();
response.getWriter().write(s);
}
Ajax Code
function makeRequest(i) {
var stopName = document.getElementById('newStopName' + i).value;
var Longitude = document.getElementById('newLongitude' + i).value;
var Latitude = document.getElementById('newLatitude' + i).value;
var Description = document.getElementById('newStopDesc' + i).value;
document.getElementById('hidnewStopName' + i).value = stopName;
document.getElementById('hidnewLongitude' + i).value = Longitude;
document.getElementById('hidnewLatitude' + i).value = Latitude;
document.getElementById('hidnewStopDesc' + i).value = Description;
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "Edit_Route", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send("stopName="+encodeURIComponent(stopName));
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
alert(xmlHttpRequest.responseText);
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
i want send StopName and and again send to client using ajax please help me using javascript not jquery.Actually i want send data and save it to database that s way i want test it
I think this might be come because u have get parameter in wrong way.
String stopName = request.getParameter("stopName") != null ? request.getParameter("stopName").toString() : "null value";
it will also handle the null condition.
try this code.
Is the servlet path correct in ajax code ?
I mean "/Edit_Route" not "Edit_Route"
Maybe the ajax can not found your servlet ,i think
my data:
var test = {cars : []};
var cars = []
cars.push({
"name" : "Ford",
"year" : "2000"
});
cars.push({
"name" : "Audi",
"year" : "2002"
});
test.cars = cars;
var json = JSON.stringify(test);
$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
alert('Success');
})
In Java I get the "json" variable as parameter key, but no value.
public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
for(Object a : req.getParameterMap().keySet()) {
System.out.println(a + " - " + req.getParameter((String)a));
}
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} -
This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. I need to have a specific key : req.getParameter("cars")
Change it to:
$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
alert('Success');
You shouldn't have stringified the JSON at all. The whole JSON object test is supposed to be treated as the request parameter map. Just pass the JSON object unmodified.
$.get('/myservlet/', test, function(data) {
// ...
});
This way it's available in the servlet as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("cars[" + i + "][name]");
if (name == null) break;
String year = request.getParameter("cars[" + i + "][year]");
// ...
}
Update
Your question could be possible duplicate of
READ JSON String in servlet
Previous answer
I assume you are trying to post JSON to the servlet, if thats the case read on.
You would have to check for request body instead of request parameter. Something like
BufferedReader buff = req.getReader();
Check if this works for you
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
BufferedReader buff = req.getReader();
char[] buf = new char[4 * 1024]; // 4 KB char buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
}
Note that I have checked the above code for syntax errors. I hope you get the idea.
I have a REST Server in Java JAX-RS and an HTML page.
I want to send a JSON array, a username, and an accountID from the HTML page through an xmlhttp POST request by making all of them a single big String so I can use the xmthttp.send() method.
The HTML sending code is:
function sendData() {
var req = createRequest();
var postUrl = "rest/hello/treeData";
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
var accID = "onthespot";
var username = "alex";
req.open("post", postUrl, true);
req.setRequestHeader("Content-type","text/plain");
req.send("data=" + JSON.stringify(dsdata) + "&username=" + username + "&accID=" + accID);
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
And the Server JAX-RS code is:
#Path("/treeData")
#POST
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String storeTreeData(
#QueryParam("data") String data,
#QueryParam("username") String username,
#QueryParam("accID") String accID) {
System.out.println("Data= " + data + "\nAccID= " + accID + "\nUsername= " + username);
return "Done";
}
The problem is that all the variables are printed as null..
the storeTreeData function should find the data , username , accID variables through #QueryParam and store them isn't that right?
Anyone know what's the problem here?
PS:The xmlhttp request is initiallized correctly and the connection is made but the parameters are not passed on the server.
What you try to do:
#QueryParam is used to get parameters from the query of the request:
http://example.com/some/path?id=foo&name=bar
In this example id and name can be accessed as #QueryParam.
But you are sending the parameters in the body of your request.
What you should do:
To get the parameters from the body, you should use #FormParam together with application/x-www-form-urlencoded:
#Path("/treeData")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public Response storeTreeData(
#FormParam("data") String data,
#FormParam("username") String username,
#FormParam("accID") String accID) {
// Build a text/plain response from the #FormParams.
StringBuilder sb = new StringBuilder();
sb.append("data=").append(data)
.append("; username=").append(username)
.append("; accId=").append(accID);
// Return 200 OK with text/plain response body.
return Response.ok(sb.toString()).build();
}
Edit:
You should also use
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in your JavaScript code.
I am sorry to ask this but i've been working on this for hours and I can't figure it out on my own.
I have to use json for part of a project and I was able to get it to work but now it's not returning it back to the right jsp but instead just displaying the json jsp. I am pretty sure it is how I am receiving the json.
here are screen shots of what is happening:
this is the jsp that I need to use ajax on, I am wanting to populate the second dropdown using ajax:
this is what is happening instead, (it's the right data):
here is the code(sorry it's long):
-the jsp I am doing ajax on
<script type="text/javascript">
/**
* Utility function to create the Ajax request object in a cross-browser way.
* The cool thing about this function is you can send the parameters in a two-dimensional
* array. It also lets you send the name of the function to call when the response
* comes back.
*
* This is a generalized function you can copy directly into your code. *
*/
function doAjax(responseFunc, url, parameters) {
// create the AJAX object
var xmlHttp = undefined;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
} catch (othermicrosoft){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {}
}
}
if (xmlHttp == undefined && window.XMLHttpRequest) {
// If IE7+, Mozilla, Safari, etc: Use native object
xmlHttp = new XMLHttpRequest();
}
if (xmlHttp != undefined) {
// open the connections
xmlHttp.open("POST", url, true);
// callback handler
xmlHttp.onreadystatechange = function() {
// test if the response is finished coming down
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// create a JS object out of the response text
var obj = eval("(" + xmlHttp.responseText + ")");
// call the response function
responseFunc(obj);
}
}
// create the parameter string
// iterate the parameters array
var parameterString = "";
for (var i = 0; i < parameters.length; i++) {
parameterString += (i > 0 ? "&" : "") + parameters[i][0] + "=" + encodeURI(parameters[i][1]);
}
// set the necessary request headers
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameterString.length);
xmlHttp.setRequestHeader("Connection", "close");
// send the parameters
xmlHttp.send(parameterString);
}
}//doAjax
/**
* Submits the guess to the server. This is the event code, very much
* like an actionPerformed in Java.
*/
function getSeats() {
// this is how you get a reference to any part of the page
var packInput = document.getElementById("pack");
var pack = packInput.value;
// while (packInput.childNodes.length > 0) { // clear it out
// aSeats.removeChild(aSeats.childNodes[0]);
// }
// an example of how to do an alert (use these for debugging)
// I've just got this here so that we know the event was triggered
//alert("You guessed " + seat);
// send to the server (this is relative to our current page)
// THIS IS THE EXAMPLE OF HOW TO CALL AJAX
doAjax(receiveAnswer, "ttp.actions.Sale3PackAction.action",
[["pack", pack]]);
// change the history div color, just 'cause we can
// var randhex = (Math.round(0xFFFFFF * Math.random()).toString(16) + "000000").replace(/([a-f0-9]{6}).+/, "#$1").toUpperCase();
// document.getElementById("history").style.background = randhex;
}
/**
* Receives the response from the server. Our doAjax() function above
* turns the response text into a Javascript object, which it sends as the
* single parameter to this method.
*/
function receiveAnswer(response) {
// show the response pack. For this one, I'll use the innerHTML property,
// which simply replaces all HTML under a tag. This is the lazy way to do
// it, and I personally don't use it. But it's really popular and you are
// welcome to use it. Just know your shame if you do it...
var messageDiv = document.getElementById("aSeats");
messageDiv.innerHTML = response.aSeats;
// replace our history by modifying the dom -- this is the right way
// for simplicity, I'm just erasing the list and then repopulating it
var aSeats = document.getElementById("aSeats");
while (aSeats.childNodes.length > 0) { // clear it out
aSeats.removeChild(aSeats.childNodes[0]);
}
for (var i = 0; i < response.history.length; i++) { // add the items back in
var option = aSeats.appendChild(document.createElement("option"));
option.appendChild(document.createTextNode(response.history[i]));
}
// reset the input box
//document.getElementById("pack").value = "";
}
</script>
<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>
What Packages do you want to see?
<form method="post" action="ttp.actions.Sale3PackAction.action">
<select name="packid" id="pack">
<% for (Conceptual_Package cp: cpList) { %>
<option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
<% } %>
</select>
<input type="submit" value=" next " onclick="getSeats();"/>
</form>
<!--new-->
Available Seats:
<select name="eventSeatid" id="aSeats">
<option value="aSeats"></option>
</select>
<input type="button" value=" Add "/>
Selected Seats:
<form method="post" action="ttp.actions.sale4Action.action">
<select name="eventSeat2id" size="10" id="seat2">
<option value="seat2"></option>
</select>
</form>
<jsp:include page="/footer.jsp"/>
-the json jsp
<%#page contentType="text/plain" pageEncoding="UTF-8"%>
<jsp:directive.page import="java.util.*"/>
{
"history": [
<% for (String newSeats: (List<String>)session.getAttribute("newSeats")) { %>
"<%=newSeats%>",
<% } %>
]
}
-the action class
public class Sale3PackAction implements Action{
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String packid = request.getParameter("packid");
System.out.println("packid is: " + packid);
Conceptual_Package cp = Conceptual_PackageDAO.getInstance().read(packid);
request.setAttribute("cp", cp);
List<Physical_Package> ppList = Physical_PackageDAO.getInstance().getByConceptual_Package(cp.getId());
request.setAttribute("currentPack", ppList);
session.setAttribute("aSeats", null);
//return "sale3Pack_ajax.jsp";
//new
//HttpSession session = request.getSession();
// ensure we have a history
for (Physical_Package pPack: ppList){
try {
if (session.getAttribute("aSeats") == null) {
LinkedList aSeatsList = new LinkedList<String>();
session.setAttribute("aSeats", aSeatsList);
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
} else {
LinkedList aSeatsList = (LinkedList) session.getAttribute("aSeats");
aSeatsList.add("Sec: " + pPack.getVenueSeat().getRowInVenue().getSectionInVenue().getSectionNumber() + " Row: " + pPack.getVenueSeat().getRowInVenue().getRowNumber() + " Seat: " + pPack.getVenueSeat().getSeatNumber());
session.setAttribute("newSeats", aSeatsList);
}
} catch (DataException ex) {
Logger.getLogger(Sale3PackAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
// next jsp page to go to
return "AjaxPack_json.jsp";
}
}
Hehe, I think we've all been in your place. Spending hours on something just to eventually realize that we overlooked some simple detail.
Read comments for more information...