Json data how to pass in to DataTable using Jsp - java

i am creating simple crud system using jsp. data passing through json format i tested through console it is passing well but data is not display on the datatable.i don't why. i wrote what i tried so far.
Table
<table id="tbl-projects" class="table table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
jQuery
<script>
get_all()
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$('#etbl-projects').DataTable().ajax.reload();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
alert(data.course);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns": [
{"sTitle": "StudentName", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
{
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="get_project_details(' + mData + ')">Edit</button>';
}
},
{
"sTitle": "Delete",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-primary" onclick="Remove_details(' + mData + ')">Delete</button>';
}
}
]
});
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</script>
all_project.jsp
Jsp Page
<%#page import="org.json.simple.JSONObject"%>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from records";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id =rs.getString("id");
String name =rs.getString("name");
String course =rs.getString("course");
String fee =rs.getString("fee");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("course", course);
json.put("fee", fee);
json.put("id", id);
out.print(json);
out.flush();
}
%>
i have tested through the console result. screen shot below
{"fee":"10000","name":"john","course":"java","id":"1"}{"fee":"7000","name":"Raja","course":"C#","id":"2"}{"fee":"2323","name":"sad","course":"asd","id":"3"}{"fee":"12000","name":"Nishan","course":"Jsp","id":"4"}
i have attached the Datatable image below
enter image description here

Your response in JSON format is invalid (missing comas between object).
Use org.json.simple.JSONArray to create a list of objects, for example:
<%#page import="org.json.simple.JSONArray"%>
...
JSONArray list = new JSONArray();
while(rs.next())
{
String id = rs.getString("id");
String name = rs.getString("name");
String course = rs.getString("course");
String fee = rs.getString("fee");
JSONObject obj = new JSONObject();
obj.put("name", name);
obj.put("course", course);
obj.put("fee", fee);
obj.put("id", id);
list.put(obj);
}
out.print(list.toJSONString());
out.flush();

Related

Why prepared statement in jdbc in jsp program is returning null value

