Searching in JSP - java

I have a Jsp page in which there is a table that is populated from the database. I want to Implement a search based on the fields on this table please tell me how to do this.
My Jsp page is given below
<html>
<jsp:include page="Headj.jsp"/>
<body>
<script type="text/javascript">
function deletedata(prdid) {
var url = "Con_Product?action=delete&prdid=" + prdid;
window.location = url;
}
function editdata(prdid) {
var url = "Editprd.jsp?prdid=" + prdid + "&type=p&pg=prd";
window.location = url;
}
</script>
<div id="maindiv" class="container-fluid">
<jsp:include page="Headerj.jsp"/>
<div id="menu_content">
<jsp:include page="Menuj.jsp"/>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">Product</h1>
<ul class="nav nav-tabs" role="tablist">
<li class="active">Display</li>
<li>Add New</li>
<!--<li><a href="#">Messages<a><li>-->
</ul>
<br>
<div class="panel panel-default">
<div class="panel-body" style="padding: 3px;">
<strong style="font-size: 20px; font-family: sans-serif; color: #3b6282; margin-left: 10px;">Display Products</strong>
<form class="navbar-right form-inline">
<div class="form-group">
<select class="form-control">
<option>Choose Option</option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search...">
</div>
</div>
<button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-search"></button>
</form>
</div>
</div>
<div class="alert-success"><p>${param.message}</p></div>
<%
general gen = new general();
Op_Product opp = new Op_Product();
Op_Category opc = new Op_Category();
ResultSet rs = opp.getallproducts();
%>
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<th><strong>Sl. No.</strong></th>
<th><strong>Product</strong></th>
<th><strong>Category</strong></th>
<th><strong>Sub-Category</strong></th>
<th><strong>Creator</strong></th>
<th><strong>Operations</strong></th>
</thead>
<%
int no = 1;
while (rs.next()) {
%>
<tr>
<td><%= no%></td>
<td><%= rs.getString("Prd_nme")%></td>
<td><%= opc.getOnecategoryname(rs.getString("Prd_catid"))%></td>
<td><%= opc.getOnesubcategoryname(rs.getString("Prd_scatid"))%></td>
<td><%= gen.getCreator(rs.getString("Prd_usr"))%></td>
<td>
<button type="button" class="btn btn-default btn-sm btn-danger" onclick="deletedata('<%= rs.getString("Prd_id")%>');">
<span class="glyphicon glyphicon-trash"></span>
</button>
<button type="button" class="btn btn-default btn-sm btn-primary" onclick="editdata('<%= rs.getString("Prd_id")%>')">
<span class="glyphicon glyphicon-edit"></span>
</button>
<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-eye-open"></span>
</button>
<button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-plus"></span>
</button>
</td>
</tr>
<%
no++;
}
%>
<tfoot>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<div>
<jsp:include page="Footerj.jsp"/>
</div>
<!-- Modal -->
<div class="modal " id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
ScreenShot of my page is given below.
The section the is circled is the search option the drop down list will have the field names and the search values will be entered in the text box.

To implement this you have 2 options:
The nice and slightly more complicated option
You can make an Ajax call using a JavaScript framework like jQuery to a servlet that will make the database query and respond to the ajax call via a Json object. This method will allow you to present the data without updating the page and the user experience will be better.
The easier option
You can submit that form to a servlet that makes the query and exposes the data as request attributes that are then presented in a jsp using jstl
Either way I recommend you to avoid scripting on the jsp files ( no <% %>) and instead use jstl and ${} to expose information. And do all the object creation and other login on servlets. That will make your code a lot easier and maintainable.

I did this operation using Jquery, this way there is no page reload and since it is in the client side it will be more faster. A sample of what i have done is given in
http://jsfiddle.net/9hGym/35/
The JQuery code is given below
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($("#table tbody").find("tr"), function() {
console.log($(this).text());
var s = $("#sss").val(); if($(this).find('td').eq(s).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
});
});

Related

NoSuchElementException - junit test error

