Receive values in JSP from JS function created in other JSP - javascript

I have written a code where I want the admin to be able to change the user as active or inactive through radio button. For that I am using JSP, MySQL and JS.
admin.jsp:
<tr>
<td>
Name: <% out.println(firstname); %> <% out.println(lastname); %>
</td>
<td>
<% if (flag.equals("A")){ %>
Active: <input type="radio" value="A" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecta('<% out.println(email); %>', this.value);" checked>
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecti('<% out.println(email); %>', this.value);">
<%
}else if(flag.equals("I")){%>
Active: <input type="radio" value="A" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecta('<% out.println(email); %>', this.value);">
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="<% out.println(email); %>" onchange="pageupdatecti('<% out.println(email); %>', this.value);" checked>
<%
} %>
<script type="text/javascript">
function pageupdatecta(emailid, optedval) {
location.href='changeToActive.jsp?email='+emailid+'&optedval='+o‌​ptedval;
}
function pageupdatecti(emailid, optedval) {
location.href='changeToInactive.jsp?email='+emailid+'&optedval='+o‌​ptedval;
}
</script>
changeToActive.jsp:
try{
Class.forName("com.mysql.jdbc.Driver");
System.err.println("Driver loaded!");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/work", "root", "MyNewPass");
System.err.println("Database Connected..");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
stmt.executeUpdate("update assignment set flag='A' where email='"+email+"'");
System.err.println("A"+email);
}
Can you tell me how to receive values from the function, and make my code work?

The below code will fetch a record from assignment table of work database for id=1.
The checked status of the radio button will be decided by the existing checked status in the DB.
Here, as soon as you change the status from active to inactive OR inactive to active the changes will be reflected successfully in the database.
index.jsp Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%# page import="java.sql.*,stack.filter.JDBCConnector" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Radio Select</title>
</head>
<body>
<%
Connection con = null;
String firstname = null;
String lastname = null;
String email = null;
String flag = null;
try {
con = JDBCConnector.connect_database();
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from assignment where id=1");
while(rs.next()){
firstname=rs.getString(2);
lastname=rs.getString(3);
email=rs.getString(4);
flag=rs.getString(5);
}
System.out.println(""+firstname+" "+lastname+" "+email+" "+flag);
} catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
}
%>
<table>
<tr>
<td>
Name: <% out.println(firstname); %> <% out.println(lastname); %>
</td>
<td>
<%
if(flag.equals("A")){
%> Active: <input type="radio" name="<%=email%>" id="r1" value="A" onclick="updateStatus()" checked="checked"/>
In active: <input type="radio" name="<%=email%>" id="r2" value="I" onclick="updateStatus()"/>
<%
}else if(flag.equals("I")){
%> Active: <input type="radio" name="<%=email%>" id="r1" value="A" onclick="updateStatus()"/>
In active: <input type="radio" name="<%=email%>" id="r2" value="I" onclick="updateStatus()" checked="checked"/>
<%
}
%>
</td>
</tr>
</table>
<script type="text/javascript">
function updateStatus(){
if (document.getElementById('r1').checked) {
location.href='changeToActive.jsp?email='+'${email}'+'&status=A';
}else if (document.getElementById('r2').checked) {
location.href='changeToActive.jsp?email='+'${email}'+'&status=I';
}
}
</script>
</body>
</html>
changeToActive.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*,stack.filter.JDBCConnector" %>
<%
Connection con = null;
try {
con = JDBCConnector.connect_database();
System.err.println("Database Connected..");
Statement stmt = con.createStatement();
String status = request.getParameter("status");
String email = request.getParameter("email");
int i= stmt.executeUpdate("UPDATE assignment SET status='"+status+"' where email='"+email+"'");
if(i==1){
out.println("Successfully updated the status");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
con.close();
}
%>
JDBCConnector.java class: created for centrally creating connection object in your app.
package stack.filter;
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCConnector {
public static Connection connect_database(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/work", "root", "root");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(con!=null)
{
System.out.println("Connected...");
}
}
return con;
}
}
Assignment Table:
CREATE TABLE `assignment` (
`id` INT(11) NOT NULL,
`firstname` VARCHAR(30) DEFAULT NULL,
`lastname` VARCHAR(30) DEFAULT NULL,
`email` VARCHAR(30) DEFAULT NULL,
`status` CHAR(1) DEFAULT NULL,
PRIMARY KEY (`id`)
)
/*Data for the table `assignment` */
INSERT INTO `assignment`(`id`,`firstname`,`lastname`,`email`,`status`) VALUES (1,'rohit','gaikwad','rohitgaikwad#xyz.com','I');
Note: The id=1 primary key is hardcoded, I guess you have some logic that displays a record of assignment in your html table.

