how to retrieve data from servlet to jsp using javascript - javascript

I am new to servlets i wrote a servlet which fetches data from database and prints a table,i have a jsp page which has a button to search for employee id.
My requirement is the table should be displayed in same page where i search i.e
jsp page.I searched all day but could not find solution using javascript . I want this to be done only using javascript not jquery .thanks in advance.
Here is my jsp page
search.jsp
<html>
<head>
<script>
var request;
var date;
function data()
{
var v = document.getElementById("ele1").value;
var url = "Retrieve?ele1=" + v;
alert("v" + v);
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e)
{
alert("unable to connect to server");
}
}
function getInfo()
{
request = new XMLHttpRequest();
if (request.readyState == 4)
{
alert(val);
var response = request.responseXML;
var val = request.responseText;
document.getElementById("sun").innerHTML = val;
}
}
}
</script>
</head>
<body>
<div>
<form id="search" name="search" action="Retrieve" method="post">
<label id="search">Search By Empid</label>
<input type="text" name="ele1" id="ele1">
<input type="button" value="Get Details" onclick="data();">
</form>
</div>
<div id="sun">
</div>
</body>
this is my servlet page
Retrieve.java
public class Retrieve extends HttpServlet {
Connection con = null;
Statement st = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/name", "postgres", "admin");
st = con.createStatement();
String num = request.getParameter("ele1");
int id = Integer.valueOf(num);
PreparedStatement ps = con.prepareStatement("select * from empretrieve where Empid=?");
ps.setInt(1, id);
out.print("<table width=50% border=1>");
out.print("<caption>Result:</caption>");
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int tot = rsmd.getColumnCount();
out.print("<tr>");
for (int i = 1; i <= tot; i++) {
out.print("<th>" + rsmd.getColumnName(i) + "</th>");
}
out.print("</tr>");
while (rs.next()) {
out.print("<tr><td>" + rs.getInt(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td><td>" + rs.getString(4) + "</td><td>" + rs.getString(5) + "</td><td>" + rs.getString(6) + "</td><td>" + rs.getString(7) + "</td><td>" + rs.getString(8) + "</td><td>");
}
out.print("</table>");
System.out.println("processRequest : : ");
} catch (Exception e) {
PrintWriter out = response.getWriter();
out.println(" e : " + e);
} finally {
try {
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (Exception ex) {
}
}
}

This is working for me:
Servlet:
#WebServlet("/XTMLRequestServlet")
public class XTMLRequestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public XTMLRequestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
JSP:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XTMLREQUEST</title>
</head>
<body>
<h1>XTMLREQUEST</h1>
Response:<div id="response"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'XTMLRequestServlet', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
var el = document.querySelector("#response");
el.insertAdjacentHTML("beforeend", xhr.responseText);
console.log(xhr.responseText);
}
}
};
xhr.send(null);
</script>
</body>
</html>

Related

Creating json object in javascript and sending it to servlet for getting response

I am creating json object to save data and then sending it to the servlet. But when I try to retrieve the object and display its contents in java servlet, I am not getting any response from server. Even though a simple System.out.println() message on browser.
angular.module('TestApp').controller('PostController',
function($scope, $rootScope, $http) {
$scope.retriveDataAndConvertToJson = function() {
var collectionJsonData = new Array();
for (var i = 0; i < rowID.length; i++) {
collectionJsonData.push({
"payment_term": document.getElementById("textfield1" + rowID[i])
.getAttribute("value"),
"payment": document.getElementById("textfield2" + rowID[i])
.getAttribute("value"),
"party": document.getElementById("textfield3" + rowID[i])
.getAttribute("value"),
"amount": document.getElementById("textfield4" + rowID[i])
.getAttribute("value")
});
console.log(collectionJsonData[i].payment_term);
console.log(collectionJsonData[i].payment);
console.log(collectionJsonData[i].party);
console.log(collectionJsonData[i].amount);
console.log("==========================");
} //End of For loop
var xhr = new XMLHttpRequest();
var url = "http://" + document.location.host + "/SivaTask/processInfo";
console.log("The url is " + url);
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
var data = JSON.stringify(collectionJsonData);
xhr.send(data);
}
});
Servlet
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String contextName = req.getRequestURI();
String url = contextName.substring(contextName.indexOf('/', 2) + 1);
System.out.println(url);
String jsonData = "";
resp.setContentType("text/plain");
System.out.println("hello world");
PrintWriter out = resp.getWriter();
out.write("The information is : ");
System.out.println("hello world2");
}

