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.
Related
I hope you get my problem.
out.println("<li class='has-sub'><a href='#'>" + k1.getKName() + "</a>\n");
I have a JSP and inside this java code. The result is a navigation on the left side with several categories and subcategories. So this is one category element. As you can see, I didn't put anything in the href. What I want to do is, that when I click on this category, I will get the articles of this category in the content space on the right side.
So, what do I have to do with servlets or JSPs in order to give a result to the content space. I can't just call a servlet there of course, because that means that I get the result of the servlet inside the href obviously.
I am sorry if this is a silly question, but I really don't know how to solve this :(
Further to previous comments you do not need web services. You can do this using ajax and a normal Servlet. You might want to look at using JQuery to help with the Ajax part. Here's some JQuery documentation around the load() function which will:
Load data from the server and place the returned HTML into the matched
element.
https://api.jquery.com/load/
Your link will look something like (if k1 is a bean in some scope then you can use EL rather than scriptlets):
<a href='javascript:loadData(${k1.id});'>${k1.name}</a>
Your Javascript will look something like:
function loadData(id){
var url = "/pathToMyServlet?id=" + id;
$( "#result" ).load( url );
}
which will call your Servlet and insert the HTML returned to an element on your page with the ID 'result'.
Your Servlet then needs to generate the data and forward to a simple JSP which returns the results (and only the results) i.e. it does not need to be a fully formed HTML page but should only contain the table of results or whatever.
And stop using scriptlets:
How to avoid Java code in JSP files?
I have a jsp page having a 'submit' option for input.On clicking it i want to update the value of a table called tbIndividual.What can be the best approach to do it?
On jsp page i have somthing like this :
User Name : <%=rs.getString(2)%>
First Name : <%=rs.getString(4)%>
Last Name : <%=rs.getString(5)%>
Email Id : <%=rs.getString(6)%>
Contact : <%=rs.getString(7)%>
<input type="submit" value="ADD"></input>
And now i want to update the value of status of that particular individual from 'NO' to 'WAIT' state.On click of this submit button.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
If i need to make a new servlet then what will be the code for it on jsp page .?Please help.
If you are trying to learn servlet with this project then you should create a separate servlet where you will perform your business logic (e.g addition of element in Db) and jsp should be kept away from business logic because role of jsp is to render the output not to produce the output.
If this is a project for production purposes, then you should ( IMO you must ) opt some web framework. As framework will reduce your effort, headache and increase productivity.
First of all, there are certain things you need to understand while developing web applications in Java. I have a few recommendations and inputs
Please don't use Scriptlets. Scriptlets are deprecated and they make your code clumsy and the maintainance will be hard. Use JSTL
You need to create a form in your html to have a set of variables to push them to the server on clicking submit button. The form will have an action attribute which contains the URL where the request should be sent
Create a Servlet and map with the action URL and write the doPost method which can receive the form parameters and do the business logic whatever changing the status from NO to WAIT or anything else
Please take a note that you need to have Session variables in order to have the store the data in between requests from the same client. eg browser.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
Writing a new servlet is a good option, than doing the business logic in jsp page. jsp is meant for presentation, just view. They shouldn't be used to perform business logic
If i need to make a new servlet then what will be the code for it on jsp page .?
JSP should just have all the necessary html elements and attributes like form, action attribute etc.. to post the parameters in the request to the action URL. Please note the method attribute of form. You should use HTTP POST method for posting form parameters to the server
Note : Finally, Writing Servlets are also NOT recommended. Instead, you should opt for webframeworks like Spring MVC , Struts etc. Please go through the link to understand about web frameworks answered by #BaluC
Hope this clarifies.
<%
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).
I new in JSP, i have a problem with JSP
in php i use
$page=$_GET["page"]
for display multiple page for one layout it mean i have index , it display layout and when i click on menu go to about us the index url = index.jsp?page=about
in PHP when i declare $page above and next step i do
Switch($page){
case 1:about
include 'aboutus.php'
case 2:news
include 'news.php'
}
How can i do it ?
How jsp can do the same way php to display multiple page in 1 layout
Use jsp:include.
<jsp:include page="/WEB-INF/${param.page}.jsp" />
And pass ?page=news or ?page=about, etc as parameter. The ${param.page} prints the outcome of request.getParameter("page"). You can prevent direct access to JSP files (by entering URL in browser address bar) by placing JSP files in /WEB-INF folder.
See also:
Basic JSP/Servlet tutorials
Hidden features of JSP/Servlet
How to avoid Java code in JSP
nowadays you use "templates" of Java Server Faces (JSF) for this approach. When you use JSP, you actually don't use the same concept as in PHP. You'd better use the MVC concept. But to answer your question, you could probably achieve this with the include tag http://java.sun.com/products/jsp/tags/11/syntaxref1112.html and control it with JSTL:
http://www.java2s.com/Code/Java/JSTL/JSTLiftag.htm
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 5 years ago.
I've developed an application using Tomcat, Mysql and Servlets.
One of the options the user can choose is to see on the web browser the information of one of the tables of a database. When the user chooses this option a servlet is used. This servlet opens a connection to the data base and iterates over the rows, showing the information. This works without problems.
In order to show this information in the browser I'm using a lot of "out.println()" lines.
Although the functionality is implemented I'd like to know if there is any other way of showing this information on the browser. If anyone could name a method or provide me with links to examples it would be great.
thanks a lot.
Create a Javabean class which represents each item (row) of the table. Create a DAO class which returns a list of those items using JDBC. Then in the servlet, just put the list of items in the request scope using HttpServletRequest#setAttribute(), forward the request to a JSP file using RequestDispatcher#forward() and iterate over the list of items using JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag.
Basic kickoff example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Item> items = itemDAO.list();
request.setAttribute("items", items); // It's now available as ${items} in EL.
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
}
where result.jsp look like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<table>
<c:forEach items="${items}" var="item">
<tr>
<td>${item.someProperty}</td>
<td>${item.anotherProperty}</td>
</tr>
</c:forEach>
</table>
For more hints and examples you may find this article an useful starting point.
It's a Good Thing that you asked this. Putting presentation logic in a Servlet class is a bad practice. Any of those out.println() statements inside a Servlet class needs to be eliminated. It belongs in a JSP file.
To go some steps further, you can also use a MVC framework so that you basically end up with only a Javabean class and a JSP file (i.e. the role of the servlet have been taken over by the MVC framework).
Just choose one web framework among many
Try using Java Server Pages along with the JavaServer Pages Standard Tag Library. JSP's with JSTL is a way of using html like syntax (xml) to create dynamic Java web pages. JSP's are converted to Servlets at runtime.
There are many different ways to achieve the same ( thanks to the abundance of web frame works)
To list a few:
Pure Servlets (As you have done)
Servlet + JSP
Servlet + JSP ( using JSTL)
Struts frame work involving JSP and action classes
Spring webflows (involves JSP)
Velocity, Tapestry, Cocoon, Stripes ( all require JSP knowledge) ... and it is endless
An ideal way is to separate content out of Servlets.
Content should go into pages such as JSPs. Servlets' out.println is so.. 90s.
Java web technology has come a long way since then.
Cheers!