You can get the values of query parameters with:
String email = request.getParameter("email");
String optedval = request.getParameter("optedval");
Then you can use them in your sql statement.

It should be like this. You have given same id to both the radio.
Active: <input type="radio" value="A" name="<% out.println(email); %>" id="id1" onchange="pageupdatecta('<% out.println(email); %>');" checked>
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" id="id2" onchange="pageupdatecti('<% out.println(email); %>');">
<script>
function pageupdatecta(emailid) {
alert('Hi');
location.href='changeToActive.jsp?email='+emailid;
}
function pageupdatecti(emailid) {
alert('Hi');
location.href='changeToActive.jsp?email='+emailid;
}
</script>
and in your servlet use String email = request.getParameter("email");to get the value of email variable.

Related

How to get data from API for only chosen categories

I have an app, it uses an external api for data
http://newsapi.org/v2/top-headlines?category=alpha&apiKey=APIKEY
this external API shows data for several categories:
http://newsapi.org/v2/top-headlines?category=beta&apiKey=APIKEY
http://newsapi.org/v2/top-headlines?category=gamma&apiKey=APIKEY
http://newsapi.org/v2/top-headlines?category=theta&apiKey=APIKEY
My app has user login and select which category they prefer. Its a multiselect control.
Based on the selection of the categories, I need to show data from those.
Eg: if user selected alpha and beta and save it. Then the homepage should show NEWS from those two categories only in one list
I am using Node JS Express and Mongo with vanilla JS
Following is some code I wrote, but unable to make it work.
index.js
router.get('/homepage', auth, async(req,res)=>{
const alpha= req.user.alpha
const beta = req.user.beta
const gamma= req.user.gamma
const theta= req.user.theta
if (alpha== 'yes'){
var url = 'http://newsapi.org/v2/top-headlines?category=alpha&apiKey=APIKEY';
const news_alpha =await axios.get(url)
}
if (beta == 'yes'){
var url = 'http://newsapi.org/v2/top-headlines?category=beta&apiKey=APIKEY';
const news_beta =await axios.get(url)
}
if (gamma== 'yes'){
var url = 'http://newsapi.org/v2/top-headlines?category=gamma&apiKey=APIKEY';
const news_gamma =await axios.get(url)
}
if (theta== 'yes'){
var url = 'http://newsapi.org/v2/top-headlines?category=theta&apiKey=APIKEY';
const news_theta =await axios.get(url)
}
//HERE I AM TRYING TO SEND ALL VALID CATEGORIES DATA TO UI. NOT SURE IF ITS RIGHT WAY TO DO!
try {
res.status(200).render('home',{articles:news_alpha.data.articles, articles:news_beta.data.articles, articles:news_gamma.data.articles, articles:news_theta.data.articles, user: req.user, id: req.user._id})
} catch (error) {
if(error.response){
console.log(error)
}
}
});
homepage.ejs
<div >
<% articles.forEach(function(article,index){ %>
<% if ((typeof article.url=='object') || (typeof article.title=='object') || (typeof article.urlToImage=='object') || (typeof article.content=='object')){ %>
<% } else{ %>
<a href="<%- article.url %>" target="_blank" class="news-box Hover-effect">
<!-- <img src="<%- article.urlToImage %>" alt="Image"> -->
<h3>
<%- article.title %>
</h3>
<p>
<%- article.content.replace(/<[^>]+>/g, '') %>
</p>
<br>
</a>
<% } %>
<% }) %>
</div>
PAGE WHERE USER SELECTS THEIR PREFERENCES OF CATEGORIES
they are basically radio button with YES / NO
<body>
<div>
<form method="PUT" id="update_user" action="/homepage">
<div class="form-group">
<h3> <label for="name" class="text-dark">preferences</label> </h3>
<input type="hidden" name="id" value="<%= id %>">
</div>
<div class="form-group">
<label for="alpha" class="text-dark">alpha</label>
<input type="radio" id="radio-2" name="alpha" value="yes" <%= alpha== 'yes' ? 'checked' : '' %>>
<label for="radio-2" class="radio-label">Yes</label>
<input type="radio" id="radio-3" name="alpha" value="no" <%= alpha== 'no' ? 'checked' : '' %> >
<label for="radio-3" class="radio-label">No</label>
</div>
<div class="form-group">
<label for="beta" class="text-dark">beta</label>
<input type="radio" id="radio-2" name="beta" value="yes" <%= beta== 'yes' ? 'checked' : '' %>>
<label for="radio-2" class="radio-label">Yes</label>
<input type="radio" id="radio-3" name="beta" value="no" <%= beta== 'no' ? 'checked' : '' %> >
<label for="radio-3" class="radio-label">No</label>
</div>
<div class="form-group">
<label for="gamma" class="text-dark">gamma</label>
<input type="radio" id="radio-2" name="gamma" value="yes" <%= gamma== 'yes' ? 'checked' : '' %>>
<label for="radio-2" class="radio-label">Yes</label>
<input type="radio" id="radio-3" name="gamma" value="no" <%= gamma== 'no' ? 'checked' : '' %> >
<label for="radio-3" class="radio-label">No</label>
</div>
<div class="form-group">
<label for="theta" class="text-dark">theta</label>
<input type="radio" id="radio-2" name="theta" value="yes" <%= theta== 'yes' ? 'checked' : '' %>>
<label for="radio-2" class="radio-label">Yes</label>
<input type="radio" id="radio-3" name="theta" value="no" <%= theta== 'no' ? 'checked' : '' %> >
<label for="radio-3" class="radio-label">No</label>
</div>
So to summarise, the objective is user selects categories, one or few or all from preferences.
Based on each preference there are some news articles linked in external API
therefore I need to bring all the news articles for the preferences marked as YES, consolidate the response and send to UI for display.
Can you guys help me? Please let me know!