As a part of my project, I started a student monitoring system. As a part of this, I want to insert the student details into the database. I want to insert entered details into database using a prepared statement. In this process I faced this issue. How to solve?
The code is as follows.
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<html>
<body bgcolor = "pink">
<%!
Connection con;
PreparedStatement ps;
public void jspInit()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection( "jdbc:oracle:thin:#localhost:1521:XE","system","sai");
ps = con.prepareStatement("insert into list(?,?,?,?,?,?)");
}
catch(Exception ex){ex.printStackTrace();}
}
%>
<%
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String ID = request.getParameter("ID");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
%>
<h2 align = "center"><font color = "red">Your Entered Details::</font></h2>
<table align = "center" border = "1px solid black" cellspacing = "2px" cellpadding="5px">
<tr>
<td><b>Field</b></td>
<td><b>data</b></td>
</tr>
<tr>
<td><b>Firstname</b> </td>
<td><%=firstname%></td>
</tr>
<tr>
<td><b>Lastname</b></td>
<td><%=lastname%></td>
</tr>
<tr>
<td><b>Student ID</b></td>
<td><%=ID%></td>
</tr>
<tr>
<td><b>Gender </b></td>
<td><%=gender%></td>
</tr>
<tr>
<td><b>Phone </b></td>
<td><%=phone%></td>
</tr>
<tr>
<td><b>Email</b></td>
<td><%=email%> </td>
</tr>
</table>
<%
try
{
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.setString(3,ID);
ps.setString(4,gender);
ps.setString(5,phone);
ps.setString(6,email);
int i = ps.executeUpdate();
if(i>0)
{
out.println("<h3 align = 'center'><font color = 'red'>successfully registered</font></h3>");
out.println("<h4 align = 'center'>Click here to.! -> <a href='http://localhost:9999/kaushik/index.html'>Go back</a></h4>");
}
else
{
out.println("<h3 align = 'center'><font color = 'red'>Unable to register</font></h3>");
out.println("<h4 align = 'center'>please try again.! -> <a href='http://localhost:9999/kaushik/insert.html'> click here</a></h4>");
}
}
catch(Exception ex){out.println("An exception occurred: " + ex);}
%>
<%!
public void jspDestroy()
{
try
{
ps.close();
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
</body>
</html>
I think the is no problem in the variables set (firstname, lastname, etc.) as those values are successfully being displayed in the table.
So, the ps.setString(...) is not working because ps is set to null. I created the table in Oracle database. How to solve this issue? What is the error in my program?

Data is not loaded in to Datatable using Jsp Ajex crud

i am creating simple crud system.i am beginner of jsp.i can add data into the database using ajax in JSP record added successfully.after add the record i tried to load the data on datatable but data is not loading on datatable
i written code below. what i tried so far
Table
<table id="tbl-projects" class="table table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</table>
********JQuery********
<Script>
get_all();
function get_all()
{
$('#tbl-projects').dataTable().fnDestroy();
$.ajax({
url : "all_project.jsp",
type : "GET",
dataType : "JSON",
success:function(data)
{
$('#tbl-projects').html(data);
$('#tbl-projects').dataTable({
"aaData": data,
"scrollX": true,
"aoColumns": [
{"sTitle": "StudentName", "mData": "name"},
{"sTitle": "Course", "mData": "course"},
{"sTitle": "Fee", "mData": "fee"},
{
"sTitle": "Edit",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="get_project_details(' + mData + ')">Edit</button>';
}
},
{
"sTitle": "Delete",
"mData": "id",
"render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-primary" onclick="Remove_details(' + mData + ')">Delete</button>';
}
}
]
});
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
// content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
</Script>
this is the Jsp code
all_project.jsp JSP CODE
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<%
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
String query="select * from record";
Statement stmt=con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
String id =rs.getString("id");
String name =rs.getString("name");
String course =rs.getString("course");
String fee =rs.getString("fee");
out.println(id);
out.println(name);
out.println(course);
out.println(fee);
}
%>
data displayed on the console look like this
**1
john
java
10000
2
Raja
C#
7000
3
sad
asd
2323
4
Nishan
Jsp
12000**
but but display on the datatable
Add the data into the database code JSP Ajax
function addProject()
{
if($("#frmProject").valid())
{
var url= '';
var dat = '';
var method = '';
if(isNew == true)
{
url = 'add.jsp';
data = $('#frmProject').serialize();
method = 'POST';
}
else
{
url = 'update_project.jsp';
data = $('#frmProject').serialize() + "&project_id=" + project_id;
method = 'POST';
}
$.ajax({
type : method,
url : url,
dataType : 'JSON',
success : function (data)
{
$('#frmProject')[0].reset();
$('#save').html('');
$('#save').append('Add');
var msg;
get_all();
if(isNew)
{
msg = "Course Created";
}
else
{
msg = "Course Updated";
}
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
// content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
add.jsp
<%#page import="java.sql.*" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
String studname = request.getParameter("studname");
String course = request.getParameter("course");
String fee = request.getParameter("fee");
Connection con;
PreparedStatement pst;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud", "root","");
pst = con.prepareStatement("insert into records(name,course,fee)values(?,?,?)");
pst.setString(1,studname);
pst.setString(2,course);
pst.setString(3,fee);
pst.executeUpdate();
%>
With version 1.10.0 of DataTables, it is built-in and easy:
var table = $('#example').DataTable();
table.ajax.reload();
Or may be :
$('#example').DataTable().ajax.reload();

Autocomplete country text box in jsp form with data in my table tbcntry using jquery

//below is my form page with a text box for country i want to display all countries with letters starting and auto completing with values in my database with data for country using jsp,java,jquery
<html>
<head>
<link href = "https://code.jquery.com/ui/1.10.4/themes/uilightness/jquery- ui.css"rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#country').focusin(function() {
$("#country").autocomplete("List.jsp");
});
});
</script>
</head>
<body>
<br><br><center>
<font face="verdana" size="2">
<font size="4">Java(jsp)/jQuery Autocompleter Example</font>
<br><br><br><br>
Select Country :
<input type="text" id="country" name="country"/>
</font>
</body>
</html>
//below is the List.jsp page that have connection to database
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try {
String s[] = null;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver found");
String url = "jdbc:mysql://localhost:protNum/dbName";
String user = "";
String pass = "";
System.out.println("Connected....");
Connection con = (Connection) DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tbctry");
List li = new ArrayList();
while (rs.next()) {
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while (it.hasNext()) {
String p = (String) it.next();
str[i] = p;
i++;
}
//jQuery related start
String query = (String) request.getParameter("q");
int cnt = 1;
for (int j = 0; j < str.length; j++) {
if (str[j].toUpperCase().startsWith(query.toUpperCase())) {
out.print(str[j] + "\n");
if (cnt >= 5)// 5=How many results have to show while we are typing(auto suggestions)
{
break;
}
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
//Below is a implementation of autocomplete using json and jquery
//Jsp form page for entering country name as a text box while user enters the First letter the autocomplete start functioning
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Autocomplete in java web application using Jquery and JSON</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script>
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source: function(request, response) {
$.ajax({
url: "CountryListCheck",
type: "GET",
data: {
term: request.term
},
dataType: "json",
success: function(data) {
response(data);
}
});
}
});
});
});
</script>
</head>
<body>
<div class="header">
<h3>Autocomplete in java web application using Jquery and JSON</h3>
</div>
<br />
<br />
<div class="search-container">
<div class="ui-widget">
country:
<input type="text" id="search" name="search" class="search" />
</div>
</div>
</body>
</html>
//below is the code to be placed on controller corresponding to url CountryListCheck
"/CountryListCheck":
String term = request.getParameter("term");
System.out.println("Data from ajax call " + term);
ArrayList<String> list = new Op_contact(dcon).getAllCountriesCheck(term);
System.out.println(list);
Json = new Gson().toJson(list);
response.getWriter().write(Json );
//below is the operation class code or database query section
public ArrayList<String> getAllCountriesCheck(String l) {
ArrayList<String> list = new ArrayList<String>();
PreparedStatement ps = null;
String data;
try {
String ch=l+"%";
ps = (PreparedStatement) dcon.con.prepareStatement("SELECT nicename FROM tbctry WHERE nicename LIKE '"+ch+"'");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
data = rs.getString("nicename");
System.out.println(data);
list.add(data);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}

JSP - Changing values in SQL database

I have a table where I display items from database. In first ResultSet I have created an dropdown menu that let you choose if you want item to be available or not. But, because I have created it in first ResultSet rs, I cannon use it in second ResultSet rs1. Problem is in this line:
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno"))
And here is the whole code:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<%
out.print("<p align = \"center\">Administrator <a style=\"color:red;\">" + session.getAttribute("user") + "</a></p>");
%>
<table align = "center" bgcolor = "darkgrey" border = "1" cellpadding="3" cellspacing="1">
<tr>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</tr>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
%>
<tr bgcolor="grey">
<td><%=rs.getString("naziv")%></td>
<td><%=rs.getString("opis")%></td>
<td><%=rs.getString("cena")%></td>
<%
if (rs.getString("dostupnost").equals("1")) {
out.print("<td><p style = \"color: green; font-size: 20px\">Dostupno</p></td>");
} else {
out.print("<td><p style = \"color: red; font-size: 20px\">Nedostupno</p></td>");
}
%>
<%
int a = rs.getInt("dostupnost");
if (a == 1) {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
} else {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
}
}
%>
</tr>
<tr><td></td><td></td><td></td><td></td>
<td align=center>
<form method="post">
<% Statement statement1 = connection.createStatement();
int bre;
ResultSet rs1 = statement.executeQuery(sql);
while (rs1.next()) {
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno")) {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
} else {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<input type="submit" value="Apply" name="Apply" />
</form>
</td>
</tr>
</table>
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;"><img src = "Slike/home.png" alt = "home"/></p>
</body>
First, I'll split your code in Servlets and JSP and show you why this is a better way to go.
Your view (assuming is called "foo.jsp"):
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!-- adding JSTL to your project -->
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<p align="center">
Administrator <span style="color:red"><c:out value="${user}" /></span>
</p>
<!--
In this case, the form should wrap all your table
since you want to process all the input elements
inside it. Otherwise, you will update the entire data
rather than update per entity.
-->
<form method="post">
<table align="center" bgcolor="darkgrey" border="1" cellpadding="3" cellspacing="1">
<th>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</th>
<c:forEach items="${oruzjeList}" var="oruzje">
<tr bgcolor="grey">
<td>${oruzje.naziv}</td>
<td>${oruzje.opis}</td>
<td>${oruzje.cena}</td>
<td>
<p style="color: green; font-size: 20px">
<!-- printing the value dynamically in view -->
<c:out value="${oruzje.dostupnost == '1' ? 'Dostupno' : 'Nedostupno'}" />
</p>
</td>
<td>
<!--
oruzje.naziv should be an ID, not the "unique name"
because a name could contain empty spaces which
will break the name of the component
here I use id but you will replace it with your ID
-->
<select name="polje_${oruzje.id}">
<option value="1" ${oruzje.dostupnost == '1' ? 'selected' : ''}>Dostupno</option>
<option value="0" ${oruzje.dostupnost == '0' ? 'selected' : ''}>Nedostupno</option>
</select>
<!--
Additionally, we need to obtain the respective id for
the row to be updated.
We will use a hidden input field which uses the ID
-->
<input type="hidden" name="hidId_${oruzje.id}" value="${oruzje.id}" />
</td>
</tr>
</c:forEach>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="submit" value="Apply" />
</td>
</tr>
</table>
</form>
<p style="position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">
<img src="Slike/home.png" alt="home"/>
</p>
</body>
</html>
This assumes you have an entity that supports that maps to your database table:
public class Oruzje {
private int id;
private String naziv;
private String opis;
private String cena;
private String dostupnost;
//propers getters and setters for your fields
}
Now, your Servlet:
//yes, a Servlet can map directly to your JSP
//there's no problem using this approach
#WebServlet("/foo.jsp")
public class OruzjeServlet extends HttpServlet {
//I won't go far with more classes
//nor with other improvements to the code
//I'll write the basic stuff here in Servlet
//this method should be in an utility class
//to provide reusability
private void closeResource(Closeable resource) {
try {
if (resource != null) {
resource.close();
}
} catch (IOException e) {
//silent exception
}
}
//this method should also be in an utility class
//and should recover the connection from a DataSource
//instead of creating the physical connection everytime
private Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
} catch (Exception e) {
//this should be splitted for better handling
//but I leave this up to you
//handle the exception
//very basic handling
e.printStacktrace();
}
}
//this method should be in a proper DAO class
//reusing a connection for execution of multiple statements
private List<Oruzje> getOruzjeList(Connection con) {
List<Oruzje> oruzjeList = new ArrayList<Oruzje>();
Statement statement = null;
ResultSet rs = null;
try {
statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
Oruzje oruzje = new Oruzje();
oruzje.setId(rs.getInt("id")); //use the real column
oruzje.setNaziv(rs.getString("naziv"));
oruzje.setOpis(rs.getString("opis"));
oruzje.setCena(rs.getString("cena"));
oruzje.setDostupnost(rs.getString("dostupnost"));
oruzjeList.add(oruzje);
}
} catch (SQLException e) {
//again, handle the exception
e.printStacktrace();
} finally {
closeResource(rs);
closeResource(statement);
}
return oruzjeList;
}
//this method will be executed when a client (browser)
//tries to enter to your foo.jsp page
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
closeResource(con);
//setting the oruzjeList variable as attribute
//this will feed the ${oruzjeList} used in the
//<c:forEach>
request.setAttribute("oruzjeList", oruzjeList);
//now, forward the view to the right view (JSP)
//it is not a redirect
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
//this method will be executed when user selects "Apply"
//option in the view (the JSP)
//because you stated that the method to submit the <form>
//is POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//now, we just retrieve the necessary parameters and process the data
//sent from the form
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
//each ? is a parameter in the query
//starting at index 1
String updateSql = "UPDATE oruzje SET dostupnost = ? WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement();
for(Oruzje oruzje : oruzjeList) {
//this is where the static part of the name becomes handy
String theId = request.getParameter("hidId_" + oruzje.getId());
String theDostupnost = request.getParameter("polje_" + oruzje.getId());
//I'll avoid basic validation like
//if (theId == null || "".equals(theId))
//right to the update!
//setting the first parameter: dostupnost = ?
pstmt.setString(1, theDostupnost);
//setting the second parameter: ID = ?
//since it's an int, parsing the String to int
pstmt.setInt(2, Integer.parseInt(theId));
//perform the update for the current ID and Dostupnost
pstmt.execute();
}
//at the end, closing the resources
closeResource(pstmt);
//this is cumbersome but just to make sure
//the data was updated successfully
oruzjeList = getOruzjeList(con);
closeResource(con);
//similar to the doGet, we will forward to the view
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
}
More info:
How to avoid Java code in JSP files?
StackOverflow JSTL Wiki
StackOverflow EL Wiki
Difference between JSP forward and redirect
Sending a variable from Servlet to JSP
Retrieve values from JDBC and use JSTL tags to call the methods
Is it a good idea to put jdbc connection code in servlet class?
Difference between Statement and PreparedStatement

