download a file on ajax success electron, jsp - javascript

i connected electron, jsp for login, sign up. electron is front side(html,js), jsp(jsp, java) is server side.
now i'm trying to download a file from server to electron.
(here i set a file (bullet01.png) for test.)
flow:
when user clicks a button(ajax get request)
server find file which from url parameter
success method gets result
myscript.js
function downloadClick() {
$.ajax({
url: 'http://localhost:8090/curriculum1.4/login_controller.jspx?cmd=downloadFile&bFile=bullet01.png',
type: 'get',
//dataType: 'json',
success: function(resp) {
console.log("success");
console.log(resp);
//window.open("C:\Users\CP\Desktop\테스트\core5.0.14\out\artifacts\unnamed\curriculum1.4\filedir\bullet01.png");
},
error: function(xhr, status, error) {
alert("err")
}
});
}
when i execute on jsp it downloads ok but from electron it doesn't download anything.
here is the code
public void downloadFile(ViewMeta view) throws IOException {
DataSet input = view.getInputDataSet();
HttpServletRequest request = view.getHttpServletRequest();
HttpServletResponse response = view.getHttpServletResponse();
String bFile = new String(input.getText("bFile").getBytes("UTF-8"), "ISO-8859-1");
String filePath = request.getServletContext().getRealPath("/curriculum1.4/filedir");
response.setHeader("Content-Disposition", "attachment;filename=\"" + bFile + "\";");
File file = new File(filePath + "/" + bFile);
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream servletOutputStream = response.getOutputStream();
byte b[] = new byte[1024];
int data = 0;
while ((data = (fileInputStream.read(b, 0, b.length))) != -1) {
servletOutputStream.write(b, 0, data);
}
servletOutputStream.flush();
servletOutputStream.close();
fileInputStream.close();
}
test.html in electron
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script language="JavaScript" type="text/javascript" src="js/jquery-3.2.1.js"></script>
<script src="js/myscript.js"></script>
<script>if (window.module) module = window.module;</script>
<body>
<h1 class="signUpTitle">test page</h1>
<!-- <input type="button" value="버튼" class="signUpButton" onclick="showOk()" > -->
<a onclick="downloadClick()">file</a>
</body>
</html>

Related

HTML page not rendering from Flask after AJAX call

I want to send a JavaScript variable with a image that a user will upload to my Flask file where processing will be done. So I am using Formdata and a AJAX call for the same. But after the data and image is received in flask and processing is done, I am unable to render a HTML page in flask which will display the processed image .
Java Script Code :
formdata = new FormData();
jQuery("#image_to_upload").on("change", function() { // On Change Of image upload
var file = this.files[0];
if (formdata) {
formdata.append("file", file);
formdata.append("array", filtersActive);
jQuery.ajax({
url: "/object-detect-uploader",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(){}
});
}
});
Flask Code :
#app.route("/object-detect-uploader", methods = ['GET', 'POST'])
def upload_object_detection():
detect_objs = request.values['array'].split(",")
d_array= [0 for i in range(6) ]
for i in detect_objs:
d_array[int(i)] = 1
for upload in request.files.getlist("file"):
filename = upload.filename
# This is to verify files are supported
ext = os.path.splitext(filename)[1]
if (ext == ".jpg") or (ext == ".png"): #File extention check
print("File supported moving on...")
ans=(object_detection_module.object_detection(upload,d_array))
else:
render_template("Error.html", message="Files uploaded are not supported...")
print("Rendering")
return render_template("index.html", result = ans)
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<br>
<br>
<h1><center>Output</h1></center>
<br>
<img src="data:image/png;base64, {{result[0]}}" >
<br>
<br>
<h2> No of objects = {{ result[1] }}</h2>
</body>
</html>
An Ajax call is an asynchronous request initiated by the browser that does not reload the page when it receives the server response.
IMO, since you want to render the template, you should not use AJAX, just use a normal <form> element or create a form programmatically, fill the data, then submit with jQuery('selector').submit().

I wanted to know how can I do get response and post response using ajax and jquery on jsp servlet web project

