<%
ResultSet rsta=st.executeQuery("SELECT DISTINCT user_type FROM details where user_type not like 'null'");
while(rsta.next()) {
out.write("<option value=" + rsta.getString("user_type") + ">" + rsta.getString("user_type") + "</option>");
}
%>
</select>
<label>Sct</label><select name="sct" id="subject" >
<option selected="true" style="display:none;">Select Sct</option>
<%
ResultSet rsta1=st.executeQuery("SELECT DISTINCT sct,user_type FROM details where sct not like 'null'");
while(rsta1.next()) {
out.write("<option value=" + rsta1.getString("sct") + ">" + rsta1.getString("sct") + "</option>");
}
%>
</select>
<label>Standard:</label><select name="standard" id="standard" >
<option selected="true" style="display:none;">Select Standard</option>
<%
ResultSet rsta2=st.executeQuery("Select DISTINCT standard from details where standard not like 'null'");
while(rsta2.next()) {
out.write("<option value=" + rsta2.getString("standard") + ">" + rsta2.getString("standard") + "</option>");
}
%>
</select>
<label>Division:</label><select name="division"id="division" >
<option selected="true" style="display:none;">Select Division</option>
<%
ResultSet rsta3=st.executeQuery("Select DISTINCT division from details where division not like 'null'");
while(rsta3.next()) {
out.write("<option value=" + rsta3.getString("division") + ">" + rsta3.getString("division") + "</option>");
}
%>
</select>
These are 4 select fields.All the 4 get the list from the mysql database.
But all the selects get all the possible values from the database depending on the column selected.
I will give an example
While entering into the database suppose I add for the 4 columns a,1,cat,milk
2nd row consists of b,2,dog,bone.
Now in my above code I will get in the first select(a,b),second select(1,2) and so on.
I want the search to narrow,if I select a in the first select only 1 should appear n the second and cat in the third.How should I do this.
I am using JSP
I first suggest you read a book on JSP cover to cover. We typically don't embed scriplets ( < % % >) in JSP pages anymore. Search amazon.com for beginning books on JSP that have good reviews and have been published within the last year or so. The book will most likely cover servlets too. you can also read up on JSTL. Reading the book can save you countless hours messing around with code fragments online and asking questions. You should be reading many books on Java and related technologies over time.
That being said:
The JSP page (presentation layer) is responsible for displaying data and handling user events (mouse clicks, etc). There should be no business logic or database logic in the page. In a very basic design, you have one and only one servlet that many JSP pages communicates with. When a person enters a url in his browser, the request goes to the servlet. The servlet calls business logic that in turn calls the database to get all the data it needs to initially populate the JSP page. The servlet puts the data in request scope (or session scope), then dispatches to the JSP page. The JSP page gets data from request scope to populate itself.
In answer to your question: populate the first dropdown upon initial page load (SQL call) via the servlet. The other dropdown boxes will be empty. When the user makes a selection in the first dropdown, have the page submit to the servlet. The servlet will read the first selected value and query the database to populate the second column. It will then dispatch to the JSP page to display the data in the first and second dropdown. A similiar operation occurs when the user selects an item in the second column.
Lastly: read up on database design. Your database tables should be properly normalized. Also, you don't store a string value of 'null' in your datbase columns. You store an actual null instead.
The more professional approach is to use an ajax call to populate a dropdown box(s) rather than reload the entire form. Instead of raw ajax, I would recommend JQuery, which has ajax built in. Note Ajax calls are often generally used to alter an component on the browser and avoid repopulating the entire form. Another alternative is to store all the dropdown data in a multidimentional javascript structure and use oncick events to grab the selected item in one dropdown box to populate the next dropdown box. This way, there is no need to call back to the server (it all runs client side).
Related
I fetched data(some strings) from the database and i covered each string in a link in A.jsp page . Now if clicked a link,then the string that covered by the link is displayed in B.jsp . Here i note that in database i stored an image as a string .So here string is nothing but an image.
<% ResultSet rs=st.executeQuery("Select name,image from base64image");
int ii=0;
while(rs.next()){
if(ii==0)
out.println("<tr>");
ii=1;
%>
<td> <img src='<%=rs.getString(2)%>' height='200px;' width='200px' />n</td>
<%
i++;
if(i%3 ==0 ){
out.println("</tr>");
ii=0;
}
}
out.println("</tr> </table>");
}
Ok, so looking at your code, your using the expression tags for outputting the string you need. This string is the image source path, and the image is then used as the click link for your B.jsp page.
I'm assuming this expression is java, since the variable your using has a object type, and respective "getString()" method. If this is the case your code doesn't show the above "rs" object to be in jsp <% %> tags. Any java you write in jsp files need to be in these tags.
<% ResultSet rs=st.executeQuery("Select name,image from base64image"); %>
This being said using java in scriptlets in this manner is generally considered bad practice, however, I could understand the want to clean up the jsp file, and minimize the amount of lines to accomplish the query. This being said, just for completion's sake of this answer, this is how you might accomplish the same thing using jstl tags:
//first include the sql tag library in your Jsp
<%# taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
<sql:query dataSource = "datasource/here" var = "result">
//full query here
SELECT * from Employees;
</sql:query>
//You can then use the result variable using standard jsp
//Here you can grab the row, or sift through multiple results, etc.
<c:forEach var = "row" items = "${result.rows}">
<img src='${row.columnName}' height='200px;' width='200px' />n
</c:forEach>
info and examples here
However this is a lot of code in your jsp that isn't even the best way of going about this. Because you're only expecting one row returned, you would be forced to handle the results as if it returned multiple rows. (which is great however, if you needed to put this information into a table format)
The other solution would be to use java servlets. I can't fully recommend this though, as I don't know the structure of your code. This could either be easy, or difficult to implement into your system. However this still doesn't beat the one-line approach.
If you were to accomplish this via a separate servlet class, you would essentially call the class via an ajax call in the jsp, or using other various methods mentioned in this answer.
I hope I helped you solve your issue, and help any other people who stumble upon this answer!
Pass an Id with anchor tag in A.jsp
' <img src='c%>
Now in B.jsp retrives all the names 1st column value from the database.If it matches with this id's value,then show the image by using tag
<img src="<%=rs.getString(2)" />
I am brand new to all of this, I like servlets and java on a whole so far but I'm having some growing pains.
Servlet Question: Just starting to learn servlets and I'm having an issue with Attributes/Parameters, Sessions and jsp.
Basically, I have a very basic
form. My servlet code states:
println("Hello, " + request.getParameter("name") + "!!!");
..and my .jsp states:
<form action="SimpleServlet" method="POST">
<input type="text" name="name">
<input type="submit"/>
</form>
So now what I need to do is take the last name input into this servlet, save it in session and then send it to a different .jsp that states:
'Hello, '
For example, if I input JIM into the servlet and it returns 'Hello, Jim!!!' in my first .jsp I would then need to click on a link on that page that re-directs me to another .jsp that takes the 'Jim' input and also displays 'Hello, Jim!'.
So I created a 2nd .jsp and have tried many different combinations of code on both to try and get this to work and I keep on getting null or screwing up the output of the first part of the form.
Could someone guide me in the right direction, I would greatly appreciate it.
if you want to show your last name JIM in multiple jsp pages you can use session to store your last name add following code in your servlet.
String name = request.getParameter("name");
HttpSession session=request.getSession();
session.setAttribute("name",name);
then in all your jsp you need to do is put following scriplet where you want to print your name.
<%
String name = request.getSession().getAttribute("name");
out.print(name);
%>
You can do exactly what you want using a single .jsp page, you don't have to create a different one. Just create a link that will POST different parameters to the same .jsp
But as an advice/direction to you, I think the first thing you must understand well is how can you pass and receive parameters and attributes to deal with at server side. Understanding what a request can carry has a huge importance in server-side development.
Just an addon to Mitul's answer
I'd advice you to use EL. It is a simplified approach.
Instead of String name = request.getSession().getAttribute("name"); use
${sessionScope.name} It would give you the desired output.
The best part is that scope resolution is done automatically. So, here name could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as
I initially wrote a .jsp connected by Struts 1.1 to pull some data from a database using scriplets:
<% Map<String, myObject> map = MyClass.returnMap();
for(Map.Entry<String, myObject> entry : map.entrySet()) {
myObject element = entry.getValue();
out.println("<tr>");
out.println("<td><input type=\"checkbox\" name=\"objects[]\" value=\"" + entry.getKey() + "\"/>" + entry.getKey() + "</td>");
out.println("<td>" + element.property1() + "</td>");
out.println("<td>" + element.property2() + "</td>");
}
%>
So I end up with a table with a checkbox, object name, and two of the element's properties as the columns, with a row for each entry in the Map returned by returnMap().
Now, I want to be able to check however many checkboxes inside the generated table, and then click a button to send a list of all the checked checkboxes to a servlet to perform some server-side calculations depending on the checkboxes selected.
One problem is that the said "submit" button is outside the table, in a separate div (used for a fixed position header). Could I just wrap a form around the entirety of the div containing the button, and the table?
I am starting out in web development, and have done some tutorials on Servlets and I understand the basic concepts. I have seen that it's generally bad practice to use scriptlets for business logic in the jsp, so I am considering generating the table through my Servlet instead. However, I also want to be able to use the elements generated by the Servlet in another Servlet method (if that makes sense).
My thought process was:
1) .JSP loads through Struts
2) .JSP receives table from Servlet
3) When submit button is clicked, sends list of checked checkboxes back to the Servlet
4) Servlet uses list of checkboxes and performs some business logic
5) .JSP refreshes with updated table
Is this a viable process? Or is there a better way to do this?
I have to access the .jsp (through Struts), not the servlet url most of the tutorials use
I suggest to avoid Scriplet instead use JSP Standard Tag Library and Expression language that is easy to user and less error prone.
Map.Entry contains getKey() and getValue() methods to access key and value from Map Entry.
Simply set the return value as request attribute in Servlet and then you can access it in JSP using JSTL.
Sample code:
Servlet:
request.setAttribute("map",MyClass.returnMap());
// forward the request to the jsp
JSP:
<c:forEach var="entry" items="${map}">
<c:out value="${entry.key}"/>:<core:out value="${entry.value}"/>
</c:forEach>
read more...
Struts1 is rather outdated now and is officially no longer supported by Apache foundation. From Apache Struts site : The Apache Struts Project Team would like to inform you that the Struts 1.x web framework has reached its end of life and is no longer officially supported. So if you are beginning with it, you should considere using another framework such as Struts2 or Spring MVC.
But the resources are still present and you should use Struts 1 User Guide.
So you should have one Action for displaying the JSP. In the JSP, the form must include all the input fields **and* the submit one (possibly across many divs). You should have another Action to treat the inputs and an ActionForm to carry the data between first Action and the JSP at render time, and to give the input values to the second one at submit time.
Do not forget that Struts1 comes with a taglib that could help you to avoid as much scriptlet as possible from you JSP, but IMHO, you should use JSTL when possible instead of Struts specific tags when they do same thing : migration will be easier if you later want to use another framework.
Normally it is the job of second action to call business methods to do intelligent things with input values, and it is recommended to do a redirect after a submit (POST) to avoid submitting again if user refreshes its browser or clicks on back arrow button of browser.
I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.
Hello i have a JSP page that displays records from animal table in my database which contain id, name, date-of-birth and some other information
what i want when the user click on animal name will be redirected to updateServlet which will display another JSP page for updating
I was trying the following:
<td><a href="/Relay?update="+${view.animalId}>${view.animalName}</a></td>
where ${view.animalId} represents the animal_id column, and ${view.animalName} the animal_name and these records come from arraylist
is it possible to pass the animal_id in the link in jsp page ?
Yes, it is possible, but you were doing it wrong. You seem to think that HTML is a dynamic language and somehow part of the Java/JSP language. But this is not true. You should see JSP more as a HTML code generator. The following example should work for you:
<td>${view.animalName}</td>
This way it's as following available in the servlet mapped on /Relay:
String animalId = request.getParameter("update");
// ...