From what I can see when the checkbox page passes of parameters to the Proto page, which puts it in the portfolio object which is then used to check the value of the data and display the portfolio name ,and when the proto page refreshes the parameters arent passed again from the checkbox page and the portfolio object has a null value stored in it which gives a null pointer exception.
so if I store the parameter values once they're already passed from the checkbox page would that solve the problem ? And if so how can I go about it ?
Here is the code for proto page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="oracle.jdbc.pool.OracleDataSource"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>
<title>Live Data Tracking</title>
<style type='text/css'>
.wrapper {
margin: 0px auto;
width: 1379px;
background-color: #cccccc
}
.header {
float: left;
width: 100%;
background-color: #356aa0
}
.left1 {
float: left;
margin-right: 10px;
width: 338px;
background-color: #ffffff
}
.left2 {
float: left;
margin-right: 10px;
width: 337px;
background-color: #ffffff
}
.left3 {
float: left;
margin-right: 10px;
width: 337px;
background-color: #ffffff
}
.right {
float: right;
width: 337px;
background-color: #ffffff
}
.footer {
float: left;
width: 100%;
background-color: #00457b
}
body {
padding: 0px;
margin: 0px;
font-size: 90%;
background-color: #e7e7de
}
</style>
</head>
<script type="text/javascript">
<%
ArrayList<ArrayList<String>> testList = new ArrayList();
portfolio = request.getParameterValues("portfolio");
try{
OracleDataSource ds= new OracleDataSource();
//javax.sql.DataSource ds = new javax.sql.DataSource();
ds.setDriverType("thin");
ds.setServerName("localhost");
ds.setPortNumber(1521);
ds.setDatabaseName("orcl");
ds.setUser("system");
ds.setPassword("amex1234");
Connection connection = ds.getConnection();
System.out.println("Connected Successfully");
Statement statement = connection.createStatement() ;
if (portfolio!=null)
{
for(int i=0;i<portfolio.length;i++)
testList.add(new ArrayList());
//System.out.println(testList);
for(int i=0; i<portfolio.length;i++)
{ String temp="";
ResultSet resultset = statement.executeQuery("select num FROM "+portfolio[i]+"_Test") ; //Put in SQl command and Table name here
while(resultset.next()){
temp = resultset.getString(1);
testList.get(i).add(temp);
}
//System.out.println(testList);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
%>
</script>
<body>
<%! String[] portfolio; %>
<div class="wrapper">
<div class="header">
<center>
<h4>Live Tracker</h4>
</center>
</div>
<div class="left1">
<h3>Portfolio</h3>
<%
if (portfolio != null)
{
for (int i = 0; i < portfolio.length; i++) //i=portfolio length proxy
{
out.println ("<b>"+portfolio[i]+"<b>"); %>
<br>
<% }
}
else out.println ("<b>none<b>");
%>
</div>
<div class="left2">
<h3>Pre-Stage</h3>
for (int j = 0; j < portfolio.length; j++)
{
response.setIntHeader("Refresh", 2);
//System.out.println(testList.get(j).size());
if (testList.get(j).size()!=0){ %>
Data is there <br>
<% } else { %>
No data <br>
<% }
}%>
</div>
<div class="left3">
<h3>Stage</h3>
</div>
<div class="right">
<h3>Mirror</h3>
</div>
<div class="footer">Something Funny and Witty Here</div>
</div>
</body>
</HTML>
This is the code for the checkbox page. Run via this page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<body>
<FORM method="POST" ACTION="Proto_1.jsp">
<center>
Select your portfolio(s): <br><br>
<table>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=X>
</td>
<td>
X
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=Y>
</td>
<td>
Y
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=W>
</td>
<td>
W
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=V>
</td>
<td>
V
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=S>
</td>
<td>
S
</td>
</tr>
</table>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</center>
</FORM>
</BODY>
</HTML>
There are several options to resolve.
Option 1: Set the params into session. Instead of:
portfolio = request.getParameterValues("portfolio");
Try this:
String[] portfolio = null;
if(null == request.getParameter("submit")) { //page reload, true
portfolio = (String[])session.getAttribute("portfolio");
} else {
portfolio = request.getParameterValues("portfolio");
session.setAttribute("portfolio", portfolio);
}
Option 2: Separate the view and business logic i.e. split your page into two. First jsp to get the portfolio from request and make frequent call to get the updated records from the second jsp. This approach requires JavaScript.
View.jsp: Make call to the Records.jsp frequently using setInterval()
<script>
var getRecords = function() {
// to do here
};
setInterval(getRecords, 2 * 1000); (in miliseconds)[every 2 sec]
</script>
Records.jsp: Generate dynamic html along with records
You can save the checkbox data to the session via session.setAttribute("portfolio", portfolio).
You can retrieve this and set the value back to the page via document.getElementById(id).value or via value={$sessionVariable} in jsp
Related
I am trying to create a shopping cart using cookies in spring boot but the cookie is not being added/displayed. Below are the controller mappings and page htmls, can you let me know what I'm doing wrong?
Screenshots of pages :
Controller Mappings:
#GetMapping("/products/addToCart/{id}")
private String addToCart(#PathVariable("id") long productId, HttpServletResponse response) {
try {
Cookie browserSessionCookie = new Cookie(Long.toString(productId), Long.toString(1L));
response.addCookie(browserSessionCookie);
return "redirect:/products/cart";
} catch (Exception e) {
logger.error(e.getMessage());
return "fail";
}
}
#GetMapping("/products/cart")
public String showCookies(HttpServletRequest request, Model model) {
Cookie[] cookies = request.getCookies();
model.addAttribute("cookies",cookies);
return "/cart";
}
Thymeleaf Page For Products List:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>All Products</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
table, th, td {
border: 1px solid black;
}
td {
padding: 20px;
}
.topnav {
background-color: #A32638;
overflow: hidden;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #FCB514;
color: white;
}
</style>
</head>
<body>
<div class="topnav">
<a th:href="#{/}">Home</a>
<a class="active" th:href="#{/productsList}">Products</a>
<a th:href="#{/products/cart}">Cart</a>
</div>
<br>
Products
<br>
<br>
<div th:if="${ not#lists.isEmpty(products)}">
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Action</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.category.name}"></td>
<td>
<a th:href="#{/products/details/{id}(id=${product.id})}">Details</a>
<a th:href="#{/products/addToCart/{id}(id=${product.id})}">Add To Cart</a>
</td>
</tr>
</table>
<br>
</div>
</body>
</html>
Thmeleaf Page For Showing Cookies :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br>
<h1>Show cookies</h1>
<dl th:each="cookie : ${cookies}">
<dt th:text="${cookie.getName()}"></dt>
<dd th:text="${cookie.getValue()}"></dd>
</dl>
<h1>Session Data</h1>
<dl th:each="elem : ${sessionElems}">
<dt th:text="${elem.getName()}"></dt>
<dd th:text="${elem.getValue()}"></dd>
</dl>
</body>
</html>
Thank you.
The solution was to set the path of the created cookie to the path of the cart page as below :
browserSessionCookie.setPath("/products/cart");
Thanks for the responses!
I'm trying to code a dynamic web project into Eclipse, but the tag img in the jsp page don't work. This is my project:
ProjectName
--WebContent
--WEB-INF
--images
page.jsp
And this is my jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="Beans.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>HomePageImpiegato</title>
<style>
body{color: #333;font-family: 'Muli', sans-serif;background-color: #F5F5F5;}
h1{font-family: 'Open Sans Condensed', sans-serif;font-size: 30px;color: #333;width: fit-content;margin-left: auto;margin-right: auto;}
h4{font-family: 'Open Sans Condensed', sans-serif;font-size: 20px;color: #333;width: fit-content;margin-left: auto;margin-right: auto;}
.preventivi{height: fit-content;display: flex;width: 100%;}
.preventiviGestiti{float: left;margin-left: auto;margin-right: auto;width: 48%;}
.preventiviLiberi{float: right;margin-right: auto;margin-left: auto;width: 48%;}
.dati-personali{margin: auto;width: fit-content;}
.gestisciPreventivo{margin-left: auto;margin-right: auto;width: fit-content;margin-top: 50px;}
#preventivi {font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;border-collapse: collapse;width: 100%;}
#preventivi td, #preventivi th {border: 1px solid #ddd;padding: 8px;}
#preventivi tr:nth-child(even){background-color: #f2f2f2;}
#preventivi tr:hover {background-color: #ddd;}
#preventivi th {padding-top: 12px;padding-bottom: 12px;text-align: left;background-color: #4CAF50;color: white;}
</style>
</head>
<body>
<div class="contenuto">
<h1>Home Page Impiegatodiv</h1>
<%
Utente utente = (Utente) session.getAttribute("utente");
if (utente==null) {
response.sendRedirect(getServletContext().getContextPath() + "/LoginPage.html");
}
else {
if (utente.getTipo().equals("cliente")) {
response.sendRedirect(getServletContext().getContextPath() + "/LoginPage.html");
}
else {
%><div class="dati-personali"><%
out.println("Ciao " + utente.getTipo() + " " + utente.getNome());
out.println(" Con password " + utente.getPass());
%></div><%
Preventivo[] preventivi = (Preventivo[]) session.getAttribute("preventiviU");
Preventivo[] preventiviNull = (Preventivo[]) session.getAttribute("preventiviN");
%><div class="preventivi">
<div class="preventiviGestiti">
<h4>Preventivi gestiti in passato</h4>
<%
if (preventivi==null) {
out.println("Nessun preventivo");
}
else {
for (int i=0; i<preventivi.length; i++) {
%>
<table id="preventivi">
<tr>
<th><img src="<%= request.getContextPath()%>/WEB-INF/images/<%= preventivi[i].getImg() %>"></th>
<th><% out.println(preventivi[i].getId()); %></th>
<th><% out.println(preventivi[i].getCliente()); %></th>
<th><% out.println(preventivi[i].getImpiegato()); %></th>
<th><% out.println(preventivi[i].getPrezzo()); %></th>
<th><% out.println(preventivi[i].getNomeProdotto()); %></th>
</tr>
<%
Opzione[] opzioni = preventivi[i].getOpzioni();
for (int j=0; j<opzioni.length; j++) {%>
<tr>
<th><% out.println(opzioni[j].getNome()); %></th>
<th><% out.println(opzioni[j].getTipo()); %></th>
</tr>
<%
}
%></table><%
}
%></div><%
}
%><div class="preventiviLiberi">
<h4>Preventivi da gestire</h4>
<%
for (int i=0; i<preventiviNull.length; i++) {
%><table id="preventivi">
<tr>
<th><img src="<%= request.getContextPath()%>/WEB-INF/images/<%= preventiviNull[i].getImg() %>" height="42" width="42"></th>
<th><% out.println(preventiviNull[i].getId()); %></th>
<th><% out.println(preventiviNull[i].getCliente()); %></th>
<th><% out.println(preventiviNull[i].getImpiegato()); %></th>
<th><% out.println(preventiviNull[i].getPrezzo()); %></th>
<th><% out.println(preventiviNull[i].getNomeProdotto()); %></th>
</tr>
<%
Opzione[] opzioni = preventiviNull[i].getOpzioni();
for (int j=0; j<opzioni.length; j++) {%>
<tr>
<th><% out.println(opzioni[j].getNome()); %></th>
<th><% out.println(opzioni[j].getTipo()); %></th>
</tr>
<%
}
%></table><%
}
%></div><%
%></div>
<div class="gestisciPreventivo">
<h4>Gestisci preventivo</h4>
<form action="gestisci" method="POST">
<select id="idPreventivoNew" name="idPreventivoNew">
<%
for (int i=0; i<preventiviNull.length; i++) {
%> <option value="<%= preventiviNull[i].getId() %>"> <%= preventiviNull[i].getId() %> </option> <%
}%>
</select>
<label>Scegli preventivo</label>
<input type="hidden" id="impiegato" name="impiegato" value="<%= utente.getNome() %>">
<input type="submit" value="PREZZA PREVENTIVO">
</form>
</div>
</div>
<%
}
}
%>
</body>
I also try to pass the absolute path but work only in Eclipse and not in the browser.
I also try to change my browser but i can't get any result.
Thanks
I want to retrieve the parameters sent through the form login.jsp in the controller..but I am getting the error-"Request parameter is not present". My code for login.jsp is as follows:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Security</title>
</head>
<body>
<center>
<h1>Welcome to Spring Security Learning</h1>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<font color="red">
Your login attempt was not successful due to <br/><br/>
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
</font>
</c:if>
<div style="text-align: center; padding: 30px; border: 1px solid; width: 250px;">
<form method="post"
action='j_spring_security_check'>
<table>
<tr>
<td colspan="2" style="color: red">${message}</td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" name="j_username" id="uname"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password" /></td>
</tr>
<tr>
<td colspan="1"><input type="submit" value="Login" /></td>
<td colspan="1"><input name="reset" type="reset" /></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
The code for controller is as follows:-
#RequestMapping("/search")
public ModelAndView search(HttpSession session2,#RequestParam("j_username") String name) {
session2.setAttribute("name", name);
Session session=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
String hql = "SELECT E.firstName FROM User E";
Query query = session.createQuery(hql);
List results = query.list();
//System.out.println(results.get(1).getClass().getFields());
HashMap model = new HashMap();
model.put("users", results);
return new ModelAndView("search", model);
}
Please help..thanx in advance..
I have been searching around for reason why I have error Neither BindingResult nor plain target object for bean name 'addItemForm' available as request attribute but can't understand.
The page is loading fine but if I click on Add new item button, a lightbox containing a form appears, I click on Add item and I got same error as above but bean name is searchForm.
The controller looks fine, I think there is a binding problem between the view and the form. Can someone explain please?
Also, it is able to add new items to database, so the POST method is working, but the view returns errors ..
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=ISO-8859-1">
<title>Admin View</title>
<style type="text/css">
body{margin:0, padding:0}
#body{
text-align: center;
top: 3%;
}
.table2{
border-spacing: 5%;
}
.table1 {
border-collapse: collapse;
width: 80%;
}
.table1 tr:nth-child(odd) td{
background-color: #ffffff;
}
.table1 tr:nth-child(even) td{
background-color: #4da6ff;
}
.table1 td, th {
text-align: left;
border: 1px solid green;
}
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="body">
<h3>This is the Administrator View</h3>
<p>From here, you can search for items in the database, view, add new items and delete items from database</p>
<table align="center">
<tr>
<td>
<form:form action="AdminView" method="POST" commandName="searchForm">
<form:input path="KeyWordSearch" size="40"/>
<input type="submit" name="search" value="Search Store"/>
</form:form>
</td>
<td><button onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Add new item</button></td>
</tr>
</table>
<br>
<c:if test="${not empty itemList}">
<table class="table1" align="center">
<tr>
<th>Item Name</th>
<th>Date added</th>
<th>Item Description</th>
<th>View Details</th>
</tr>
<c:forEach var="item" items="${itemList}">
<tr>
<td>${item.itemName}</td>
<td>${item.itemAdded}</td>
<td>${item.itemDescription}</td>
<td>View</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<div id="light" class="white_content">
<h2 align="center">Add new item to Store</h2>
<form:form action="AdminView" method="POST" commandName="addItemForm">
<table align="left">
<tr>
<th style="border:0">Item name</th>
<td><form:input path="ItemName"/></td>
</tr>
<tr>
<th style="border:0">Item location</th>
<td><form:input path="ItemLocation"/></td>
</tr>
<tr>
<th style="border:0">Item Description</th>
<td><form:textarea path="ItemDescription"/></td>
</tr>
<tr>
<td><input type="submit" name="add" value="Add Item"/></td>
</tr>
</table>
</form:form>
Close
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html
This is the Controller:
package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.test.forms.AddNewItemForm;
import com.test.forms.SearchForm;
import com.test.models.items.ItemIF;
import com.test.transaction.TransactionFactory;
/**
* Handles requests for Admin View page
* #author Trung
*
*/
#Controller
#RequestMapping (value = "/AdminView")
public class AdminViewController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView adminForm(Model model){
SearchForm searchForm = new SearchForm();
model.addAttribute("searchForm", searchForm);
AddNewItemForm addItemForm = new AddNewItemForm();
model.addAttribute("addItemForm", addItemForm);
return new ModelAndView("AdminView");
}
#RequestMapping (params = "search", method = RequestMethod.POST)
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, Model model){
List<ItemIF> relatedItems = null;
TransactionFactory transaction = new TransactionFactory();
relatedItems = transaction.retrieveItemByName(searchForm.getKeyWordSearch());
if (relatedItems.isEmpty()){
System.out.println("okay, there isn't any item that is matched your criteria");
} else {
model.addAttribute("itemList", relatedItems);
}
return "AdminView";
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView addNewItemForm(#ModelAttribute("addItemForm") AddNewItemForm addItemForm){
TransactionFactory transaction = new TransactionFactory();
String itemName = addItemForm.getItemName();
String itemLocation = addItemForm.getItemLocation();
String itemDescription = addItemForm.getItemDescription();
transaction.insertItem(itemName, itemLocation, itemDescription);
return new ModelAndView("AdminView");
}
}
You need a BindingResult as parameter in both post methods after the #ModelAttribute parameter, like this:
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, BindingResult result, Model model){
i have a page editpatient.jsp which includes a page patientlist.jsp. when you run editpatient.jsp then it displays all the records present in the database.I have a dropdown and also a search field to specify searches. So when i run editpatient.jsp then it displays all the records in the manner it is stored in DB. So i wanted to sort it according to name and display.So please tell me how to do the same. when you hit the name or email or city then it will sort accordingly
patientlist.jsp
<%# page import="java.util.*" %>
<%# page import="java.sql.*" %>
<%# page import="DB.*" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.evenRow{
height: 50px;
background-color: white;
text-transform: none;
text-shadow: none;
color: black;
}
.evenRow:hover
{
background-color: #C2FEF0;
}
.row{
height: 50px;
background-color: #E4E6E6;
text-transform: none;
text-shadow: none;
color: black;
}
.row:hover {
background-color: #C2FEF0;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<table style="border-collapse: collapse;overflow-x: scroll; width:97%">
<tr style="background-color:grey;height:50px">
<th style="min-width: 100px">
NAME
</th>
<th style="min-width: 100px">
CITY
</th>
<th style="min-width: 100px">
LAST VISIT
</th>
<th style="min-width: 100px">
MOBILE
</th>
<th style="min-width: 100px">
EMAIL
</th>
<th style="min-width: 100px">
STATUS
</th>
<th style="min-width: 100px">
VIEW
</th>
<th style="min-width: 100px">
EDIT
</th>
</tr>
<%
DataBaseConnection db = new DataBaseConnection();
Connection con = db.connet();
PreparedStatement pt = con
.prepareStatement("select * from Patient");
ResultSet rs = pt.executeQuery();
String searchBy = request.getParameter("searchBy");
String searchElement = request.getParameter("searchElement");
int count = 0;
int index = -1;
boolean name = false;
if ("city".equalsIgnoreCase(searchBy))
index = 9;//change the index to the index of the city
else if ("firstName".equalsIgnoreCase(searchBy))
index = 1;
else if ("lastName".equalsIgnoreCase(searchBy))
index = 2;
else if ("name".equalsIgnoreCase(searchBy)) {
index = 1;
name = true;
}
while (rs.next()) {
if (searchElement == null
|| ((searchElement.equals(rs.getString(index)) && !name) || (name && searchElement
.equalsIgnoreCase(rs.getString(index) + " "
+ rs.getString(index + 1))))) {
if (count++ % 2 == 0) {
%>
<tr class="evenRow" >
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<form action="getPatientDetails.jsp"><input type="hidden" name="hidden" value="<%=count%>"/><input type="submit" value="view"></form>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
} else {
%>
<tr class="row">
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<a onclick="renderView(<%out.println("view");%>)"><%
out.println("view");
%></a>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
}
}
}
%>
</table>
</body>
</html>
editpatient.jsp
<%# page import="java.util.*" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script type="text/javascript">
var request;
function getRequestObject()
{
if (window.ActiveXObject)
{
return(new ActiveXObject("Microsoft.XMLHTTP"));
}
else if (window.XMLHttpRequest)
{
return(new XMLHttpRequest());
}
else {
return(null);
}
}
function sendRequest()
{
request = getRequestObject();
request.onreadystatechange = handleResponse;
var address = "patientList.jsp?searchBy=" + document.getElementById("searchBy").value + "&searchElement="+ document.getElementById("searchElement").value;
request.open("GET", address, true);
request.send(null);
}
function handleResponse()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("table").innerHTML = request.responseText;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Patient</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form id="f1" name="f1" method="post" onsubmit="ccheck();" >
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<section id="page" > <!-- Defining the #page section with the section tag -->
<header > <!-- Defining the header section of the page with the appropriate tag -->
<hgroup align="center">
<h3>Edit Patient</h3>
</hgroup>
</header>
<section id="articles"> <!-- A new section with the articles -->
<!-- Article 1 start -->
<div class="line"></div> <!-- Dividing line -->
<article id="article1"> <!-- The new article tag. The id is supplied so it can be scrolled into view. -->
<div class="articleBody clear">
search:
<select id="searchBy">
<option value="lastName">Last Name</option>
<option value="firstName">First Name</option>
<option value="name">Name</option>
<option value="city">City</option>
</select>
<input id="searchElement"/>
<input type="button" value="Search" onclick="sendRequest();"/>
</div>
</article>
<div id="table" align="center">
<jsp:include page="patientList.jsp" />
</div>
</article>
</section>
<footer> <!-- Marking the footer section -->
<div class="line"></div>
Go UP
</footer>
</section> <!-- Closing the #page section -->
<!-- JavaScript Includes -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"></script>
<script src="script.js"></script>
</form>
</body>
</html>
See if this links help you.
http://tympanus.net/codrops/2009/10/03/33-javascript-solutions-for-sorting-tables/
http://www.allmyscripts.com/Table_Sort/
Also let us know if you tried anything already
1.First store the dropdown /search value in Model class(using setter).
2.When you fired a query to fetch the details from database append the dropdown /search value which is stored in model class(using getter).
3.After fetch the value from DB render the dataTable .
Suggestion :
Please Follow the any one MVC architecture (Like Spring MVC architecture) to avoid the complexity of the your project.
Thanks you.
ASFAIK, The solution to your problem is ,you can use the jquery in jsp code, So you can find all Library's and include in it . There is no need to worry about sort and editing . Jquery has the Data Tables which has inbuilt API to sort the data in listed tables, its possible to edit the data in the table.
Reference Edit Reference Sort How to use data table in jsp pages
This is not exactly answers to question.
Try grid like jqGrid which takes care of things like sorting, searching, etc..