I wanted to know how can i do a get and post from a servlet and use jquery ajax i.e. in the jsp page to get response and post it .I have done doget .Also if possible I want to remove jstl from my jsp page.Please help me .And thanks in advance
Here is my controller class
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//get the data from database ie the model class
try {
List<Script> scriptitems=modelDBUtil.getScriptList();
request.setAttribute("scriptItems", scriptitems);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*String itemsfood[]={"biriyani","rice"};
request.setAttribute("itemsfood",itemsfood)*/;
//redirect to a different page
RequestDispatcher dispatcher =request.getRequestDispatcher("scriptviewer.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
}
Now my jsp page please help me here
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Menu</title>
</head>
<body>
<p>Script Items</p>
<c:forEach var="items" items="${scriptItems}">
${items.id} ${items.command}
</c:forEach>
<form action="appendfile.jsp" method="post">
<select name="department">
<c:forEach var="item" items="${scriptItems}">
<option value="${item.id}">${item.command}</option>
</c:forEach>
</select>
<button type="submit" id="idsubmit">Submit</button>
</form>
</body>
</html>
Here is how you can send json from JSP to Servlete please refer this code
with comments
$("#mForm").submit(function(e) { //your form ID chane it here
e.preventDefault();
var $form = $(this);
if (!$form.valid()) return false;
var url = "yourServeleteName";
$.ajax({
type: "POST", //the method you want invoke
url: "yourServeleteName", //Add here your servelete name
data: $("#mForm").serialize(), //your form ID remove default action from your form
success: function (data) //This is to handle if you want any response from Servlete
{
alert(data); //it will alret you message you send from servelete
//$("#mForm")[0].reset(); /if any form you can reset it option
}
});
});
}
Here is how you can remove jstl from my jsp page and can make it html.
you need to use these jquery cdn or you can use javascript directly.
Addtinaly you need to download Gson library to get response from servlet.
This code will work with get method.
This is how you can send your itemsfood to your html or jsp
Modify your doGet method as:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Script> scriptitems=modelDBUtil.getScriptList();
request.setAttribute("scriptItems", scriptitems);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String itemsfood[]={"biriyani","rice"};
List<String> list = Arrays.asList(itemsfood);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
And HTML or jsp code for that is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
rel="stylesheet" type="text/css" />
<link
href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
rel="stylesheet" type="text/css" />
<link rel='stylesheet' type='text/css'
href='http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' />
<link rel="stylesheet"
href="https://jqueryvalidation.org/files/demo/site-demos.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script
src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script
src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$.get("appendfile or (add your serveletName here)", function(
responseJson) {
var $select = $("#item");
$select.find("option").remove();
$.each(responseJson, function(value, key) {
$("<option>").val(key).text(key).appendTo($select);
});
});
});
</script>
<title>Menu</title>
</head>
<body>
<form name=myform id="mForm">
<select name="item" required id="item">
<option value="Select">select</option>
</select>
<button type="submit" id="idsubmit">Submit</button>
</form>
</body>
</html>

Spring Controller not returning a html page after an Ajax get Request