cannot read properties of undefined(reading"name")

I trying to make a survey website and I have been stuck on this bug for hours. I have a from that has 5 inputs and it takes name, question and 4 options as text and submits them. when clicking on submit button the server recieves a post method with the action /all after getting /all the server should render all.ejs. below is my index.js file:
router.post('/all', function (req, res) {
const newsurvey=new survey({
"name":req.body.name,
"question":req.body.question,
"option1":req.body.option1,
"option2": req.body.option2,
"option3":req.body.option3,
"option4": req.body.option4,
})
survey.create(newsurvey)
console.log(newsurvey)
console.log(req.body.name)
res.render('all', { title: 'All Surveys', survey});
});
// initializing a new survey object
router.get('/addsurvey', function (req, res, next) {
survey.find((err, list)=>{
const newsurvey = new survey({
"name":"",
"question":"",
"option1":"",
"option2":"",
"option3":"",
"option4":""
}
)}
,res.render('surdetails', { title: 'Details', survey})
);
});
router.get('/all', function (req, res) {
survey.find((err, list)=>{
if (err){
return console.error(err);
}else{
res.render('all', { title: 'All Surveys', survey: survey });
}
})
});
and below is my all.ejs file which returns cannot read properties of undefined(reading"name"):
<tbody>
<!-- Template Row -->
<% for (let count = 0; count < survey.length; count++) { %>
<tr>
<td><%= survey[count].name %></td>
<td class="text-center"><%= survey[count].name %></td>
<td class="text-center"><%= survey[count].question %></td>
<td class="text-center">
<input type="radio" id="option1" name="option1" value="<%= survey[count].option1 %>">
<label for="option1"><%= survey[count].option1 %></label><br>
<input type="radio" id="option2" name="option2" value="<%= survey[count].option2 %>">
<label for="option2"><%= survey[count].option2 %></label><br>
<input type="radio" id="option3" name="option3" value="<%= survey[count].option3 %>">
<label for="option3"><%= survey[count].option3 %></label><br><br>
</td>
<td class="text-center">
<i class="fa fa-trash-o"></i> Delete
</td>
</tr>
<% } %>
</tbody>

Request variable from forEach loop jQuery

