I have a created a small Java web application. I have made use of DAO and a JSP file. My issue is that when I enter an isbn number in the input field, if the book is found in the database, it displays me "Book Found" and the corresponding details. But if I enter an isbn number in the input field, and if the book is not found in the db, it still displays me "Book Found" but with isbn number 0 and book title "null" which I don't want. In that case, it should display me only "Book not found".
Note that the problem lies mainly in the JSP page.
Here is my full code: http://pastebin.com/cTZy4w6V (using pastebin since the code is too long)
Here is the JSP code:
<jsp:useBean id = "bm" class="book.ManagerBook" scope = "session"/>
<h1> Welcome to ABC Library</h1>
<form>
<table>
<tr>
<td> Enter Details </td>
<td><input type="text" name="isbn"></td>
<td><input type="submit" name="find" value="find"></td>
</tr>
</table>
<input type="hidden" name="submitted" value="true">
</form>
<%
Boolean submitted = Boolean.parseBoolean(request.getParameter("submitted"));
if(submitted){
int isbn = Integer.parseInt(request.getParameter("isbn"));
Book b2 = bm.findBook(isbn);
%>
<table>
<tr>
<td colspan=2>
<h2>Book Found</h2>
</td>
</tr>
<tr>
<td><h3>ISBN</h3></td>
<td><h3>Title</h3></td>
</tr>
<tr>
<td><%= b2.getIsbn()%></td>
<td><%= b2.getTitle() %></td>
</tr>
</table>
<%}else if(!submitted){ %>
<h3> Book Not Found</h3>
<% } %>
If possible, don't use scriptlets in jsp. It's a bad practice.
Try something like this:
if(submitted){
int isbn = Integer.parseInt(request.getParameter("isbn"));
Book b2 = bm.findBook(isbn);
if (b2.getTitle() != null) {
%>
<table>
<tr>
<td colspan=2>
<h2>Book Found</h2>
</td>
</tr>
<tr>
<td><h3>ISBN</h3></td>
<td><h3>Title</h3></td>
</tr>
<tr>
<td><%= b2.getIsbn()%></td>
<td><%= b2.getTitle() %></td>
</tr>
</table>
<% } else { %>
<h3> Book Not Found</h3>
<% } %> }
Related
I have one jsp page. I am passing 2 model objects from spring controller.
asset (gets selected asset).
assets (get all assets)
I want to set option selected if condition matches.
My code
<table>
<tr>
<td>Asset Id :</td>
<td>
<form id="getAssetForm" method="get">
<select id="assetid" name="assetid" onchange="submitForm(this);">
<c:if test="${not empty assets}">
<c:forEach items="${assets}" var="assetsproperties">
<c:choose>
<c:when test="${not empty asset}">
<c:forEach items="${asset}" var="assetobj">
<c:choose>
<c:when test="${assetobj.id} == ${assetsproperties.id}">
<option value="${assetobj.id}" selected>${assetobj.name}</option>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:if>
</select>
</form>
</td>
</tr>
<tr>
<td>Name :</td>
<td><input type="text" name="assetname" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.name}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Model Number :</td>
<td><input type="text" name="assetmodelnumber" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.modelNumber}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Rating (1 to 5 ):</td>
<td><input type="text" name="assetrating" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.rating}</c:forEach></c:if>"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="Save" value="Update">
</tr>
</table>
<script type="text/javascript">
function submitForm(a){
var e = document.getElementById("assetid");
var assetid = e.options[e.selectedIndex].value;
var assetnametxt = e.options[e.selectedIndex].text;
var assetnameElement = document.createElement("input");
assetnameElement.type = "hidden";
assetnameElement.name = "assetname";
assetnameElement.value = assetnametxt;
var form = document.getElementById('getAssetForm');
form.appendChild(assetnameElement);
form.setAttribute('action', "get-asset");
form.submit();
}
</script>
here is my controller code :
#RequestMapping(value="/get-asset", method = RequestMethod.GET)
public String showGetAssetPage(ModelMap model,
#RequestParam("assetid") int assetid,
#RequestParam("assetname") String assetname){
System.out.println("inside showGetAssetPage() ");
List<Asset> asset = service.getAsset(assetid, assetname);
model.addAttribute("asset", asset);
List<Asset> assets = service.getAssets();
model.addAttribute("assets", assets);
return "update-asset";
}
I want to show selected asset on page load.
How to match condition using jstl?
You should have a boolean field isSelected in your Asset model. In your controller,set the isSelected property in all the assets object. Using this only all assets and checking isSelected property you can set is as selected.
I'm having a few problems with some JSTL code. The thing is that i'm trying to compare the id of the user that logged in with the id from the reservation class which has a foreign key of the user id.And after doing that i'm trying to populate the page with update links based on the reservation id.
Here's the code of what i tried but i can't find a way to make it work.
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
</c:forEach>
<% for(ReservationBean res : theReserv){
/* int userId = (Integer) request.getSession().getAttribute("userId"); */
if(userId == res.getUserId()){ %>
<tr>
<td> <%= res.getReservationId() %> </td>
<td> <%= res.getDataCheckin() %> </td>
<td> <%= res.getDataCheckout() %> </td>
<td> <%= res.getNrPersoane()%> </td>
<td> <%= res.getNrCamere() %> </td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this reservation?'))) return false">Delete</a>
</td>
</tr>
<%}%>
<%}%>
</tr>
</table>
In the second for i'm comparing the id of the user that logged in with the id of the user from the reservation class but of course the updated links will contain the last value of the first for and i don't know how to do what i did in pure java with JSTL to have only one for and get the correct values of the update link or delete ones.Do you guys have any clue on how to do that?
I've tried something like this
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:if test="${tempReservation.userId}" == userId >
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<tr>
<td>${tempReservation.reservationId}</td>
<td>${tempReservation.dataCheckin}</td>
<td>${tempReservation.dataCheckout}</td>
<td>${tempReservation.nrPersoane}</td>
<td>${tempReservation.nrCamere}</td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:if>
</c:forEach>
But that if condition doesn't work or i don't know how to compare jstl code with java code
Edit2: I made it work! You had to compare it something like this
<c:if test="${tempReservation.userId == userId }">
Thanks for help!
In View.jsp I created a form by using . there are some inputs and 3 select-box on it, actually I want to validate all of them. for inputs I used but I don't know how can I validate my
Actually I want to validate these three :
<aui:select id="birthday_day" name="birthday_day">
<aui:select id="birthday_month" name="birthday_month">
<aui:select id="birthday_year" name="birthday_year">
This is my view.jsp
<portlet:actionURL var="myUrl">
</portlet:actionURL>
<aui:form enctype="multipart/form-data" action="<%= myUrl %>" method="POST" name="fm">
<table border="0" bgcolor=#ccFDDEE>
<tr>
<td colspan="2" align="center"><b>Recruiment Form</b></td>
</tr>
<tr>
<td colspan="2" align="center"></td>
</tr>
<tr>
<td><b>First Name:<span>*</span></b></td>
<td>
<aui:input name="fname" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Last Name:<span>*</span></b></td>
<td>
<aui:input name="lname" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Father Name:<span>*</span></b></td>
<td>
<aui:input name="father_name" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Birth Date:<span>*</span></b></td>
<td>
<aui:select id="birthday_day" name="<portlet:namespace/>birthday_day">
<aui:option value="0">روز</aui:option>
<%
for(int i=1;i<=31;i++) {
%>
<aui:option value="<%=i%>"><%=i%></aui:option>
<%
}
%>
</aui:select>
/
<aui:select id="birthday_month" name="birthday_month">
<aui:option value="0">ماه</aui:option>
<%
String[] monthBirthDay = {"فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"};
for(int j=0;j<monthBirthDay.length;j++) {
%>
<aui:option value="<%=j+1%>"><%=monthBirthDay[j]%></aui:option>
<%
}
%>
</aui:select>
/
<aui:select id="birthday_year" name="birthday_year">
<aui:option value="0">سال</aui:option>
<%
String[] yearBirthDay = {"1370","1369","1368","1367","1366","1365","1364"};
for(int j=0;j<yearBirthDay.length;j++) {
%>
<aui:option value="<%=yearBirthDay[j]%>"><%=yearBirthDay[j]%></aui:option>
<%
}
%>
</aui:select>
</td>
</tr>
</table>
</aui:form>
How can I solve this issue??????
Please guide me.
<aui:select showEmptyOption="true" name="select hospital name" required="true">
</aui:select>
THis may help you.
just assign an id to the aui:select tag
<aui:select inlineField="true" label="xxx" name="xxx" id="xxxId">
and then you can get the value with this (javascript + AUI)
var selectedVal = A.one('#<portlet:namespace/>xxxId').val();
with the selected value you can perform any kind of validation.
I have this code that checks duplicate name id
NameRefBean myNameBean = new NameRefBean();
myNameBean.load(NameID);
if (!myNameBean.getErrFlag()) {
errExistFlag = true;
errCode = DUPLICATE_NAME_ID;
return(false);
I have switch case where it saves data from the jsp page form
case ACTION_SAVE:
if (hdTxnType.equalsIgnoreCase("Add")) {
if (validateInputData()) {
nameBean.setNameID(tbNameID);
nameBean.setName(tbName);
nameBean.setGender(tbGender);
hdTxnType = new String("Update");
}
} else {
nameBean.setNameID(hdNameID);
nameBean.setName(tbName);
nameBean.setGender(tbGender);
}
break;
My question is how can I check for gender value when particular nameid is selected? If user changes gender value from M to F, I need to give a warning on the jsp page saying "gender already exist do you want to modify it?"
Here is my jsp page
<% if (nameBean.getErrFlag()) {%>
<CENTER><b><font color=red><%= nameBean.getErrMsg() %></b></font></CENTER>
<% } %>
<TABLE WIDTH="800" BORDER="0">
<TR>
<TD><B>Name ID: </B></TD>
<% if (nameBean.getTxnType().equalsIgnoreCase("Add"))
{ %>
<TD><INPUT TYPE=TEXT NAME="tbNameID" VALUE="<%= nameBean.getnameID()%>" ></TD>
<% } else { %>
<TD><%= nameBean.getNameID()%> </TD>
<% } %>
<TD><B> Name: </B></TD>
<TD><INPUT TYPE=TEXT NAME="tbName" VALUE="<%= nameBean.getName()%>" ></TD>
<TD><B>Gender: </B></TD>
<TD><INPUT TYPE=TEXT NAME="tbGender" VALUE="<%= nameBean.getGender()%>" ></TD>
</TR>
<BR>
<TR>
<% if (userProfileBean.hasRole("FULL") ) { %>
<TD>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes">
<% if (nameBean.getTxnType().equalsIgnoreCase("Update"))
{ %>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Delete">
<% } %>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Cancel">
</TD>
<% } %>
You could add a piece of JavaScript that print the warning, if a user changed the gender. The only thing you have to do then, is to enable this java script if the nameid is already set (then the name already exists, and every change should print the warning.) If the nameid is null, then it is a new name and you must not enable the java script warning functionality.
in jsp
<table width="100%" id='table1' border="0" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="10%">
<div align="left">Project ID</div>
</td>
<td class="tab-highlighted-2" width="10%">
<div align="left">Project Name</div>
</td>
<td class="tab-highlighted-2" width="20%">
<div align="left">Cost Center</div>
</td>
<td class="tab-highlighted-2" width="20%">
<div align="left">Manager</div>
</td>
</tr>
<tr class="bg-row1">
<c:forEach items="${resultList}" var="resultList">
<td class="td-highlighted-2">
<div align="left">${resultList.Projid}</div>
</td>
<td class="td-highlighted-2">
<div align="left">${resultList.Projname}</div>
</td>
<td class="td-highlighted-2">
<div align="left">${resultList.Cost}</div>
</td>
<td class="td-highlighted-2">
<div align="left">${resultList.Manager}</div>
</td>
</tr>
</table>
in dao
public final class SearchProjDAO
{
private static InitialContext context;
String CLASS_NAME="DBConnectionFactory";
public ArrayList submitProjectDetails(SearchProjVO searchprojVO)
{
ArrayList ar = new ArrayList();
String methodname="createConnection";
Connection conn = null;
PreparedStatement psmt;
try {
System.out.println("in DAO");
System.out.println("searchprojVO id=="+searchprojVO.getProjid());
conn = DBConnection.getJNDIConnection();
ResultSet rs = null;
String query="select * from CR_EMPLOYEE_DETAILS";if(searchprojVO.getProjid()!=null || searchprojVO.getProjname()!=null || searchprojVO.getManager()!=null)
query=query+" where ";
if(searchprojVO.getProjid()!=null)
query=query+" PROJ_ID="+searchprojVO.getProjid();
if(searchprojVO.getProjname()!=null)
query=query+"PROJ_NAME="+searchprojVO.getProjname();
if(searchprojVO.getCost()!=null);
query=query+"PROJ_COST="+searchprojVO.getCost();
if(searchprojVO.getManager()!=null)
query=query+"PROJ_MANAGER="+searchprojVO.getManager();
psmt= conn.prepareStatement(query);
rs=psmt.executeQuery();
while(rs.next())
{
SearchProjVO projVO = new SearchProjVO();
projVO.setProjid(rs.getString("PROJ_ID"));
projVO.setManager(rs.getString("PROJ_NAME"));
projVO.setProjname(rs.getString("PROJ_COST"));
projVO.setManager(rs.getString("PROJ_MANAGER"));
ar.add(projVO);
}
System.out.println("conn==="+conn);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return ar;
}
}
I spot several mistakes:
Here,
<c:forEach items="${resultList}" var="resultList">
You're overriding the list value with the value of the list item everytime. Don't do that. Give the var an unique variable name. The entity name is the most straightforward choice.
<c:forEach items="${resultList}" var="project">
Note that I'd personally also rename the nothing-saying resultList to a more self-explaining projects.
And here,
<tr class="bg-row1">
<c:forEach items="${resultList}" var="project">
the flow is wrong. You should print a new row inside each loop. Swap them.
<c:forEach items="${resultList}" var="project">
<tr class="bg-row1">
And here,
${resultList.Projid}
${resultList.Projname}
${resultList.Cost}
${resultList.Manager}
the property names must start with lowercase (and fix the item name to be the same as in var).
${project.projid}
${project.projname}
${project.cost}
${project.manager}
Note that I'd personally also get rid of proj prefix in some property names.
And finally you're forgotten a closing </c:forEach>.
</tr>
</c:forEach>
Unrelated to the concrete problem, your JDBC code is sensitive to SQL injection attacks and is leaking resources. Fix it as well.