Send and Retrieve Data using JSON and AJAX

I have the following front end code, I need to get the textfield(id=uid) value and parse it to the servlet and based on that value, fill the other two textfields(It's a Search Function), But following code only retrieves the values, couldn't send the "uid". How could I do that? Please help me.
<script type="text/javascript">
$(document).ready(function(){
$('#getData').click(function(){
$.ajax({
url:'JsonServlet',
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
});
</script>
</head>
<body>
UserID:<input name="userid" type="text" id="uid"/><br/>
Name:<input type="text" id="uname"/>
Address:<input type="text" id="uadd"/>
<input type="button" id="getData" value="Get Data"/>
My servlet Code looks like this
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String userid = request.getParameter("userid");
ResultSet rs = db.selectQuery("select * from tbl_user where userid = '"+userid+"'");
JSONObject json = new JSONObject();
while (rs.next()) {
json.put("uname", rs.getString("username"));
json.put("uadd", rs.getString("useraddress"));
}
//json.put("uname", "user1");
// json.put("uadd", "address1");
out.print(json);
} catch (Exception e) {
e.printStackTrace();
}
your ajax should like this..
$.ajax({
url:'JsonServlet?userid='+document.getElementById("uid").value,
type:'post',
dataType: 'json',
success: function(data) {
$('#uname').val(data.uname);
$('#uadd').val(data.uadd);
}
});
});
the you should able to use String userid = request.getParameter("userid");

Categories