I am trying to make a multiple choice questionnaire in node. I have a forEach loop printing the form for the questions and answer fields. Problem is that I can not get the correct variable in my jQuery file where I am doing the comparison.
Using a forEach loop in an EJS and checking it in a jQuery file.
jQuery File:
$(document).ready(function(){
$('.bcheck').click(function(){
var on = 1;
var ans = $(this).attr('realanswer');
var theirAns = $("input[placeholder=Answer]").val();
console.log(ans);
if(ans == theirAns){
//DO SOMETHING
}
});
});
The value for var theirAns = $("input[placeholder=Answer]").val(); stays the first element in the iteration. Could I use the this function to get value of something that is not an element of the item I am clicking?
HTML for the EJS file:
<% topic.questions.forEach(function(question){ %>
<% if(question.difficulty == 10){ %>
<form action="/lesson/<%= lesson._id %>/topic/<%= topic._id %>/course/<%= question._id %>/quest?_method=PUT" method="POST">
<div class="quest_info questionf">
<%= question.question %>?
<div class="text_input">
<input type="hidden" name="res[_id]" value="<%= question._id %>">
<input type="hidden" name="realAnswer" value="<%= question.answer %>">
<input id="correct" type="hidden" name="res[correct]" value="<%= false %>">
<% if(question.question_type == "multiple"){ %>
<% var ran = ranNumber(0, 3) %>
<% var n = 0; %>
<% question.wrong_answers.forEach(function(wAns){ %>
<div class="bw btn btn-success" value="<%= wAns %>"> <%= wAns %> </div>
<% if(ran == n){ %>
<div class="ba btn btn-success "><%= question.answer %></div>
<% }; %>
<% n += 1; %>
<% }); %>
<input type="hidden" name="res[answer]" value="<%= question.answer %>" placeholder="Answer">
<% }else{%>
<input type="text" name="res[answer]" placeholder="Answer" >
</input>
</div>
<% }; %>
<div class="text_input">
<div class="bcheck btn btn-primary pull-right" realanswer="<%= question.answer %>" >Check Answer</div>
</div>
<% x += 1 %>
<div class="text_input">
</div>
</div>
<% }; %>
<% }); %>
You're trying to use $("input[placeholder=Answer]").val() - it will return the first value indeed.
If you want to check every element matching a selector $("input[placeholder=Answer]").each() will help. Here is an example based on your code snippet.
$(document).ready(function() {
$('.bcheck').click(function() {
var ans = $(this).data('realanswer');
$("input[placeholder=Answer]").each(function() {
var theirAns = Number($(this).val());
if (ans === theirAns) {
console.log('Nice');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="bcheck" data-realanswer="42">check</button>
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">

Form ajax data on jsp example

I would like to form data parameter correctly inside ajax call.
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: <<< my data here >>>
});
});
});
</script>
This is part of my jsp:
<form action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>
I would like to pass everything that normally passes by form above.
Could you please show me around ajax technology by this example?
Give an instance id to the form and use with the serialize() method
$('#form').submit(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: $(this).serialize()
});
});
<form id="form" action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>

Populate values in a textbox from the database using servlets and ajax

