I have implemented Phonegap Plugins for v1.0.0.
Please have a look at my HTML code
/**** HTML FILE ****/
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum- scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="system.js"></script>
<script type="text/javascript">
var uname = "User1"; //------------- 2
var System = function() {};
System.prototype.func = function(funcname,funcdata) {
//alert("In the list function");
return PhoneGap.exec(
null, //Success callback from the plugin
null, //Error callback from the plugin
'SystemPlugin', //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
funcname, //Tell plugin, which action we want to perform
funcdata); //Passing list of args to the plugin
};
PhoneGap.addConstructor(
function() {
PhoneGap.addPlugin("system", new System());
}
);
var _anomFunkMap = {};
var _anomFunkMapNextId = 0;
function anomToNameFunk(fun)
{
var funkId = "f" + _anomFunkMapNextId++;
var funk = function()
{
fun.apply(this,arguments);
_anomFunkMap[funkId] = null;
delete _anomFunkMap[funkId];
}
_anomFunkMap[funkId] = funk;
return "_anomFunkMap." + funkId;
}
function GetFunctionName(fn)
{
if (typeof fn === "function") {
var name= fn.name;
if (!name) {
var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
name= m && m[1];
}
if (name && (window[name] === fn)) {
return name;
} else {
return anomToNameFunk(fn);
}
}else {
return null;
}
}
function post_sync_data(url, urlparam, param, requestheader, callback){
//alert("In post_sync_data");
if(undefined == callback){
if(undefined == requestheader){
var fnname = GetFunctionName(param);
var dataArray = [fnname, fnname, url, urlparam];
}
else{
var fnname = GetFunctionName(requestheader);
//Note : the param is optional parameter or request header
var dataArray = [fnname, fnname, url, urlparam, param];
}
}
else{
var fnname = GetFunctionName(callback);
var dataArray = [fnname, fnname, url, urlparam, param, requestheader];
}
//alert("Calling plugin function post with \r\n"+dataArray);
var r = window.plugins.system.func("post",dataArray);
//alert("r is :\r\n"+r); ------------- 3
return r;
}
function validate(){
//Make a webservice call for the Omnesys Token
post_sync_data(url,urlparam,uname,postDataCB);
}
function postDataCB(token,name){
//Here uname is undefined.
alert("In postDataCB()\r\nuname: "+uname+"\r\nuname from C Func: "+name+"\r\n\r\ntoken: "+token);
return;
}
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
function onDeviceReady()
{
// do your thing!
navigator.notification.alert("PhoneGap is working")
document.getElementById('d1').style.visibility = "visible";
}
</script>
</head>
<body onload="onBodyLoad()">
<div id="d1" style="visibility:hidden">
<form> <!-- 1 -->
<button onclick="javascript:validate()">Submit</button><br />
</form>
</div>
</body>
</html>
My Phonegap Plugin File.
/*** My PhoneGap Plugin.xml File ***/
<?xml version="1.0" encoding="utf-8"?>
<plugins>
<plugin name="App" value="com.phonegap.App"/>
<plugin name="Geolocation" value="com.phonegap.GeoBroker"/>
<plugin name="Device" value="com.phonegap.Device"/>
<plugin name="Accelerometer" value="com.phonegap.AccelListener"/>
<plugin name="Compass" value="com.phonegap.CompassListener"/>
<plugin name="Media" value="com.phonegap.AudioHandler"/>
<plugin name="Camera" value="com.phonegap.CameraLauncher"/>
<plugin name="Contacts" value="com.phonegap.ContactManager"/>
<plugin name="Crypto" value="com.phonegap.CryptoHandler"/>
<plugin name="File" value="com.phonegap.FileUtils"/>
<plugin name="Network Status" value="com.phonegap.NetworkManager"/>
<plugin name="Notification" value="com.phonegap.Notification"/>
<plugin name="Storage" value="com.phonegap.Storage"/>
<plugin name="Temperature" value="com.phonegap.TempListener"/>
<plugin name="FileTransfer" value="com.phonegap.FileTransfer"/>
<plugin name="Capture" value="com.phonegap.Capture"/>
<plugin name="SystemPlugin" value="com.phonegap.test.SystemPlugin" />
</plugin>
And my JAVA Class
/** Plugin Code **/
public class SystemPlugin extends Plugin {
#Override
public PluginResult execute(String funcname, JSONArray funcargs, String jscallbackid){
//Get the success and failure call back functions
try{
SuccessCallBack = funcargs.getString(0);
FailureCallBack = funcargs.getString(1);
}
catch (JSONException jsonEx) {
return null;
}
if(funcname.equals("post")){
try{
url = funcargs.getString(2);
urlparam = funcargs.getString(3);
}
catch (JSONException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
try {
conn = new URL(url).openConnection();
conn.setDoOutput(true);
} catch (MalformedURLException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
if(requestheader == null){
//Default Request Property
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
else{
String Headers[] = requestheader.split("\r\n");
for(i=0; i < Headers.length; i++){
String hReq[] = Headers[i].split(":");
if(hReq.length == 2){
conn.setRequestProperty(hReq[0], hReq[1]);
}
}
}
try {
//Blank String
String data="";
String param[] = urlparam.split("&");
for(i=0; i < param.length; i++){
String keyval[] = param[i].split("=");
if(keyval.length == 2){
data += URLEncoder.encode(keyval[0], "UTF-8") + "=" + URLEncoder.encode(keyval[1], "UTF-8") + "&";
}
}
//remove the unwanted & at the end of the string
data = data.substring(0,data.length()-1);
ro = new OutputStreamWriter(conn.getOutputStream());
ro.write(data);
//Close the connection
ro.close();
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
try{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
//Close the connection
rd.close();
} catch (IOException e) {
SendJS = "javascript:" + FailureCallBack + "('" + e.getMessage() + "')";
sendJavascript(SendJS);
return null;
}
SendJS = "javascript:" + SuccessCallBack + "('" + JSONObject.quote(sb.toString());
if(jObj != null)
SendJS += "','" + jObj + "')";
else if(StringParam != null)
SendJS += "','" + StringParam + "')";
else
SendJS += "')";
sendJavascript(SendJS);
return null;
}
else{
return null;
}
}
}
Now in the first code you can see numerals 1 2 3
1 - the form element
2 - is a global variable
3 - is the plugin alert
Now if i remove 1. everything works fine. But if i keep the form, the global variable cannot hold its value. It becomes undefined and the alert also gives undefined
Can someone guide me what the issue is ?
This is a Form issue. The form was not as per the standard form format
Rectifying this fixed the issue.
Related
This question already has answers here:
Struts2 passing variables case
(3 answers)
Closed 1 year ago.
i recently try to learn java and struts.
i want to pass the selected value from my dropdown but all i receive in my action is null
here's my code
dropdown in my jsp
<s:select list="UrgencyList" listKey="name" listValue="name"
key="urgency" name="urgency" emptyOption="false" headerKey="12" required="true"
headerValue="--------------------------------------------------------" />
<font class="ui-widget-R"><s:property value="errors['urgency'][0]" /></font>
my xml, SavSharing is the post action used ob my button
<action name="SavSharing" class="com.ao.qshare.form.Sharing" method="Save">
<exception-mapping exception="org.apache.commons.fileupload.FileSizeLimitExceededException"
result="error" />
<result name="success">/qs/sharing.jsp</result>
<result name="input">/qs/sharing.jsp</result>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="mydefault" />
</action>
public class Sharing extends ActionSupport {
public String Save() throws Exception {
String result = "";
SharingSqlManger sql = null;
SiteDeploySqlManger sSql=null;
try {
Log.info(getClass(), "-----Save start-----");
con = DbConnection.getDbConnection();// get account
con.setAutoCommit(false);
sql=new SharingSqlManger(con);
sSql= new SiteDeploySqlManger(con);
ActionContext actionContext = ActionContext.getContext();
Map<?,?> data=actionContext.getParameters();
String tp=SharingUtil.getString(data.get("tp"));
attachs=SharingUtil.getFile(this.sno,SharingConstants.sharing);
boolean isSameFile=SharingUtil.isSameFile(SharingUtil.getFileString(attachs),this.getUploadFileName());
// boolean isSameFile=SharingUtil.isSameFile(this.attach,this.getUploadFileName());
//save
this.setPara();
String oldStatus=entity.getStatus();
if (isSameFile){
this.addActionMessage(SharingConstants.messFileExists);
mess.add(SharingConstants.messFileExists);
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}else{
//upload!=null,do upload
if (!GenericValidator.isBlankOrNull(this.getUploadFileName())) {
this.setAttach(this.attach+this.getUploadFileName()+";");
entity.setAttach(this.attach);
}
if (tp.equals("File")){
if (this.lengthValidate() && this.isSaveValidate(sql)){
if (status.equals(SharingConstants.deployStatusKey)) {
SharingEntity shEntity = sql.getSharing(sno, "</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
}
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
init(sql);
con.commit();
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.status.equals(SharingConstants.newStatusKey)){
this.setStatus(SharingConstants.drafStatusKey);
if (this.lengthValidate() && this.isSaveValidate(sql)){
entity.setStatus(SharingConstants.drafStatusKey);
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
Log.info(getClass(), sno + " status:"+this.getStatusName());
Log.info(getClass(), sno + " save finished");
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (status.equals(SharingConstants.deployStatusKey)){//deploy
if (this.lengthValidate() && isValidate(SharingConstants.Deployed,sql)) {
SharingEntity shEntity=sql.getSharing(sno,"</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.lengthValidate() && isSaveValidate(sql)) {
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}
}
}
}
if (!tp.equals("Exit")){
isValidate=false;
}
} catch (SizeLimitExceededException e) {
Log.info(this.getClass(), "SizeLimitExceededException:" + e.getMessage());
mess.add("SizeLimitExceededException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (IOException e) {
Log.info(this.getClass(), "IOException:" + e.getMessage());
mess.add("IOException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (FileUploadException e) {
Log.info(this.getClass(), "FileUploadException:" + e.getMessage());
// this.addActionError("Exception:"+e.getMessage());
mess.add("FileUploadException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (Exception e) {
Log.info(this.getClass(), "Save exception:" + e.getMessage());
mess.add("Exception:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
// this.addActionError("Exception:"+e.getMessage());
if (con!=null) con.close();
}finally{
// this.setEntityDesc(sql,sSql);
// this.setEntity(entity);
//
// init(sql);
// isValidate=false;
if (con!=null) con.close();
}
return result;
}
private String urgency="";
public String geturgency() {
return urgency;
}
public void seturgency(String urgency) {
this.urgency = urgency;
}
}
I think i supposed to get the value from the jsp going to my action but not doing what im expecting.
Note: there's other textfield and dropdown i remove on the code above all of that is working except to the urgency dropdown that i added.
Also no exception or error found on the console on debugging mode
Your urgency setter names are incorrect; they should follow the JavaBean naming convention and be setUrgency/getUrgency.
Unrelated:
The action method should be named save to follow Java naming convention.
All parameters should be retrieved via setters (or ModelDriven), there is no need to access the action context here.
Most of your exception handling could be handled with a single multi-catch.
This action does far, far too much in a single method: refactor.
In general, setters should just set. If a setter is doing much more than setting it should have a more-obvious name.
There's more, but that's enough for now :)
Hi I am struggling in storing files at server I am new to spring MVC. Can anyone point me if I am doing it right or wrong.
What I have to do is take some files (text or binary) and store those in the storage device using Restservice.
public #ResponseBody String storeFiles(#RequestBody List<File> filenames, #PathVariable String dirname)
throws Exception {
// TODO Auto-generated method stub
Gson gson = new Gson();
String jsonList = gson.toJson(storeFiles.storeFilesToHitachi(filenames, dirname));
return jsonList;
}public Map<String, Integer> storeFilesToHitachi(List<File> filenames,String dirname) throws Exception{
Map<String, Integer> resultStored = new HashMap<String, Integer>();
if(checkDirAvailable(dirname) || createDirectoryAtHitachi(dirname)){
resultStored = storeFilenamesAtHitachi(filenames, dirname);
}
return resultStored;
}
public boolean createDirectoryAtHitachi(String dirname){
boolean isDirCreated = false;
try{
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCreateDir(dirname);
httpPutRequest.setURI(hitachiURI);
HttpResponse httpCreateDirResp = httpClient.execute(httpPutRequest);
int responseCode = httpCreateDirResp.getStatusLine().getStatusCode();
if(responseCode == 201) {
isDirCreated = true;
logger.info("A directory by the name "+ dirname +" has been created" );
}
logger.info(responseCode);
}
catch(Exception e){
logger.error("Unable to create directory:" + dirname + e.getMessage());
}
return isDirCreated;
}
public boolean checkDirAvailable(String dirname){
boolean dirAvailable = false;
try{
httpGetRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCheckDir(dirname);
httpGetRequest.setURI(hitachiURI);
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
int respCode = httpResponse.getStatusLine().getStatusCode();
if (respCode == 200){
dirAvailable = true;
logger.info("A directory named "+dirname +" is avaliable");
}
logger.info(respCode);
}
catch(Exception e){
logger.error("An exception occured while checking for "+dirname + e.getMessage());
}
return dirAvailable;
}
public Map<String, Integer> storeFilenamesAtHitachi(List<File> filenames,String dirname){
Map<String,Integer> resultMap = new HashMap<String, Integer>();
try{
File filename=null;
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
Iterator<File> iter = filenames.iterator();
while(iter.hasNext()){
filename = iter.next();
hitachiURI = constructURLForStorFilesAtHitachi(dirname, filename);
httpPutRequest.setURI(hitachiURI);
receivedFile = new FileInputStream(filename);
httpPutRequest.setEntity(new InputStreamEntity(receivedFile, -1));
HttpResponse httpPutResponse = httpClient.execute(httpPutRequest);
int respCode = httpPutResponse.getStatusLine().getStatusCode();
resultMap.put(filename.getName(), respCode);
logger.info(resultMap);
logger.info("Response code is :"+respCode +" while saving " +filename +" in directory " +dirname);
}
}
catch(Exception e){
logger.error("Got the following exception while storing files:" +e.getMessage());
}
return resultMap;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Error 415--Unsupported Media Type</TITLE>
</HEAD>
<BODY bgcolor="white">
<FONT FACE=Helvetica><BR CLEAR=all>
<TABLE border=0 cellspacing=5><TR><TD><BR CLEAR=all>
<FONT FACE="Helvetica" COLOR="black" SIZE="3"><H2>Error 415--Unsupported Media Type</H2>
</FONT></TD></TR>
</TABLE>
<TABLE border=0 width=100% cellpadding=10><TR><TD VALIGN=top WIDTH=100% BGCOLOR=white><FONT FACE="Courier New"><FONT FACE="Helvetica" SIZE="3"><H3>From RFC 2068 <i>Hypertext Transfer Protocol -- HTTP/1.1</i>:</H3>
</FONT><FONT FACE="Helvetica" SIZE="3"><H4>10.4.16 415 Unsupported Media Type</H4>
</FONT><P><FONT FACE="Courier New">The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.</FONT></P>
</FONT></TD></TR>
</TABLE>
</BODY>
</HTML>
My goal is to take list of files and store in particular directory at server.
I don't get any error in Netbeans, but it doesn't execute nothing except the "Hola?" that i put for test,
I think the main error is in the Printwriter command, it doesn't generate anything in my display,
<%#page import="java.io.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Página Nacho</title>
</head>
<%#page import="ejemplo.BaseDatos" %>
<% out.println("Hola?");
out.println("<body>");
BaseDatos b = new BaseDatos();
PrintWriter salida = response.getWriter();
if (request.getParameter("Agregar") != null) {
boolean inserto = b.inserta (
request.getParameter("nombre"),
request.getParameter("apellido_p"),
request.getParameter("apellido_m"),
request.getParameter("direccion"),
request.getParameter("telefono"),
request.getParameter("email")
);
if (inserto) {
salida.println("<br>Usuario agregado");
} else {
salida.println("<br>No fue posible agregar el usuario");
}
} else {
//Agrega la funcionalidad de consultar todos los usuarios
}
out.println("</body>");
%>
</html>
This is the java file for this code, it's named on spanish, but I think nothing is too difficult:
public class BaseDatos {
Connection conexion = null;
public BaseDatos() {
conexion = null;
}
private boolean conecta() {
try {
String urlBD = "jdbc:mysql://localhost/practica2?user=root&password=";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conexion = DriverManager.getConnection(urlBD);
} catch (Exception e) {
System.out.println(e);
return false;
}
return true;
}
public boolean inserta(
String nom, String ap_p,
String ap_m, String dir, String tel,
String email) {
try {
if (conecta()) {
String q = "insert into personas " +
"(nombre,apellido_p,apellido_m,direccion,telefono,email) " +
"values(?,?,?,?,?,?)";
PreparedStatement i = conexion.prepareStatement(q);
i.setString(1, nom);
i.setString(2, ap_p);
i.setString(3, ap_m);
i.setString(4, dir);
i.setString(5, tel);
i.setString(6, email);
i.executeUpdate();
i.close();
conexion.close();
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(e);
return false;
}
}
public String tablaUsuarios() {
try {
if (conecta()) {
String q = "select * from personas";
PreparedStatement p = conexion.prepareStatement(q);
ResultSet r = p.executeQuery();
String tabla = "<table border=\"3\" align=\"center\">";
tabla += "<tr bgcolor=blue><th align=center>" +
"<font color=white>Nombre</font></th>";
tabla += "<th align=center><font color=white>Apellido</font></th></tr>";
while (r.next()) {
tabla += "<tr><td>" + r.getString("nombre") +
"</td><td>" + r.getString("apellido_p") +
" </td></tr>";
}
r.close();
p.close();
conexion.close();
return tabla;
} else {
return "";
}
} catch (Exception e) {
System.out.println(e);
return "";
}
}
}
There is a whole bunch of URL parameters that the JSP is expecting, the least is the parameter called "Agregar". You need to pass these parameters to the page for it to do further processing.
if (request.getParameter("Agregar")!= null){
boolean inserto = b.inserta (
request.getParameter("nombre"),
request.getParameter("apellido_p"),
request.getParameter("apellido_m"),
request.getParameter("direccion"),
request.getParameter("telefono"),
request.getParameter("email")
);
if(inserto){
salida.println("<br>Usuario agregado");
}else{
salida.println("<br>No fue posible agregar el usuario");
}
}else{
//Agrega la funcionalidad de consultar todos los usuarios
}
I am doing a sample application for UTF-8 with Spring to support multi-language .
This is my JSP with Script ,
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<!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">
</head>
<body>
<h1>Test</h1>
<input type="text" id="hide" />
<input type="text" id="message"/>
<button id="button">test</button>
<div id="messageDisplayArea"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var contexPath = "<%=request.getContextPath() %>";
</script>
<script>
$('#button').on('click', sendMessage);
function sendMessage() {
var intxnId = $("#hide").val();
var message = $("#message").val();
alert("send : \n intxnId : " + intxnId + "\nmessage : " + message);
$.ajax({
type: "POST",
cache: false,
url: contexPath + "/test.html",
async: true,
data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
//dataType: "json",
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8",
success: function(response) {
alert(response);
alert(response.message);
if (response !== null && response !== "" && response !== "null") {
var txt = '{"data":[' + response + ']}';
var json = eval("(" + txt + ")");
for (i = 0; i < json.data.length; i++) {
var data = json.data[i];
var name = data.name;
var message = data.message;
var time = data.time;
alert("Name : " + name + "\nMessage : " + message + "\ntime : " + time);
var createHTML = send(name, message, time);
$("#messageDisplayArea").append(createHTML);
}
;
}
},
error: function(e) {
alert('Error: ' + e);
},
});
function send(name , message , time){
var user = "<div id='user' class='fontStyle'>"+name+"</div>";
var msg = "<div id='msg' class='fontStyle'>"+message+"</div>";
var timeStamp = "<div id='time' class='fontStyle'>"+time+"</div>";
var row = "<div id='msgSet' >"+ user + msg + timeStamp +"</div>";
return row;
}
}
</script>
</body>
</html>
My Spring controller will be ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
String contentType = "application/json; charset=utf-8";
response.setContentType(contentType);
try {
// request.setCharacterEncoding("utf-8");
request.setCharacterEncoding("application/json; charset=utf-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
My Controllers prints ,
Send Message UTF-8 ----------------- தமிழ் அரிச்சுவடி
Send Message :::::::: : {"message":"தமிழ் அரிச்சுவடி","time":"time","name":"test"}
In this my controller prints the local language . But in the JQuery success alert , I got message as ???? . I need to append the local language text in my JSP .
Hope our stack members will help me.
Following piece of code should solve your issue.
#RequestMapping(value="<your path>",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(#RequestParam String intxnId, #RequestParam String message) {
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
This will produce UTF-8 ajax response.
Add mimeType:"application/json; charset=UTF-8" in jQuery.
I got the solution by changing the Controller as ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public ResponseEntity<String> sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
I need to pass some items from my database to the web page. For this i used json object to pass the items from servlet to the jquery. But where i getting the problem is,
If the database contains more element
Then I obviously need to use the ArrayList.
When I use ArrayList I don't know to pass the elements through JSON.
My code is:
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
ArrayList<Commenter> commentInfo;
try {
commentInfo = commenting(uname,message,itemId,albumId);
JsonElement commentObj = gson.toJsonTree(commentInfo);
boolean nonNullElemExist= true;
for (Commenter s: commentInfo) {
if (s == null) {
nonNullElemExist = false;
break;
}
}
if(nonNullElemExist == false){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("commentInfo", commentObj);
out.println(myObj.toString()); // I think problem is in this statement
out.close();
} catch (ClassNotFoundException | SQLException e) {
System.out.println( "Error --> " + displayErrorForWeb(e));
}
And the method is:
private ArrayList<Commenter> commenting(String uname,String message,int itemId,int albumId) throws ClassNotFoundException, SQLException {
ArrayList<Commenter> commentList = new ArrayList<Commenter>();
Connection conn = null;
conn=prepareConnection();
PreparedStatement stmt = null;
String sql = null;
try {
StringBuilder sb1=new StringBuilder(1024);
sb1.append("insert into ").append(uname.trim()).append("comments values(?,?,?)");
String sql1=sb1.toString();
PreparedStatement stmt1 = conn.prepareStatement(sql1);
stmt1.setString(1,uname);
stmt1.setString(2,message);
stmt1.setInt(3,itemId);
StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("comments");
sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
Commenter comment = new Commenter();
comment.setUname(rs.getString("uname").trim());
comment.setComment(rs.getString("comment").trim());
commentList.add(comment);
}
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
catch(Exception e){System.out.println( "Error --> " + displayErrorForWeb(e));}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlex) {
System.out.println( "Error --> " + displayErrorForWeb(sqlex));
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
System.out.println( "Error --> " + displayErrorForWeb(sqlex));
}
conn = null;
}
}
return commentList;
}
And the jquery is :
$.ajax({
type: "GET",
url: "Comments",
data:'comm='+encodeURIComponent(comm)+'&'+'data-id='+encodeURIComponent(dataid)+'&'+'data-alid='+encodeURIComponent(dataalid),
dataType: "json",
success: function( data, textStatus, jqXHR)
{
if(data.success)
{
/* $.each(data, function(i, item)
{*/
var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix"> <section class="c-author">';
newcommhtml = newcommhtml + '<h3>Anonymous</h3>';
newcommhtml = newcommhtml + '<span class="pubdate">'+month+' '+day+', '+year+'</span> </section>';
newcommhtml = newcommhtml + '<section class="c-content">';
newcommhtml = newcommhtml + '<img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava">';
newcommhtml = newcommhtml + '<p>'+nl2br(data.commentInfo.comment)+' '+nl2br(data.commentInfo.itemId)+'</p> </section></div>';
/*newcommhtml = newcommhtml + '<p>'+nl2br(item.commentInfo.comment)+' '+nl2br(item.commentInfo.itemId)+'</p> </section></div>';
});
*/
var thelm = "#c0"+thecid;
commwrap.append(newcommhtml);
$(thelm).hide().fadeIn('slow');
setTimeout(function() { $(thelm).addClass('green'); }, 800);
$("#comm").val("");
thecid++;
if(errorspan.html() != null) {
errorspan.remove();
}
}
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error"+errorThrown);
console.log("Something really bad happened " + textStatus);
},
});
If I use $each() success block wasn't work at all.
Please any one tell me how to do the stuff for this case.........thanks.......
Convert ArrayList to json using new Gson().toJson(object) method. Now you will get a jsonarray of jsonobjects then you can pass it like json to server and vice versa.
Array list is a collection so follow this
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
gson user guide
for displaying json using jquery follow this link.
Best way to display data via JSON using jQuery
Use XStream to convert your object to JSON. It's very simple. You can get a tutorial from it's site. XStream has various drivers. For JSON, you will have to use JettisonMappedXmlDriver.