Upload file from android to App Script

Um so basically I'm trying to upload a file from my android phone to app script which will create the file in google drive. This works will when accessing via browser. But when trying to do a multipart/httppost/formdata, it doesn't work. the params AFAIK seems to be correct. Posting Strings work without any issue (tried with volley library), however files/images don't seem to work. Adding Google drive SDK is not an option for me since most of my app users are going to be using custom custom OS, hence google play services not working correctly.
Current code for app script
server.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dir = "Files";
var folder, folders = DriveApp.getFoldersByName(dir);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dir);
}
var blob = form.myFile;
// var file = folder.createFile("BlobTest","test");
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return file.getId() ;
} catch (error) {
return error.toString();
}
}
**Form.html**
<form id="myForm">
<input type="text" name="myName" placeholder="name..">
<input type="file" name="myFile" >
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
**And my android code**
private class uploadimg extends AsyncTask<Void, Integer, Integer> {
int serverResponseCode = 0;
String serverResponseMessage;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
return uploadFilez();
}
public int uploadFilez() {
String sourceFileUri = selectedImagePath;
String upLoadServerUri = url;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("myFile", fileName);
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// String k ="";
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="+"tits"+";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
return serverResponseCode;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
}
any help is appreciated :) thank you

Inject javascript in webview android