I have the following data in the database. I want to populate my text fields by populating this data using servlets and ajax.
data_id ------------------------ char(30)
Lat --------------------------double precision
Long ------------------------- double precision
Info.class
package org.bean
public class Info {
private String data_id;
private String lat;
private String long;
public void setData_id(String data_id) {
this.data_id = data_id;
}
public String getData_id() {
return data_id;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLat() {
return lat;
}
public void setLong(String long) {
this.long = long;
}
public String getLong() {
return long;
}
}
FetchData.class
public class FetchData {
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream =
FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Info> getAllInfo() {
connection = FetchData.getConnection();
ArrayList<Info> inf = new ArrayList<Info>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from info_table");
while(rs.next()) {
Info in=new Info();
in.setData_id(rs.getString("data_id"));
in.setLat(rs.getString("Lat"));
in.setLong(rs.getString("Long"));
inf.add(in);
}
} catch (SQLException e) {
e.printStackTrace();
}
return inf;
}
}
PopulateTable.class
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;
public PopulateTable() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Info> in=new ArrayList<Info>();
in=FetchData.getAllInfo();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(in, new TypeToken<List<Info>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
index.jsp
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.get('PopulateTable',function(responseJson) {
if(responseJson!=null){
$("#infotable").find("tr:gt(0)").remove();
var table1 = $("#infotable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['data_id']);
rowNew.children().eq(1).text(value['lat']);
rowNew.children().eq(2).text(value['long']);
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
</script>
</head>
<input type="button" value="Show Table" id="showTable"/>
<br/>
<br/>
<div id="tablediv">
<table cellspacing="0" id="infotable">
<tr>
<th scope="col">Data_id</th>
<th scope="col">Latitude</th>
<th scope="col">Longitude</th>
</tr>
</table>
</div>
</body>
</html>
I am basically populating the database data in a table using servlets and ajax on a jsp page without refreshing the page. I want the same action to be taken. Instead of onclick of a button I want the user to enter data_id and onkeyup event of that textfield Latitude and longitude values to be populated from the database. how do i do this.
If i change the jsp page to
<input type="text" id="data_id" onblur=""/>
<input type="text" id="latitude"/>
<input type="text" id="longitude"/>
then onblur event should populate my textfields having id latitude and longitude with the data corresponding to the typed id. How do i do this?
Instead of putting your Ajax call inside $(document).ready(function() {...}); put it in a function with a name and have your onblur call it:
function populatefields()
{
... //Ajax stuff
}
...
...
<input type="text" id="data_id" onblur="populatefields()" />
<%#page import="java.util.logging.Logger"%>
<%#page import="java.util.logging.Level"%>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.swing.JFrame"%>
<%#page import="javax.swing.JButton"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Student view</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script>
function selectItem()
{
var sel=document.getSelection("drop").value;
var c=document.getElementById("drop").value;
var xmlhttp,url;
if(c=="hand")
url="StudentView_2.jsp";
else
url="StudentView.jsp";
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200)
{
document.getElementById("message1").innerHTML = xmlhttp.responseText;
}
else
{
alert('Something is wrong !!');
}
}
}
}
</script>
</head>
<body>
<div id="topPan"> <!--<img src="" alt="Education Zone" width="245" height="37" border="0" class="logo" title="Education Zone"/>-->
<h1> <p>Library Manager</p></h1>
<div id="topContactPan"> </div>
<div id="topMenuPan">
<div id="topMenuLeftPan"></div>
<div id="topMenuMiddlePan">
<ul>
<li class="home">Home</li>
<li>Logout</li>
<!-- <li class="contact">Contact</li>-->
</ul>
</div>
<div id="topMenuRightPan"></div>
</div>
</div>
<div id="bodyPan">
<div id="bodyLeftPan">
<h2><span>Student View</span> </h2>
<!-- <p>Education Zone is a free, tableless, W3C-compliant web design layout by <span>Template World</span>. This template has been tested and proven compatible with all major browser environments and operating systems. You are free to modify the design to suit your tastes in any way you like.</p>
<p>We only ask you to not remove "Design by Template World" and the link <span>http://www.templateworld.com</span> from the footer of the template.</p>
<p>If you are interested in seeing more of our free web template designs feel free to visit our website, Template World. We intend to add at least 25 new <span>free templates</span> in the coming month.</p>
-->
<!-- <form action="StudentView_1.jsp">
<input type="submit" value="View All Books" >
</form>
<form action="StudentView_2.jsp">
<input type="submit" value="In Hand" >
</form> -->
<form >
<select name="drop" id="drop" onchange="selectItem()">
<option value="view" >View All</option>
<option value="hand">In Hand</option>
</select>
<!--<input type="" value="In Hand" >-->
</form>
<%
// try{
// // TODO add your handling code here:
// String [] colname={"Book Id","Book Name","Book Author"};
// Class.forName("com.mysql.jdbc.Driver");
// Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","mysql");
// Statement st=conn.createStatement();
// System.out.println("success");
// String sql1="select * from book where Available='1'";
// ResultSet rs=st.executeQuery(sql1);
// int n=0,i=0;
// while(rs.next())
// {
// n++;
// }
// rs.beforeFirst();
// Object [][] o=new Object[n][3];
// out.println("<table border=1>");
// out.println("<tr><td>Book Id</td><td>Book Name</td><td>Book Author</td></tr>");
//
// while(rs.next())
// {
// o[i][0]=rs.getString(1);
// o[i][1]=rs.getString(2);
// o[i][2]=rs.getString(3);
// out.println("<tr><td>"+o[i][0]+"</td><td>"+o[i][1]+"</td><td>"+o[i][2]+"</td></tr>");
// i++;
// }
// out.println("</table>");
//
// }catch(Exception ee)
// {
//
// }
// Object ss=request.getParameter("xx");
//System.out.println(ss);
// session.setAttribute("pp",ss );
%>
</div>
<form>
</form>
<div id="message1" class="aaa">
<%# page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%# page import="java.sql.PreparedStatement" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%!
public int Converter(String str)
{
int convrtr=0;
if(str==null)
{
str="0";
}
else if((str.trim()).equals("null"))
{
str="0";
}
else if(str.equals(""))
{
str="0";
}
try{
convrtr=Integer.parseInt(str);
}
catch(Exception e)
{
}
return convrtr;
}
%>
<%
Connection con = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root", "mysql");
ResultSet rsPgin = null;
ResultSet rsRwCn = null;
PreparedStatement psPgintn=null;
PreparedStatement psRwCn=null;
// Number of records displayed on each page
int iSwRws=4;
// Number of pages index displayed
int iTotSrhRcrds=10;
int iTotRslts=Converter(request.getParameter("iTotRslts"));
int iTotPags=Converter(request.getParameter("iTotPags"));
int iPagNo=Converter(request.getParameter("iPagNo"));
int cPagNo=Converter(request.getParameter("cPagNo"));
int iStRsNo=0;
int iEnRsNo=0;
if(iPagNo==0)
{
iPagNo=0;
}
else{
iPagNo=Math.abs((iPagNo-1)*iSwRws);
}
String sqlPgintn="SELECT SQL_CALC_FOUND_ROWS * FROM book limit "+iPagNo+","+iSwRws+"";
psPgintn=con.prepareStatement(sqlPgintn);
rsPgin=psPgintn.executeQuery();
// Count total number of fetched rows
String sqlRwCnt="SELECT FOUND_ROWS() as cnt";
psRwCn=con.prepareStatement(sqlRwCnt);
rsRwCn=psRwCn.executeQuery();
if(rsRwCn.next())
{
iTotRslts=rsRwCn.getInt("cnt");
}
%>
<html>
<head>
<title>Pagination using JSP page</title>
</head>
<body>
<form name="frm">
<input type="hidden" name="iPagNo" value="<%=iPagNo%>">
<input type="hidden" name="cPagNo" value="<%=cPagNo%>">
<input type="hidden" name="iSwRws" value="<%=iSwRws%>">
<table cellpadding="0" cellspacing="0" border="1" >
<tr>
<td>BookId</td>
<td>BookName</td>
<td>BookAuthor</td>
</tr>
<%
while(rsPgin.next())
{
%>
<tr>
<td><%=rsPgin.getString(1)%></td>
<td><%=rsPgin.getString(2)%></td>
<td><%=rsPgin.getString(3)%></td>
<td><a href="www.google.com>view </a></td>
</tr>
<%
}
%>
<%
// Calculate next record start and end position
try{
if(iTotRslts<(iPagNo+iSwRws))
{
iEnRsNo=iTotRslts;
}
else
{
iEnRsNo=(iPagNo+iSwRws);
}
iStRsNo=(iPagNo+1);
iTotPags=((int)(Math.ceil((double)iTotRslts/iSwRws)));
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<tr>
<td colspan="3">
<div>
<%
// Create index of pages
int i=0;
int cPge=0;
if(iTotRslts!=0)
{
cPge=((int)(Math.ceil((double)iEnRsNo/(iTotSrhRcrds*iSwRws))));
int prePageNo=(cPge*iTotSrhRcrds)-((iTotSrhRcrds-1)+iTotSrhRcrds);
if((cPge*iTotSrhRcrds)-(iTotSrhRcrds)>0)
{
%>
<< Previous
<%
}
for(i=((cPge*iTotSrhRcrds)-(iTotSrhRcrds-1));i<=(cPge*iTotSrhRcrds);i++)
{
if(i==((iPagNo/iSwRws)+1))
{
%>
<b><%=i%></b>
<%
}
else if(i<=iTotPags)
{
%>
<%=i%>
<%
}
}
if(iTotPags>iTotSrhRcrds&& i<iTotPags)
{
%>
>> Next
<%
}
}
%>
<b>Rows <%=iStRsNo%> - <%=iEnRsNo%> Total Result <%=iTotRslts%></b>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<%
try{
if(psPgintn!=null){
psPgintn.close();
}
if(rsPgin!=null){
rsPgin.close();
}
if(psRwCn!=null){
psRwCn.close();
}
if(rsRwCn!=null){
rsRwCn.close();
}
if(con!=null){
con.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</div>
<!--<table id="message1" align="left" width="200" border="1" class="aaa">
</table>-->
<!--<form>
<select name="message1" id="message1">
</select>
</form>-->
<div id="bodyRightPan1">
</div>
</div>
<div id="footermainPan">
<div id="footerPan">
<ul>
<li>Home| </li>
<li>Registration| </li>
</ul>
<p class="copyright">©education zone. All right reserved.</p>
<ul class="templateworld">
<li>design by:</li>
<li>Template World</li>
</ul>
<div id="footerPanhtml">HTML</div>
<div id="footerPancss">css</div>
</div>
</div>
</body>
</html>

Categories