So I have a "discount" html page, where a user is prompted to enter a promo code, by using an Ajax GET request from the buttons OnClick, I am able to transfer this promo code to my spring controller, where I manipulate the data appropriately.
For some reason I am unable to "return" a new page from this controller, I do not get any noticeable errors on my server side but on my client side I get this error:
I am not sure if this is related or relevant.
I was wondering is my logic behind this flawed or am I not implementing the correct syntax to return a new page after the AJAX call.
Note: The AJAX request works fine as I am able to get a system.out.print to the console at the bottom of the controller with the relevant info. that I passed.
Here is my html code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function myFunction(){
var code = document.getElementById("code").value;
var price = document.getElementById("price").value;
$.ajax({
type: "GET",
url: "/calculateDiscount",
data: {
code: code
}, // parameters
contentType: "application/json; charset=utf-8",
datatype: 'json'
//alert(status);
});
}
</script>
</head>
<body>
<div>
<center>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
<input type="text" name="firstname" id="code">
<button onclick="myFunction()">Calculate Discount</button>
<a style="color:blue" th:href="#{/welcome}">HomeScreen!</a>
<br />
<!-- <a style="color:blue" th:if="${myteam != null}" th:href="#{/leaveteam/{id}(id=${myteam?.id})}">Leave Team?!</a>
-->
</center>
</div>
</body>
</html>
Controller:
#RequestMapping(value="/calculateDiscount", method=RequestMethod.GET)
#ResponseBody
public String CalculateDiscount(Model model, #RequestParam("code") String code, RedirectAttributes redirectAttributes) {
///need to calculate price if codes correct then return page with card info then after proceed call purchasebooks controller!
System.out.println("Price: " + code );
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
UserLogin user = uR.findByUserName(email);
int totalPrice = 0;
if (code.equals("Discount1010"))
{
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
int discountPrice = (int) (totalPrice * .80);
model.addAttribute("totalPrice", totalPrice);
System.out.println("Price: " + discountPrice );
}
else {
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
System.out.println("Price: " + totalPrice );
model.addAttribute("totalPrice", totalPrice);
}
return "payment";
}
The page I am trying to return:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<title>Insert title here</title>
</head>
<body>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
</body>
</html>
Any more info needed let me know.
K.
EDIT: In response to one of the answers below, I do have csrf disabled.
Here is my WebSecurityConfig class:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserLoginRepository userLoginRepository;
//http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
#Autowired
DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
//disable csrf to allow communication (we also dont need for this fyp as its not live)
}
#Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/fonts/**", "/images/**", "/css/**");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
.authoritiesByUsernameQuery("select user_name, password from user_login where user_name=?");
}
#Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
Update: #ResponseBody annotation was added to the controller method, problem still persists
I guess this is CSRF problem. You have Spring Security implemented (I can see
SecurityContexHolder class) and probably csrf enabled - this is default setting. If you want to disable it just use this
Java configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
XML:
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
But if you want to keep csrf enabled, you need to pass csrf token to ajax header. To do this, include csrf to meta tag:
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
And then include csrf to Ajax request:
var token = /*[[${_csrf.token}]]*/ '';
var header = /*[[${_csrf.headerName}]]*/ '';
$(document).ajaxSend(function(e,xhr,options) {
xhr.setRequestHeader(header, token);
});

How to call cordova plugin action synchronously in Button click in javascript

How to call cordova plugin action synchronously in Button click in java script
We need to upgrade every javascript annotation method to plugin format with synchronously.
Java - Our own plugin
public class ProjectUtility extends CordovaPlugin{
public static final String TAG = " Project Utility";
private final static String characterEncoding = "UTF-8";
DataMgnt dm = new DataMgnt();
public CordovaInterface cordovaInterface;
public ProjectUtility() {
System.out.println(" project utility");
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* #param cordova The context of the main Activity.
* #param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
cordovaInterface=cordova;
Log.v(TAG,"Init CoolPlugin dsfsdf" +cordova.getActivity().getString(R.string.app_name));
}
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final int duration = Toast.LENGTH_SHORT;
// Shows a toast
Log.v(TAG,"CoolPlugin received: dsfsdfdssdadfa"+ action);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(cordova.getActivity().getApplicationContext(), cordovaInterface.getActivity().getString(R.string.app_name), duration);
toast.show();
if(action.equals("imei"))
{
callbackContext.success(getImeiNumber());
}
else if(action.equals("app_name")){
callbackContext.success(appName());
}
else if(action.equals("service_id")){
callbackContext.success(getServiceId());
}
else
{
callbackContext.error("fail");
}
}
});
return true;
}
public String getImeiNumber()
{
TelephonyManager tm = (TelephonyManager) cordovaInterface.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String imeiId="";
try{
imeiId = tm.getDeviceId();
}
catch(Exception e)
{
imeiId="null";
e.printStackTrace();
}
return "12364589785451";
}
String getServiceId()
{
String service_id= cordovaInterface.getActivity().getString(R.string.service_id);
return service_id;
}
public String appName()
{
return cordovaInterface.getActivity().getString(R.string.app_name);
}
}
javascript :
utlity.js
We initialize common funtion to access the plugin:
window.sdpproperty = function(key,arg_array ,callback) {
cordova.exec(callback, function(err) {
callback('error');
}, "ProjectUtility", key,arg_array);
};
index.html – we accessing window.property function,
This file contain two functions,
1) we_need_like_this()
2) but_it_work_like_this_no_need_this_format()
3) sample
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
<script>
function we_need_like_this() {
var service_id,
imei;
window.sdpproperty("service_id", [], function (echoValue) {
service_id = echoValue;
alert("Inside Inside the call back exec the service id " + echoValue)
});
window.sdpproperty("imei", [], function (echoValue) {
imei = echoValue;
alert("Inside call back exec the imei " + echoValue)
});
sample(service_id, imei)
}
function sample(service_id, imei) {
alert("Inside the Sample func. Service Id " + service_id + " Imei " + imei);
}
function but_it_work_like_this_no_need_this_format() {
var service_id,
imei;
window.sdpproperty("service_id", [], function (echoValue) {
service_id = echoValue;
window.sdpproperty("imei", [], function (echoValue) {
imei = echoValue;
sample(service_id, imei)
});
});
}
</script>
</head>
<body>
<div class="app">
<div id="deviceready" class="blink">
<p class="event listening">..... App Loading....</p>
</div>
<button onclick="we_need_like_this()">We Need</button>
<button onclick="but_it_work_like_this_no_need_this_format()">We no Need</button>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/utlity.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</body>
</html>
As of Cordova Plugins dev docs the JS interface must have:
cordova.exec(function(winParam) {},
function(error) {},
"service",
"action",
["firstArgument", "secondArgument", 42, false]);
and your definition has:
cordova.exec(callback,
function(err) { callback('error'); },
"ProjectUtility",
key,
arg_array);
so the parameter key is the action to be executed on the native side.
Examining your JAVA file the actions available are these:
authencation_hash_encrypt <---- PAY ATTENTION THERE IS A TYPO!
service_id
authencation_encrypt <---- PAY ATTENTION THERE IS A TYPO!
authentication_hash_decrypt
decrypt_value
decrypt
authent_token
new_decrypt
authencation_hash_encrypt <---- PAY ATTENTION THERE IS A TYPO!
encrypt_value
encrypt_hash
So the value "key_cre" as key parameter is not present...

