I want to create an Android app. There will be a form which will allow users to choose files using html tag. There will also be a submit button on the form, onclick of which the chosen file should get copied from the Android device to a location on the server.
Right now the form is on an html page and I have been using phonegap for the development.
As of now, I have created a plugin which reads the file from sdcard folder and using a jsch library I am uploading the files on the sftp server.
While researching, I found that many people are using the following method:
The form details are posted to the server and using a php script the file content are read using $_FILES (but I do not want to follow this approach)
I need a way, so that when the user chooses the file using browse option this file name will be picked up when the form is posted.
for e.g below is the code for MainActivity.java file
package com.example.filepicker;
import java.io.IOException;
import java.net.URI;
import org.apache.cordova.DroidGap;
import org.apache.http.client.methods.HttpGet;
import android.util.Log;
import android.view.Display;
import android.webkit.WebSettings.RenderPriority;
import android.view.WindowManager;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
public class MainActivity extends /* Activity */DroidGap {
private Object request;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.addJavascriptInterface(this, "MainActivity");
super.loadUrl("file:///android_asset/www/index.html");
}
public void onFormSubmit() {
//this method is to be invoked when the user clicks form submit button
Log.i("Custom Function Called", "Custom Function Called");
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>XXXX | INDEX</title>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/toast.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.magnific-popup.min.js"></script>
<script type="text/javascript" src="js/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/FileUploadPlugin.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" >
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/media-query.css" />
<link rel="stylesheet" type="text/css" href="css/magnific-popup.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mCustomScrollbar.css" />
<script type="text/javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
alert('device is ready');
var fileupload1 = new FileUploadPlugin();
var ipaddress = "xxxxxxx";
var userId ="xxx";
var password = "xxx";
/*cordova.exec(onFileSystemSuccess, fail, "FileUploadPlugin", "echo",
[ipaddress,userId,password]); */
/*cordova.exec(onFileSystemSuccess, fail, "FileUploadPlugin", "display",
["DEF"]); */
/* callNewActivity();*/
alert('after execution is called');
}
function onFileSystemSuccess(result) {
alert('on success'+result);
// alert('msg'+msg);
// alert('on status'+status);
console.log('this is success');
/* console.log(result); */
/* console.log(fileSystem.name);
console.log(fileSystem.root.name);*/
}
function fail(error) {
alert('on failure'+error);
console.log('this is error');
alert('err code'+evt.target.error.code);
/* console.log(evt.target.error.code);
*/
}
function onFormSubmit() {
window.MainActivity.onFormSubmit();
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Attach File</h1>
</div>
<div data-role="content">
<form id="file-attachment-form" action="http://PutYourServerURL">
<div data-role="fieldcontain">
<label for="data">Put some text:</label>
<input name="data" type="text" id="data"/>
</div>
<div data-role="fieldcontain">
<label for="attachment">Attachment:</label>
<input type="file" name="attachment" id="attachment"/>
</div>
<input type="submit" value="Submit"/>
</form>
</div>
<script>
$('#file-attachment-form').submit(function () {
formData = new FormData($(this)[0]);
alert('new '+formData);
/*console.log(formData);*/
/* $.ajax({
type:'POST',
url:$('#file-attachment-form').attr('action'),
data:formData,
contentType: false,
processData: false,
error:function (jqXHR, textStatus, errorThrown) {
alert('Failed to upload file')
},
success:function () {
alert('File uploaded')
}
})*/
/*alert('formData = '+formData);*/
onFormSubmit();
});
</script>
</div>
</body>
</html>
e.g MainActivity.java file will have a function called "onFormSubmit" this function should be able to read the files parameter.
I would like to know if this is a possible method. If not then any pointer/suggestions will be helpful.
Thanks in Advance.
Related
What I want:
If someone visits the page, could select two dates and click a (single) button for downloading the data between the two dates selected.
What I already have working:
JSP/web development is new for me. This is my scenario, using datepicker and JSP have a page that make a query to the database, return certain data between two dates, and create a .txt file with this data which saves locally.
Once the file is created, another button can be pressed to download the file.
What I need to work:
I need only one button who made both actions, so once the file is saved locally, a prompt for download appear and the visitor could make the download.
Because of how common the words are, it's hard to find what I need on search engines.
I need a button. I don't want links or anchors that looks like a button, this could be an easy matter for some folks, but I already have lost two days in
Info:
Apache Tomcat: 8.0.27 && Netbeans 8.1 && Ubuntu 14.04
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
Recuperación de Datos
</div>
</div>
<div id="LecturasTableContainer" style="position: relative; text-align: center; font-size: 17px; top: 10px;">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1"> <span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<!-- Button who generate the file -->
<button type="submit" id="LoadRecordsButton" onclick="return confirm('Datos Recuperados');">Generar</button>
</div>
<br>
<!-- Button who download the file -->
<s:form action="download" method="POST">
<s:submit value="Descargar" type="button"/>
</s:form>
</div>
</center>
</body>
</html>
Action class for "Generar" Button:
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DataRecovery extends ActionSupport implements ServletRequestAware {
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close ();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
Action Class for "Descargar" Button:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DownloadAction extends ActionSupport{
private InputStream fileInputStream;
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String execute() throws Exception {
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
}
Struts.xml:
<action name="GetDataRecovery" class="com.raspberry.struts.action.DataRecovery"
method="doDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="download" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
If you have followed the example, you should see that he was using two actions. One action is mapped to the JSP page, and another is used to download. First one is used to return an actionless result (class attribute is missing). It's needed to access JSP page through the action. If you follow this technique - first action, second JSP, then you can use Struts2.
You can also share the same JSP among different actions that return this JSP as a result. If you want to share the same JSP for two or more actions you should add a result that contains the name/path to the file.
You can use action class properties (not for actionless results) to hold the state of the action scope objects accessible in JSP via OGNL/JSTL or JSP EL.
Elements of type "submit" you should use inside the form, otherwise use type "button" and use javascript to submit the form (it doesn't concern s:submit tag though).
in the DataRecovery action class you should create a property for download link or some boolean to indicate that download is ready. Just keep the name of the action "download". If the property has a value then display the button for download.
<s:if test="downloadReady">
<s:form action="download" method="POST">
<s:submit type="button" cssClass="btn btn-primary" value="Descargar" />
</s:form>
</s:if>
private boolean isDownloadReady = false;
//getters and setters
and set this variable after saving a file.
First of all, thanks to #user3659052 #BalusC #Tiny and #Roman C , for your comments. All were very helpfull.
I was very confused, so after the comments enlightenment, decide to first start with some tutorials and yesterday get the web app working.
After fixing the struts action for the "Download Button", I tried to generate the file also in the Descargar Action Class, but the query to database was null.
The mistake was the form ID on the datepicker was pointing Generar Action Class, so the Descargar Action Class never get the data. So after change the pointer to the "correct" action, was able to get the dates, create the file (locally) and downloading in one action. (So Generar Action Class was deleted)
Struts .xml (fragment)
<action name="DataRecovery" class="com.raspberry.struts.action.DownloadAction" method="goDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="GetRecovery" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Descargar Action Class
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
public class DownloadAction extends ActionSupport implements ServletRequestAware {
public InputStream fileInputStream;
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
public String execute() throws Exception {
doDataRecovery();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
Recuperación de Datos
</div>
</div>
<div style="position: relative; text-align: center; font-size: 17px; top: 10px;">
<s:form theme="simple" action="GetRecovery" method="POST" id="LecturasTableContainer">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1">
<span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<s:submit value="Descargar" id="LoadRecordsButton" type="button"/>
</s:form>
</div>
</div>
</center>
</body>
</html>
Once again thanks for the help.
I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.
I am new in cordova 3.4. I want to write send sms app. I get SMSPlugin from github but i want to write this myself. I write a html file like this and copy in root/www and i write a java script file in root/www/js. but when i run the app, i don't see button in the page! Why? What is problem? How can i write this app?
And i change name of java file(Activity) from AndroidManifest manually to my class, this is not a problem, Yes? and i changed 'id' in widget tag from config.xml to my package manually.
index.html:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script type="text/javascript">
var txtMSG = "";
function onDeviceReady(){
document.getElementById("deviceName").innerHTML= device.model;
document.getElementById("version").innerHTML= device.cordova;
document.getElementById("mobilePlatform").innerHTML= device.platform;
document.getElementById("platformVersion").innerHTML= device.version;
document.getElementById("uuid").innerHTML= device.uuid;
document.getElementById("sendSMS").style.display="block";
}
function displayTextMessage(msg){
alert(msg);
$('#text-messages').prepend('<div>' + msg + '</div>');
}
function sendConsole(){
var message = "This_is_a_test"
DeviceInfo.SendConsole({text: message}, function(){
alert("success");
}, function(){
alert("fail");
});
}
function SendSMS(){
console.log("-------------------Start----------------------");
DeviceInfo.SendSMS({phoneNumber:[document.getElementById('cellNumber').value], text: document.getElementById('textMessage').value}, function(){
alert("success");
}, function(){
alert("fail");
});
console.log("---------------------End--------------------");
}
/** Called when browser load this page*/
function init(){
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</head>
<body>
<input id="sendSMS" style="display:none" type="button" ontouchend="SendSMS()" onclick="SendSMS()" value="Send SMS To:" />
<!-- <button onClick="SendSMS();">Send SMS</button> <br> -->
<input id="cellNumber" type="text" style="width:100%" value="9126012134" onclick="this.select()" ontouchend="this.select()" />
<textarea id="textMessage" style="width:100%; height:100px">Plugin Example</textarea>
<input id="sendConsole" style="display:none" type="button" ontouchend="sendConsole()" onclick="sendConsole()" value="Send Console Log" />
<div id="text-messages" style="border:solid 1px #efefef; padding 10px"></div>
</body>
</html>
DeviceInfo.js:
var DeviceInfo = function () { };
DeviceInfo.callMethod = function (methodName, content, success, fail) {
return PhoneGap.exec(function (args) {
success(args);
}, function (args) {
fail(args);
}, 'DeviceInfo', methodName, [content]);
}
DeviceInfo.GetPhoneNumber = function (content, success, fail) {
return DeviceInfo.callMethod('getPhoneNumber', content, success, fail);
};
DeviceInfo.SendSMS = function (content, success, fail) {
return DeviceInfo.callMethod('SendSMS', content, success, fail);
};
DeviceInfo.SendConsole = function (content, success, fail) {
return DeviceInfo.callMethod('SendConsole', content, success, fail);
};
Thanks for advises
There is a plugin on ghithub developed by javatechig here but only work with old cordova/phonegap version. This fork https://github.com/aharris88/phonegap-sms-plugin works with recent version of cordova and is updated frequently. Read the "readme.md" for example and more informations.
This Android Phonegap plugin allows you to easily send SMS in android using both native SMS Manager or by invoking the default android SMS app
I'm trying out AJAX for the first time. I'm using a Jersey Web Service as what gets called. But my call always executes the error part. Help! please
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jquery Basic</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#submit1").click(function() {
alert("click");
var username = $("#textbox").val;
$("#para1").text(username);
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: username,
success: function(){alert("Login Success!")},
error: function(){alert("Login Failure!")}
});
alert("ajax passed");
});
});
</script>
</head>
<body>
<a id="body1">JQuery Test Page</a><br>
<div id="heading"><a>Enter Your Details</a></div>
<div>
<div id="heading1"><a>UserName:</a></div>
<div><input id="textbox" type="text"/></div>
<button id="submit1">Submit</button>
</div>
<div><p id="para1"></p></div>
</body>
</html>
WebService is as follows
package Resource;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import POJO.passwordPojo;
import POJO.usernamePojo;
public class resource {
#POST
#Path("welcome")
public String welcomeFunction(#FormParam("username") String username)
{
setUserNameData(username);
return "success";
}
usernamePojo userName = new usernamePojo();
passwordPojo password = new passwordPojo();
public void setUserNameData(String userNameData)
{
userName.setUserName(userNameData.toString());
printuserName();
}
public void setpasswordData(String passwordData)
{
password.setPassword(passwordData.toString());
printPassword();
}
public void printuserName()
{
System.out.println("UserName:"+userName.getUserName());
}
public void printPassword()
{
System.out.println("Password"+password.getPassword());
}
}
Blast!! I know most of my question is code!! Bloody post it already!
Think data needs to be an array.
var usernameVal = $("#textbox").val;
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: { username : usernameVal }
send data as json with index like {"username":username } in ajax data like
....,data: {"username":username },....
I have a html jsp form where users can copy their text press submit and pdf is created using Itext . On the other side the servlet gets the data . What happens is when I use some non standard letters it gives me back #^& for these letters . I did use in my servler and both jsp charset=UTF-8 , I am using post method to send data . I am using netbeans and tomcat .
It is not about Itext since when I do System.out.println(variable) it also does not print correctly .
package servlets;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfAppearance;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author Jovo
*/
#WebServlet(name = "GenerateBrokersPdf", urlPatterns = {"/GenerateBrokersPdf"})
public class GenerateBrokersPdf extends HttpServlet {
/*
public static final String FONT = "C:/Windows/Fonts/segoeui.ttf";
bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
document.add(new Paragraph(title,new Font(bf, 12)));
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, DocumentException {
response.setContentType("application/pdf;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UFT-8");
BaseFont bf;
try {
HttpSession session = request.getSession(true);
if (session.getAttribute("taxnumber") == null || session.getAttribute("email") == null || session.getAttribute("password") == null) {
request.setAttribute("message", "The user does not exist in our database");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
}
String title = request.getParameter("doctitle");
String date = request.getParameter("docdate");
String text = request.getParameter("brokerstext");
//String text = URLDecoder.decode(new String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8");
// System.out.println(text);
String[] newdate = date.split("/");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph(newdate[1] + "/" + newdate[0] + "/" + newdate[2]));
document.add(new Paragraph(title));
document.add(new Paragraph(text));
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(new LineSeparator());
document.add(Chunk.NEWLINE);
document.add(new LineSeparator());
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(new Paragraph(" Brokers's digital signature Clients's digital signature"));
//potpis 1
PdfFormField field1 = PdfFormField.createSignature(writer);
field1.setWidget(new Rectangle(72, 100, 172, 200), PdfAnnotation.HIGHLIGHT_INVERT);
field1.setFieldName("mySig1");
field1.setTitle("Klijent1");
field1.setFlags(PdfAnnotation.FLAGS_PRINT);
field1.setPage();
PdfAppearance tp1 = PdfAppearance.createAppearance(writer, 72, 48);
tp1.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
tp1.stroke();
field1.setAppearance(
PdfAnnotation.APPEARANCE_NORMAL, tp1);
writer.addAnnotation(field1);
//potpis
//potpis 2
PdfFormField field2 = PdfFormField.createSignature(writer);
field2.setWidget(new Rectangle(372, 100, 472, 200), PdfAnnotation.HIGHLIGHT_INVERT);
field2.setFieldName("mySig2");
field2.setTitle("Klijent2");
field2.setFlags(PdfAnnotation.FLAGS_PRINT);
field2.setPage();
PdfAppearance tp2 = PdfAppearance.createAppearance(writer, 72, 48);
tp2.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
tp2.stroke();
field2.setAppearance(
PdfAnnotation.APPEARANCE_NORMAL, tp2);
writer.addAnnotation(field2);
//potpis
document.close();
/* TODO output your page here. You may use following sample code. */
} finally {
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
try {
processRequest(request, response);
} catch (DocumentException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
try {
processRequest(request, response);
} catch (DocumentException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is the jsp start code
<%#page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<% request.setCharacterEncoding("UTF-8");%>
<%
if(session.getAttribute("taxnumber")==null || session.getAttribute("email")==null || session.getAttribute("password")==null )
{
request.setAttribute("message", "The user does not exist in our database");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
}
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta content="width=device-width" name="viewport"> ...
This is the html with form(created by jsp) source code
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta content="width=device-width" name="viewport">
<link type="text/css" href="NodeGraph/css/base.css" rel="stylesheet" />
<link type="text/css" href="NodeGraph/css/Spacetree.css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="jit.js"></script>
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
<link href="content/css/bootstrap.css" type="text/css" rel="stylesheet">
<link href="content/css/bootstrap-responsive.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-tiles.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-charms.css" type="text/css" rel="stylesheet">
<link href="content/css/metro-ui-light.css" type="text/css" rel="stylesheet">
<link href="content/css/icomoon.css" type="text/css" rel="stylesheet">
<link href="content/css/datepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/daterangepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/demo.css" type="text/css" rel="stylesheet">
<link href="scripts/google-code-prettify/prettify.css" type="text/css" rel="stylesheet">
<link href="content/ico/favicon.ico" rel="shortcut icon">
<link href="content/ico/apple-touch-icon-144-precomposed.png" sizes="144x144" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-114-precomposed.png" sizes="114x114" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-72-precomposed.png" sizes="72x72" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-57-precomposed.png" rel="apple-touch-icon-precomposed">
<script>
function showchat()
{
if (document.getElementById("charms").style.display=="block")
{
document.getElementById("charms").style.display="none";
}
else
{
document.getElementById("charms").style.display="block";
}
}
</script>
</head>
<body >
<div class="container-fluid">
<div class="row-fluid">
<div class="span2" >
<a id="backbutton" class="win-backbutton" href="#" onclick="history.go(-1)"></a>
<a style="margin-top: 45px;position: absolute;width: 170px;" class="thumbnail" href="DebtSolutions.jsp">
<img alt="" src="DeptSolutionIc.jpg">
<label>Debt Solutions</label>
</a>
<a style="margin-top: 215px;position: absolute;width: 170px;" class="thumbnail" href="Synergy.jsp">
<img alt="" src="SynergyIc.jpg">
<label>Company Synergy</label>
</a>
<a style="margin-top: 385px;position: absolute;width: 170px;" class="thumbnail" href="PublicBid.jsp">
<img alt="" src="PublicInc.jpg">
<label>Public Procurements</label>
</a>
<a style="margin-top: 555px;position: absolute;width: 170px;" class="thumbnail" href="CompanySearch.jsp">
<img alt="" src="SearchIc.jpg">
<label>Company Search</label>
</a>
<a style="margin-top: 725px;position: absolute; width: 170px;"class="thumbnail" href="CompanyNetworking.jsp">
<img alt="" src="NetworkingIc.jpg">
<label>Company Networking</label>
</a>
<a style="margin-top: 895px;position: absolute; width: 170px;padding-bottom: 30px;"class="thumbnail" href="Brokers.jsp">
<img alt="" src="brokers.jpg">
<label>Brokers Accounts</label>
</a>
</div>
<div class="span10" style="text-align:justify;margin-right:200px;margin-left:200px;">
<hr class="win-command">
<button class="win-command" onclick="parent.location='Start.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Start</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Statistics.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Statistics</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="showchat();">
<span class="win-commandimage win-commandring">]</span>
<span class="win-label">Chat</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Setup.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Setup</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Home.jsp'">
<span class="win-commandimage win-commandring"></span>
<span class="win-label">Logout</span>
</button>
<hr class="win-command">
<div id="top-info" class="pull-right">
<a class="pull-left" href="#">
<div class="top-info-block">
<h3>Coca Cola Hellenic Company Serbia doo
</h3>
</div>
<div class="top-info-block">
<b class="icon-user"></b>
</div>
</a>
</div>
<span class="label label-success" style="display: block;background-color: #AA40FF;"> <h1>BROKERS ACCOUNTS</h1></span>
<p> <h2>Create a purchase documents for your clients </h2></p>
<p><h4>Your clients need not come to your office to sign a document for a purchase of stocks to be made. You can generate these documents online and send them to your clients for signing via smart card .
Generate a pdf document and send it to your clients by email for signing .
</h4></p>
<form onsubmit="return sendformdata();" style="margin: 30px;" target="_blank" action="GenerateBrokersPdf" method="post">
<label>Document title</label>
<input type="text" name="doctitle" id="doctitles" class="input-xxlarge" placeholder="Enter the document title"/>
<label>Document creation date</label>
<input type="text" id="datepicker" name="docdate" class="input-xxlarge" placeholder="Click to enter document creation date"/>
<label>Set the document text</label>
<textarea name="brokerstext" id="brokerstext" maxlength="999999" placeholder="The document text content" rows="20" cols="50" class="input-xxlarge" ></textarea>
<p><button type="submit" class="btn" style="margin-left: 25px;" >GENERATE A PDF DOCUMENT </button></p>
</form>
<script type="text/javascript">
function sendformdata()
{
if (document.getElementById("doctitles").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document title</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
if (document.getElementById("datepicker").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document date</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
if (document.getElementById("brokerstext").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document content text</h2><p>" ;
$('#myModal2').modal("toggle");
return false;
}
}
</script>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
window.jQuery || document.write("<script src='scripts/jquery-1.8.2.min.js'>\x3C/script>")
</script>
<script src="scripts/google-code-prettify/prettify.js" type="text/javascript"></script>
<script src="scripts/jquery.mousewheel.js" type="text/javascript"></script>
<script src="scripts/jquery.scrollTo.js" type="text/javascript"></script>
<script src="scripts/jquery.blockUI.js" type="text/javascript"></script>
<script src="scripts/jquery.form.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script src="scripts/modernizr-2.6.1.min.js" type="text/javascript"></script>
<script src="scripts/mustache.js" type="text/javascript"></script>
<script src="scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="scripts/bootstrap.js" type="text/javascript"></script>
<script src="scripts/bootmetro.js" type="text/javascript"></script>
<script src="scripts/bootmetro-charms.js" type="text/javascript"></script>
<script src="scripts/demo.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>
<script src="scripts/bootstrap-datepicker.js" type="text/javascript"></script>
<script src="scripts/daterangepicker.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>
<script type="text/javascript">
$(".metro").metro();
</script>
<div id="charms" class="win-ui-dark in" style="display: none;">
<div id="theme-charms-section" class="charms-section">
<div class="charms-header">
<a class="close-charms win-command" href="#" onclick="showchat();">
<span class="win-commandimage win-commandring"></span>
</a>
<h2>Chat</h2>
</div>
<div class="row-fluid">
<div class="span12">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<div id="myModal2" class="modal message hide fade in" aria-hidden="false" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" style="display: none;">
<div class="modal-header">
<button class="close" aria-hidden="true" data-dismiss="modal" type="button"></button>
<h3>Message</h3>
</div>
<div class="modal-body" id="mymessagesbody">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
</div>
</div>
<footer ><p style="margin-left:25px;"> © 2013 compensatemeonline.com </p></footer>
</body>
</html>
1) You need to set the data content type to utf-8 before submitting the data. Because receiver(in this case, servlet) needs to know what encoding was set(in JSP) for the data before servlet actually decodes the bytes.
ie: request.setCharacterEncoding("UTF-8");
2) <%#page pageEncoding="UTF-8"%> is not used for the java data. This line is used to tell what language the JSP file was written in. ie: English, Chinese. I think you totally misunderstood this line.
Answer Updated:
3) Remove this line >> String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8"); You don't need to convert received UTF-8 bytes to iso.
Note: Please post your JSP code
The problem is that when parsing the form fields tomcat doesn't know the charset used.
This is normally resolved using a filter that changes charset in request.
Create the following class:
public class EncodingSetterFilter implements Filter
{
/** Creates a new instance of EncodingSetterFilter */
public EncodingSetterFilter()
{
}
public void init(FilterConfig filterConfig) throws ServletException
{
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy()
{
}
}
And then configure its usage in web.xml (be sure to specify correct filter class):
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>
com.yourpackage.EncodingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>