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
}
Related
I need for my college project a login with user type autentication, its already working with email and password but i dont know how can i send the user to a view depending on the type his user.
I use a oracle database that I made, is like this :
TypeUser(table one)
-idUser PK
-description
User(table two)
-correo PK
-pass
-TypeUser_IdUser FK
i've never do this before so I do not know how to start
//the java class
public class Consultas extends Conexion{
static Connection conn;
//Email - Pass
public boolean autenticacion(String correo, String pass) {
OraclePreparedStatement pst = null;
OracleResultSet rs = null;
conn = Conexion.conexion();
try {
String consulta = "select * from usuario where correo = ? and pass = ?";
pst = (OraclePreparedStatement) conn.prepareStatement(consulta);
pst.setString(1, correo);
pst.setString(2, pass);
rs = (OracleResultSet) pst.executeQuery();
if (rs.next()) {
return true;
}
} catch (Exception e) {
System.err.println("Error" + e);
} finally {
try {
if (pst != null) {
pst.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
System.err.println("Error" + e);
}
}
return false;
}
}
//this is the servlet
String correo = request.getParameter("correo");
String pass = request.getParameter("pass");
String mensaje="";
Consultas co = new Consultas();
if (co.autenticacion(correo, pass)) {
HttpSession objsesion = request.getSession(true);
objsesion.setAttribute("correo", correo);
if (co.autenticacion(correo, pass) || correo.equals ("efrensotex#gmail.com")) {
response.sendRedirect("index.jsp");
}else if(correo.equals("empleado.2l#gmail.com")){
response.sendRedirect("indexEmpleado.jsp");
}else if(correo.equals("prov#gmail.com")){
response.sendRedirect("indexProve.jsp");
}else{
response.sendRedirect("indexCliente.jsp");
}
} else {
mensaje = "Usuario desconocido";
request.setAttribute("mensaje", mensaje);
request.getRequestDispatcher("login.jsp").forward(request, response);
}
in the servlet i have to put the admin email to send the user to his usertype view. Any help or tutorial I'd be really grateful
PD : I user Netbeans and SqlDeveloper
As you are using Servlet,
You can fetch idUser from TypeUser along with correo and pass by executing join query.
Hence you will get user type, After checking credential if its valid you can use switch case for user type, And redirect them as per their types.
if (co.autenticacion(correo, pass){
int userType = request.getParameter("userType");
Switch(usertype){
case 1:
redirect("1.jsp");
break;
case 2:
redirect("2.jsp");
break;
}
}
Hope this will help you.
I was also encountered with with this of situation.So i used the code mentioned below.Hope you find some alternative ways to improve your code.
processLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#page import="com.elibrary.DAO.UserDAO"%>
<%#page import="com.elibrary.beans.UserBean"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Verifying login</title>
</head>
<body>
<jsp:useBean id="user" class="com.elibrary.beans.UserBean"/>
<c:set property="email_id" target="${user}" value='${param.email_id}'/>
<c:set property="password" target="${user}" value='${param.password}'/>
<%
UserBean userbean=UserDAO.varifyLogin(user);
if(userbean!=null){
if(userbean.getUser_type_id()==1){
Cookie cookie=new Cookie("email_id",userbean.getEmail_id());
cookie.setMaxAge(86400);
session.setAttribute("admin",userbean);
response.addCookie(cookie);
response.sendRedirect("admin/adminhome.jsp");
}else if(userbean.getUser_type_id()==2){
Cookie cookie=new Cookie("email_id",userbean.getEmail_id());
cookie.setMaxAge(86400);
session.setAttribute("librarian",userbean);
response.addCookie(cookie);
response.sendRedirect("librarian/librarianhome.jsp");
}else if(userbean.getUser_type_id()==3){
Cookie cookie=new Cookie("email_id",userbean.getEmail_id());
cookie.setMaxAge(86400);
session.setAttribute("student",userbean);
response.addCookie(cookie);
response.sendRedirect("student/studenthome.jsp");
}
}else{
response.sendRedirect("login.jsp?invalid=1");
}
%>
</body>
</html>
I need help with redirecting to different page after login.
I manage to do normal login redirect to appDashboard.jsp however, what I'm trying to do is if the user first-time login into the system then they will be redirected to appSetup.jsp and if not they will be redirected to appDashboard.jsp. How can I do this?
The data for FIRST_TIME in database inserted as yes during registration. Below are my codes.
appLogin.jsp
<!-- Form Module-->
<div class="module form-module">
<div class="toggle"><i class="fa fa-times fa-pencil"></i>
<div class="tooltip" style=" margin-right: -110px;">Not a member? Register Here</div>
</div>
<!-- LOGIN FORM-->
<div class="form">
<h2>Login to your account</h2>
<form action="AppLogin">
<input type="text" placeholder="Username" name="appusername"/>
<input type="password" placeholder="Password" name="apppassword"/>
<button type="submit" name="login">Login</button>
</form>
</div>
<div class="cta">Forgot your password?</div>
</div>
ApplicantLoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
ApplicantBean applicant = new ApplicantBean();
applicant.setUsername(request.getParameter("appusername"));
applicant.setPassword(request.getParameter("apppassword"));
applicant = ApplicantDA.Login(applicant);
if(applicant.isValid()) {
HttpSession session = request.getSession(true); //creating session
session.setAttribute("currentApplicant", applicant);
PrintWriter out = response.getWriter();
String firstTime = applicant.getFirstTime();
if(firstTime == "yes" ) {
System.out.println("ft " + firstTime);
response.setContentType("text/html");
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('Successfully Logged In.');");
out.println("window.location= \"appSetup.jsp\"");
out.println("</script>");
}
else {
response.setContentType("text/html");
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('Successfully Logged In.');");
out.println("window.location= \"appDashboard.jsp\"");
out.println("</script>");
}
}
else {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('Sorry, invalid username or password.');");
out.println("window.location= \"appLogin.jsp\"");
out.println("</script>");
//response.sendRedirect("InvalidLogin.jsp");
}
}
catch (Throwable theException) {
System.out.println(theException);
}
}
ApplicantDA.java
public static ApplicantBean Login(ApplicantBean bean) { //ApplicantLoginServlet line 24.
//preparing some objects for connection
Statement stmt = null;
String username = bean.getUsername();
String password = bean.getPassword();
String searchQuery = "SELECT * FROM APPLICANT WHERE APPLICANT_USERNAME='" + username + "'AND APPLICANT_PASSWORD='" + password + "'";
//"System.out.println" prints in the console; Normally used to trace the process
System.out.println("Your username is " + username);
System.out.println("Your password is " + password);
System.out.println("Query : " + searchQuery);
try {
//Connect to DB
currentCon = ConnectionManager.getConnection();
stmt = currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
if(!more) {
System.out.println("Sorry, you are not a registered user! Please sign up first.");
bean.setValid(false);
}
else if(more) {
String fullname = rs.getString("APPLICANT_FULLNAME");
String email = rs.getString("APPLICANT_EMAIL");
String image = rs.getString("APPLICANT_IMAGE");
String firstTime = rs.getString("FIRST_TIME");
System.out.println("Welcome " + fullname);
System.out.println("Email : " + email);
System.out.println("Image : " + image);
System.out.println("First Time : " + firstTime);
bean.setFullname(fullname);
bean.setEmail(email);
bean.setImage(image);
bean.setValid(true);
}
}
catch(Exception ex) {
System.out.println("Login failed: An Exception has occured! " + ex);
}
//some exception handling
finally {
if(rs != null) {
try {
rs.close();
}
catch(Exception e) {
}
rs = null;
}
if(stmt != null) {
try {
stmt.close();
}
catch(Exception e) {
}
stmt = null;
}
if(currentCon != null) {
try {
currentCon.close();
}
catch(Exception e) {
}
currentCon = null;
}
}
return bean;
}
ApplicantBean.java
public class ApplicantBean {
private String fullname;
private String username;
private String email;
private String password;
private String image;
private String firstTime;
public boolean valid;
public String getFullname() { return fullname; }
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getPassword() { return password; }
public String getImage() { return image; }
public String getFirstTime() { return firstTime; }
public void setFullname(String newFullname) {
fullname = newFullname;
}
public void setUsername(String newUsername) {
username = newUsername;
}
public void setEmail(String newEmail) {
email = newEmail;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public void setImage(String newImage) {
image = newImage;
}
public void setFirstTime(String newFirstTime) {
firstTime = newFirstTime;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
This is my first time learning servlet. Thankyou in advance!
I created a java class called Executar_Query_Bd_Multiplos_Resultados in this class as the parameter for the Conectar method 2 values (int Integer1, int Integer2) of integer type.
These values are received by the query:
"SELECT DS_ESTRATEGY, STRID_ID" +
"FROM TB_BKOFFICE_ESTRATEGY" +
"WHERE IN_STRATEGY_ID IN (" + Istrategy1 + "," + Istrategy2 + ")";
The result of the above query is stored in the variable ls_command.
In the Executar_Query_Bd_Multiplos_Resultados_Test class I make the method call (Connect) and step 2 parameters (179, 319) and command to print on the screen the variable of type String codEstrategies.
But Eclipse only displays 1 result on the console. The query should bring 2 results and not 1. Here is the code for the Java classes and the result of the query executed in Oracle SQL Developer.
public class Executar_Query_Bd_Multiplos_Resultados_Test {
#Before
public void setUp() throws Exception {
Executar_Query_Bd_Multiplos_Resultados qr_2 = new Executar_Query_Bd_Multiplos_Resultados();
String codEstrategias = qr_2.Conectar(179, 319);
System.out.println("Estratégias: " + codEstrategias);
}
#After
public void tearDown() throws Exception {
}
#Test
public void test() {
}
}
public class Executar_Query_Bd_Multiplos_Resultados {
//Variáveis de BD
Connection conOracle = null;
Statement stmtOracle = null;
ResultSet rsetOracle = null;
public String Conectar(int Id_Estrategia1, int Id_Estrategia2) {
String retorno = "#;-1;#";
Boolean lb_continuar = true;
//StringBuilder ls_comando = new StringBuilder();
String ls_comando = new String();
try {
System.out.println("Conectando ao banco de dados Oracle...");
String url = "";
try {
//conectando aos bancos de dados
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
DriverManager.setLoginTimeout(10);
conOracle = (Connection) DriverManager.getConnection(url, "bkofficeadm", "bkofficeadmdesenv01");
} catch (SQLException e) {
System.out.println("falha SQL >> " + e.getMessage());
} catch (Exception e) {
//System.out.println("falha geral >> " + e.getMessage());
e.printStackTrace();
lb_continuar = false;
}
//String teste = "'BKO - Rep Conectividade'";
if (lb_continuar) {
System.err.println("Preparando comando...");
System.out.println("");
ls_comando = "SELECT DS_ESTRATEGIA, ID_ESTRATEGIA"+
" FROM TB_BKOFFICE_ESTRATEGIA"+
" WHERE ID_ESTRATEGIA IN (" + Id_Estrategia1 + ", " + Id_Estrategia2 + ")";
System.out.println(ls_comando);
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
rsetOracle = stmtOracle.executeQuery(ls_comando.replaceAll("\n", " ").trim());
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
rsetOracle.close();
stmtOracle.close();
/*
Para comandos de Insert, Delete, ou Update
--------------------------------------------------------
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
stmtOracle.execute(variavel_comando.toString());
conOracle.commit();
stmtOracle.close();
*/
}
} catch (Exception ex) {
System.out.println("Erro - " + ex.getMessage());
} finally {
try {
if (rsetOracle != null) {
rsetOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar rset - " + e.getMessage());
}
try {
if (stmtOracle != null) {
stmtOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar stmt - " + e.getMessage());
}
try {
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar con - " + e.getMessage());
}
}
return retorno;
}
}
Output from SQL Devleoper query:
Output from Eclipse console:
You're doing this
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
This runs once
Consider while instead:
List<String> retornos = new ArrayList<>();
while(rsetOracle.next()) {
retornos.add(rsetOracle.getString(1));
}
This will run until you're out of rows.
If something like this happens in the future, you'll want to modify your query to select count(*) ... and verify you get the same result in both the database workbench and your javacode. Then you'll at least know you've got the right query, and it's your presentation that's failing.
Note:
I understand this question is indeed a duplicate of other questions. However, those are difficult to search. I would propose this be a canonical answer.
I know this question has been asked a lot of times, but so far, none of the answers previously given have worked for me, here is my code:
<html>
<head>
<title>Programa</title>
</head>
<body>
<div>
Introduzca una palabra a buscar:
<input type="text" id="INPUT">
<%# page import="java.net.URL" %>
<%# page import="com.google.gson.*" %>
<%# page import="java.net.URLEncoder" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.InputStream" %>
<%# page import="java.io.Reader" %>
<%# page import="javax.swing.*" %>
<%# page import="java.awt.event.*;" %>
<%!
int min(int a,int b) {
return (a>b)? b:a;
}
int edit_distance(String a,String b) {
int n = a.length(), m = b.length(),costo;
int[][] mat = new int[n+1][m+1];
for(int i=0;i<=n;++i) mat[i][0] = i;
for(int j=0;j<=m;++j) mat[0][j] = j;
for(int i=1;i<=n;++i) {
for(int j=1;j<=m;++j) {
costo = a.charAt(i-1) == b.charAt(j-1)? 1 : 0;
mat[i][j] = min(min(mat[i-1][j] + 1,mat[i-1][j-1] + costo),mat[i][j-1] + 1);
}
}
return mat[n][m];
}
String resultados_de_la_busqueda(String search) { //Básicamente lo que hace esta función es devolverte una cadena con los resultados de la búsqueda
StringBuffer RES = new StringBuffer("<html>");
String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="; //El enlace para buscar en google
String charset = "UTF-8";
URL url;
Reader reader;
try {
url = new URL(google + URLEncoder.encode(search, charset));
try {
reader = new InputStreamReader(url.openStream(), charset);
GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);
for(int i=0;i<3;++i) {
RES.append(results.getResponseData().getResults().get(i).getTitle());
RES.append("<br/>");
RES.append("<a href=\"");
RES.append(results.getResponseData().getResults().get(i).getUrl());
RES.append("\">" + results.getResponseData().getResults().get(i).getUrl() + "</a>");
RES.append("<br/><br/>");
}
} catch(Exception e) {}
} catch(Exception e) {}
return RES.toString();
}
%>
<%
//Se supone que acá debo mostrar el resultado de la búsqueda...
out.println(resultados_de_la_busqueda("taringa"));
%>
</div>
</body>
</html>
And here is the error I'm getting:
org.apache.jasper.JasperException: No se puede compilar la clase para JSP:
Ha tenido lugar un error en la línea: 47 en el archivo jsp: /Programa.jsp
GoogleResults cannot be resolved to a type
Gson cannot be resolved to a type
Any idea on what is causing the problem?
Edit 1:
This is the GoogleResults class:
import java.util.List;
public class GoogleResults {
private ResponseData responseData;
public ResponseData getResponseData() { return responseData; }
public void setResponseData(ResponseData responseData) { this.responseData = responseData; }
public String toString() { return "ResponseData[" + responseData + "]"; }
static class ResponseData {
private List<Result> results;
public List<Result> getResults() { return results; }
public void setResults(List<Result> results) { this.results = results; }
public String toString() { return "Results[" + results + "]"; }
}
static class Result {
private String url;
private String title;
public String getUrl() { return url; }
public String getTitle() { return title; }
public void setUrl(String url) { this.url = url; }
public void setTitle(String title) { this.title = title; }
public String toString() { return "Result[url:" + url +",title:" + title + "]"; }
}
}
Seems like its not picking up your class...
Do a Project>Clean and then Refresh it (F5).
Hoped this helped, here is where I got it from:
Click here
Sometimes if you are importing your project into a new workspace, this problem is encountered if JRE was different of the previous workspace frm the new workspace, try changing the jre system library in build path. It works out
This Happen to me after my java was automatically updated.
Check The JRE is correctly set:
RClick on the project , choose Build Path ->configure Build Path , Go to libraries Path and make sure JRE System library is properly configured.
Always put your classes in packages.
Make sure your GoogleResults.class is being compiled under WEB-INF/classes/
Also it seems to me like you should import this file at the beginning of your .jsp.
Hope this help
Create new project. Copy all files in this new project from old project.
Delete old one and rename new project.
Thats it. It will work fine
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.