I am using selenium junit testing.
If i try with selenium ide, the test goes well, but with junit it gives me this error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#firstName"}
I think that the span doesn't redirect to the page it should (but in normal schedule it does).
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
driver.findElement(By.linkText("Accesso amministratori")).click();
driver.findElement(By.id("username")).sendKeys("8245");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".btn")).click();
driver.findElement(By.id("btn_createDoc")).click();
driver.findElement(By.id("firstName")).click();
driver.findElement(By.id("firstName")).sendKeys("Marco");
driver.findElement(By.id("lastName")).click();
driver.findElement(By.id("lastName")).sendKeys("Battiato");
driver.findElement(By.id("doc_type")).click();
driver.findElement(By.id("doc_type")).sendKeys("Cardiologo");
driver.findElement(By.id("id")).click();
driver.findElement(By.id("id")).sendKeys("855555");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".glyphicon-send")).click();
}
I've tried with xpath, but without success...
HTML page with span redirection:
<body>
<div class="container text-center">
<div align="center">
<h2>Gestione dottori</h2>
<table class="table table-striped table-responsive-md">
<tr>
<th>ID</th>
<th>Nome</th>
<th>Specialit&agrave</th>
</tr>
<tr th:each="doc: ${listDoc}">
<td th:text="${doc.getId()}"></td>
<td>Dr. <span th:text="${doc.getFirstName()}"></span> <span th:text="${doc.getLastName()}"></span></td>
<td th:text="${doc.getDoc_type()}"></td>
</tr>
</table>
<a th:href = "#{/admin_createdoc}"><span id="btn_createDoc" class="plus bg-dark" >+</span></a>
<hr>
<div class="col col-lg-2 align-self-center">
<div class="p-1">
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</div>
</body>
Which redirect to this page:
<body>
<div class="container">
<div class="d-flex align-items-center justify-content-start">
<form th:action="#{/admin_homepage}" method=get>
<button name="btn_back_profile" id="btn_back_profile" type="submit"
class="btn btn-info">
<span class="fas fa-chevron-left"></span>
</button>
</form>
</div>
<br>
<div style='text-align: center'>
<form class="well form-horizontal" action="#"
th:action="#{/saveDoctor}" th:object="${doc}" method="POST"
id="contact_form">
<fieldset>
<!-- Form Name -->
<legend>
<center>
<h2>
<b>Doctor Creation Form</b>
</h2>
</center>
</legend>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">First Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="first_name"
th:field="*{firstName}" placeholder="Doc First Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="last_name"
th:field="*{lastName}" placeholder="Doc Last Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Type</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-list"></i></span> <input name="doc_type"
th:field="*{doc_type}" placeholder="Doc Type"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Id</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="id"
th:field="*{id}" placeholder="Doc ID" class="form-control"
type="number" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input
th:field="*{password}" name="doc_password"
placeholder="Doc Password" class="form-control" type="password"
required>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group" align="center">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<br>
<button type="submit" class="btn btn-warning">
SUBMIT <span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
<div>
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</body>
Thank you for your time!
The failure is happening on this line
driver.findElement(By.id("firstName")).click();
ID as a CSS selector is #firstName. Since this is right after a page transition, my guess is that the page isn't fully loaded before the next line of code is run. This can sometimes happen on a modern site where the page is loaded but there's still stuff being loaded asynchronously in the background. The fix is to add a wait, specifically a WebDriverWait, to the following line. That is one option...
Instead of adding a wait piecemeal when it's found that you need it, I prefer to write helper methods that take care of common actions like click(), sendKeys(), etc. and then let those methods take care of the specific waits for me.
public void click(By locator) {
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(locator)).click();
}
public void sendKeys(By locator, String text) {
findElement(locator).sendKeys(text);
}
public WebElement findElement(By locator) {
return new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
Then you can change your script to
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
click(By.linkText("Accesso amministratori"));
sendKeys(By.id("username"), "8245");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".btn"));
click(By.id("btn_createDoc"));
sendKeys(By.id("firstName"), "Marco");
sendKeys(By.id("lastName"), "Battiato");
sendKeys(By.id("doc_type"), "Cardiologo");
sendKeys(By.id("id"), "855555");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".glyphicon-send"));
}
which I think makes it more readable, adds waits to everything in case it's needed with no extra code, and so on...
The next level is using the Page Object Model to contain the locators and methods for each page. Then your code gets cleaned up significantly, makes it near-human readable, and MUCH easier to manage.