my js script is working well in console browser but in android it says
Uncaught TypeError: Cannot read property 'removeChild' of undefined source
below is my snippet code and I added two script to see the difference :
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl(getScript2());
}
});
//this script is working well
private String getScript1(){
return "javascript:(function() { " +
"document.getElementsByTagName('frameset')[0].rows='0,*'; " +
"document.getElementsByTagName('frameset')[1].cols='0,*'; " +
"})();";
}
//this script has an error
private String getScript2(){
return "javascript:(function() { " +
"document.getElementsByTagName('frame')[2].contentDocument.documentElement.getElementsByTagName('tr')[1].removeChild(document.getElementsByTagName('frame')[2].contentDocument.documentElement.getElementsByTagName('tr')[1].getElementsByTagName('td')[0]); " +
"document.getElementsByTagName('frame')[2].contentDocument.documentElement.getElementsByTagName('tr')[1].removeChild(document.getElementsByTagName('frame')[2].contentDocument.documentElement.getElementsByTagName('tr')[1].getElementsByTagName('td')[0]); " +
"document.getElementsByTagName('frame')[2].contentDocument.documentElement.getElementsByTagName('tr')[1].getElementsByTagName('td')[1].rowSpan='0'; " +
"})();";
}
webView.loadUrl("https://www.bancnetonline.com/apps/jsp/bancnet/allIPMainPage.jsp?bnkname=4");
You are getting error because Uncaught TypeError: Cannot read property 'removeChild' of null, so check your script once again for null value.
Create a class which called by javascript if you want so
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
//called by javascript
}
}
Register interface for javascript
webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");
Sample Injection of javascript to page, try like this
webview1.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
StringBuilder sb = new StringBuilder();
sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
sb.append("var objPWD, objAccount;var str = '';");
sb.append("var inputs = document.getElementsByTagName('input');");
sb.append("for (var i = 0; i < inputs.length; i++) {");
sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
sb.append("}");
sb.append("if (objAccount != null) {str += objAccount.value;}");
sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
sb.append("window.MYOBJECT.processHTML(str);");
sb.append("return true;");
sb.append("};");
view.loadUrl("javascript:" + sb.toString());
}
});
Save the file as index.html in assets folder (Src->main->assets)
byte[] buffer = new byte[0];
try {
InputStream is = getActivity().getAssets().open("index.html");
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
String str = new String(buffer);
Then call as
ll_webview.loadDataWithBaseURL("file:///android_asset/", str, "text/html", "utf-8", null);

JSP Servlet does not work after using IF block

This servlet works fine when without the using if block but now I need to use the if block add some more options.
Please can any one tell me why is that?
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
FileReader fr = null;
BufferedReader br = null;
try {
ArrayList<Contact> contactList = new ArrayList<>();
String query = request.getParameter("q");
String path = getServletContext().getRealPath("pb.txt");
File file = new File(path);
fr = new FileReader(file);
br = new BufferedReader(fr);
String byPhone = request.getParameter("byPhone");
String byAddress = request.getParameter("byAddress");
String byEmail = request.getParameter("byEmail");
out.println(byPhone);
String data = null;
if (byPhone.equals("on")) {
out.print("By Phone:"+byPhone);
while ((data = br.readLine()) != null) {
String[] token = data.split(":");
if (token[1].toLowerCase().startsWith(query.toLowerCase())) {
Contact c = new Contact(token[0], token[1], token[2], token[3]);
contactList.add(c);
}
}
}
out.print("Else");
while ((data = br.readLine()) != null) {
String[] token = data.split(":");
if (token[0].toLowerCase().startsWith(query.toLowerCase())) {
Contact c = new Contact(token[0], token[1], token[2], token[3]);
contactList.add(c);
}
}
out.print("<h1>Results</h1>");
out.print("<table>");
out.print("<tr>");
out.print("<td>Name</td>");
out.print("<td>Phone No</td>");
out.print("<td>Email</td>");
out.print("<td>Address</td>");
out.print("</tr>");
for (Contact c : contactList) {
out.print("<tr>");
out.print("<td>" + c.getName() + "</td>");
out.print("<td>" + c.getPhoneNo() + "</td>");
out.print("<td>" + c.getEmail() + "</td>");
out.print("<td>" + c.getAddress() + "</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("Back");
} finally {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
out.close();
}
}
}
you can see the if block right below String data = null;
Thank you!
One obvious way it can fail seems to be when parameter byPhone is not supplied on the request, leaving variable byPhone = null, causing NullPointerException on the if statement.
Two ways to fix that:
// Explicit null check
if (byPhone != null && byPhone.equals("on")) {
// Reverse equals check
if ("on".equals(byPhone)) {

SQLite database not working in Android 4.4

I am using SQLite database for my PhoneGap project.The database is getting populated on every other OS I have tested except Android 4.4.0+ .
The Code for accessing database is below :-
public class MathWhiz extends CordovaActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
super.loadUrl(Config.getStartUrl());
SharedPreferences sp = getSharedPreferences("MYPREFS",
Activity.MODE_PRIVATE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
// If no shared prefs exist, e.g. first install, it doesn't matter - the
// following will return false as a default
Boolean database_copied = sp.getBoolean("database_copied", false);
if (!database_copied) {
try {
String pName = this.getClass().getPackage().getName();
this.copy("Databases.db", "/data/data/" + pName
+ "/app_database/");
this.copy("sample.db", "/data/data/" + pName
+ "/app_database/myFile/");
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("database_copied", true);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
void copy(String file, String folder) throws IOException {
File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists()) {
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder + file);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
}
And this is how I am using the database :-
window.openDatabase("sampleDB", "1.0", "sample", 200000);
Can anybody please point out what updates I need to do in order to make it work on Android 4.4 + ? Thanks
try it.. its working well...
public boolean copyDataBaseFromAssets(Context c) throws IOException {
if(android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/"+ DATABASE_NAME;
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"+DATABASE_NAME;
String pathToDatabaseFileInAssetFolder = DATABASE_NAME;
String pathToDatabaseFileInSystem = DB_PATH;
this.getReadableDatabase();
> getReadableDatabase funcation used in db import code
AssetManager assetManager = c.getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open(pathToDatabaseFileInAssetFolder);
} catch (IOException ex) {
return false;
}
if (inputStream != null) {
OutputStream outputStream = new FileOutputStream(pathToDatabaseFileInSystem);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
Log.d(TAG, "Database is copied");
return true;
}
return false;
}
Change this
this.copy("Databases.db", "/data/data/" + pName + "/databases/");
this.copy("sample.db", "/data/data/" + pName + "/databases/");

Categories