xmlHttpRequest GET/POST with Spring MVC

I am trying to find a workaround for using POST request, because I cannot use form, pass parameter and redirect to another page without displaying the parameter in the URL. I heard it is possible to do that via XHR GET request but I am not sure how. I have also tried it with POST.
Index.jsp (Peter is my example of POST via form, which works, but I cannot use. George is my example of GET. I can see that the function HttpGet is called and the responseText is the html of helloworld.jsp. Sam is my example of POST. I can see that the parameter is passed to the controller and added to mv but it stops short of redirecting to helloworld.jsp.)
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC - HelloWorld Index Page</title>
<script type="text/javascript">
function httpGet(theUrl)
{
var xmlHttp = null;
alert('httpGet is called');
alert(theUrl);
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
alert(xmlHttp.responseText);
return xmlHttp.responseText;
}
function doPost() {
var url = "http://localhost:8080/HelloWorld/hello";
var params = "name=Sam";
alert('Entered Sam');
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
}
</script>
</head>
<body>
<h2>Hello World</h2>
<form action="hello" id="test" method="POST" style="display:none;">
<input type="hidden" name="name" value="Eric" />
<input type="hidden" name="lastname" value="Peters" />
<button>Go to user 123</button>
</form>
<a href="javascript:;" onclick="javascript:
document.getElementById('test').submit()">Eric Peters</a><br/>
George
Sam
</body>
</html>
Controller:
package com.programcreek.helloworld.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
#RequestMapping("/hello")
public ModelAndView showMessage(
#RequestParam(value = "name", required = true) String name,
#RequestParam(value = "lastname", required = false, defaultValue = "Doe") String lastname) {
System.out.println("in controller");
ModelAndView mv = new ModelAndView("helloworld");
mv.addObject("message", message);
mv.addObject("name", name);
mv.addObject("lastname", lastname);
return mv;
}
}
Helloworld.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 4 MVC -HelloWorld</title>
</head>
<body>
<center>
<h2>Hello World</h2>
<h2>
${message} ${name} ${lastname}
</h2>
</center>
</body>
</html>
My questions are: 1) is it possible to use XHR get or post and not show the parameter in the URL? 2) which method (george or sam) is close, if any, and which files should I look at changing to make it redirect to helloworld.jsp (controller or index.jsp)? Thank you for your help.

Categories

Resources