Why invalid-feedback in thymeleaf not working

I required input it's work but why invalid-feedback not show in modal
HTML use thymeleaf
<!-- AddStore Modal -->
<div class="modal fade" id="AddUserModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddUserModalLabel">Add Store Form</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form autocomplete="off" action="#" th:action="#{/stores/add_store}"
th:object="${store}" method="post"
role="form" id="addModalForm">
<div class="form-row">
<div class="form-group col-md-6">
<label for="addstoreName">Store Name</label>
<input type="text" class="form-control" id="addstoreName" th:field="*{storeName}"
required="required"/>
<div class="invalid-feedback">
Please provide a store name.
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="addStatus">Status</label>
<select id="addStatus" class="form-control" th:field="*{status}">
<option th:value="Ready_to_service">Ready to service</option>
<option th:value="Temporarily_closed">Temporarily closed</option>
<option th:value="Closed">Closed</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<button class="btn btn-success" type="submit" th:text="Save"></button>
</div>
</form>
</div>
</div>
</div>
</div>
Not sure if you found the solution or not as it looks like an old question.
You are missing to let Thymeleaf know about the field specific error. You havn't bind the invalid-feedback class to the "field" error. Try below piece of code.
<input type="text" class="form-control" id="addstoreName" th:field="*{storeName}" required="required"/>
<div class="invalid-feedback" th:if="${#fields.hasErrors('storeName')}" th:errors="*{storeName}"></div>
Take a look at the working example here. Here it will look like this:

Invalid location of tag (form) in JSP Page

here is my code, I have used this code in jsp now when i am using form tag it is showing--invalid location of tag (form)
<div class="col-sm-12">
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body classPadding">
<form role="form" id="js-upload-form" > //INVALID LOCATION OF TAG(FORM)
<div class="col-sm-8 md-pl-0">
<div class="form">
<div class="form-group">
<input type="file" onchange="loadFile(event)" name="econoDataFile" accept="image/*" id="js-upload-files">
</div>
<h5 id="id-text-setting">Upload an Image of size 192*192</h5>
<img id="output" src="" class="save-img" />
</div>
</div>
<div class="col-sm-4">
<button class="btn btn-sm btn-primary" type="submit" id="js-upload-submit">Save</button>
</div>
</form>
<div class="form-group col-md-6 md-pl-0">
<span>Send to a Segment</span> <select id="segment-name" class="form-control">
<option value="-1" >All Subscribers</option> </select>
</div>
</div>
</div>
</div>
I had the same error, in my case the problem was that I had the form nested inside another form

Null value is getting passed to the Servlet from my jQuery script

I am passing a value from a jsp page to bootstrap modal using jQuery and it is working. I want to pass the same value from bootstrap modal to the servlet. I tried with ajax, post, nothing seems to be working. Here is my html:
<div class="container" style="padding-top: 60px;" >
<select class="createAlarm" id="createAlarm" name="metrics">
<option value="cpuUsage">CPU Usage</option>
<option value="memoryUsage">Memory Usage</option>
<option value="diskRead">Disk Read</option>
<option value="diskWrite">Disk Write</option>
<option value="diskUsage">Disk Usage</option>
<option value="netUsage">Net Usage</option>
</select>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-whatever="Create Alarm">Create Alarm</button>
</div>
<!-- Modal- Create Alarm -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Create Alarm</h4>
</div>
<form action="/ProjectName/createAlarm" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 170px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="alarmName">
</div>
</div>
<div class="form-group" style="height: 30px; margin-bottom:30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc"></textarea>
</div>
</div>
<div class="form-group">
<label for="priority" id="priority" name="priority" class="col-md-3 control-label">
<input type="text" class="form-control" name="name">
</label>
<div class="col-md-9">
<div class="col-md-3">
<select name="sign" class="form-control">
<option value="lessthan"><</option>
<option value="greaterthan">></option>
<option value="lessthanequalto"><=</option>
<option value="greaterthanequalto">>=</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="threshold">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" id="formSubmit" type="submit">Create Alarm</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Here is my jQuery part:
<script>
$('#myModal').on('show.bs.modal', function(e) {
var metrics_key = $('.createAlarm').val();
var metrics_label = $(".createAlarm option:selected").text();
// Now you have the key and label in variables.
// Write the key into the textfield.
$('#myModal input[name="name"]').val(metrics_key);
// Change the HTML of an element to the label.
$('#myModal label[for="priority"]').text(metrics_label);
$.post("/CMPE283_Project2/createAlarm", { val : $("#priority").text()});
alert($('#priority').text());
});
My Servlet:
String Metric = request.getParameter("val");
But, I am getting null for the String Metric. But alert pop up after clicking 'Create Alarm' button shows the correct value I want to pass the servlet. Please help. Thanks.
Your post looks ok, I believe it's just a matter of jquery syntax for accessing controls.
In particular, I'd expect a text input with id="priority" (not just a label as it appears in your code), and then you access it with '.val()' and not 'text()'
<input type="text" id="priority" ... />
$.post('your url', {priority: $("#priority").val()} ...
At least this works for me (jquery version 2.1.3). If you want to make sure, you can just start by posting hard coded data such as {priority: '7'}

Spring MVC delete using modal

I have a problem on delete item using modal. I can delete the using just the href obtaining the id and passing it to the controller. But i dont know how to get the id of the item in modal and delete it.
List of persons and actions to be performed
<c:forEach var="user" items="${listpersons}">
<tr>
<td>${user.username}<!-- <span>Clients</span> --> </td>
<td>${user.email}</td>
<td>
<button class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="Compose"><i class="fa fa-envelope-o"></i></button>
<i class="fa fa-edit" title="Edit"></i></button>
<i class="fa fa-trash-o"></i>
Launch Demo Modal
</td>
<td class="text-right mail-date">Jan 16</td>
</tr>
</c:forEach>
this part is the modal button when clicked pops.up a if i want to really delete the item
Launch Demo Modal
this is my delete button. i can delete here but i want to delete using modal
<i class="fa fa-trash-o"></i>
and this is my modal popup
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this user? </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<i class="fa fa-trash-o"></i>
</div>
</div>
</div>
</div>
I dont know how to pass the id of the person in the modal popup. delete doesnt work. it doent recognize any id
this is the controller
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView delete(#ModelAttribute("SpringWeb")User user, ModelMap model, HttpServletRequest request)
{
try
{
UserDao ud = new UserJDBC();
int id = Integer.parseInt(request.getParameter("id"));
int delete = ud.deleteUser(id);
model.addAttribute("message", "User deleted Successfuly");
}
catch(Exception e)
{
System.out.print(e);
model.addAttribute("message", "Error occured in deleting user.");
}
return new ModelAndView("admin-view-users");
}
User is not deleted. i get this delete?id=0 when clicking the Delete on the modal
Append ${user.id} with href value of popup show button i.e.
#myModal_${user.id}
Add modal popup inside the foreach loop and now append ${user.id} with popup id.
i.e. myModal_${user.id}
replace your foreach with this code and remove popup.
<c:forEach var="user" items="${listpersons}">
<tr>
<td>${user.username}<!-- <span>Clients</span> --> </td>
<td>${user.email}</td>
<td>
<button class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="Compose"><i class="fa fa-envelope-o"></i></button>
<i class="fa fa-edit" title="Edit"></i></button>
<i class="fa fa-trash-o"></i>
Launch Demo Modal
</td>
<td class="text-right mail-date">Jan 16</td>
</tr>
<div id="myModal_${user.id}" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this user? </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<i class="fa fa-trash-o"></i>Delete
</div>
</div>
</div>
</div>
</c:forEach>
Note:-Please do not forgot to add modal popup inside foreach.

Categories