The main page has link to create new record and one to show all the existing records.
On the create_new_record page I am writing all the data to a file in an action class method called saveRecords and populating a List<Records> in retriveRecords methods.
My action class code:
public class MyRecordes{
List<RecoredInfo> recoreds= new ArrayList<RecoredInfo>();
}
I have getters and setters for the same records in my action class(I am using Struts 2),
but on the main page when I click to show all records (which shows a different JSP page), nothing is displayed. Do I have to use servlets and/or doGet, etc. methods?
EDIT:
Adding code for showList.jsp:
<table>
<s:iterator value="arrayList" status="status">
<tr>
<td><s:property value="firstName"/> <s:property value="lastName"/>
</td>
</tr>
</s:iterator>
</table>
My action class has an arraylist named arrayList and I am using getters/setters to set the value.
The different action will populate the list and return a result of the different JSP page. In the different JSP you can show records using
iterator
Iterator will iterate over a value. An iterable value can be any of:
java.util.Collection, java.util.Iterator, java.util.Enumeration,
java.util.Map, or an array.
Whatever you show on the JSP the data should be bound to the beans properties that you can retrieve via OGNL expression and written to the JSP output.
OGNL
OGNL is the Object Graph Navigation Language (see
commons-ognl for the full
documentation of OGNL). Here, we will cover a few examples of OGNL
features that co-exist with the framework. To review basic concepts,
refer to OGNL Basics.
If you are using Struts2 you don't need servlets and/or doGet etc. methods. Struts2 framework implements MVC pattern that you can follow while writing your web application. If you are new to the framework, then better get started from the Tutorials.
Tutorials
The framework documentation is written for active web developers and
assumes a working knowledge about how Java web applications are built.
For more about the underlying nuts and bolts, see the Key
Technologies Primer.
Related
i have done some learning on struts based on one project that i got.Now i have to build 2 to 3 struts jsp pages.
I have following scenario..
<action name="BackAction" class="ClassnamePath">
<result name="user_validated" type="redirectAction">
<param name="actionName">welcome</param>
</result>
<result name="user_profile_found_in_database">/resources/userprofile.jsp</result>
what does param will tell..what is the significance of param(i do not know about this)
my scenario is like this In the class(ClassnamePath) i have done one java program which bring the data from the database and put the values in the userprofile.java(for example the userprofile has variable members like name,email,phone,pin)
that values are come from database and stored in the object of the class userprofile.
i have a task that whenever the result "user_profile_found_in_database" has been done those values should be presented in the jsp as result of the "user_profile_found_in_database"
Is the result "user_profile_found_in_database" that i mentioned in the action tag correct?
the jsp page should be having userprofile with labels as the fields of the userprofile and values should be in the text boxes.
i do not know anything about jsp pages...even web programming..but i am learning on my own..(i am having one doubt how jsp pages are different from struts jsp pages)
with the above tasks i can learn lot in struts and jsp..
Please give some knowledge on this to build further.
JSP pages are not way different than simple JSP pages and in short Struts2 will provides a set of tags which will help we as an end developer to build application fast as these tags provides a easy to access functionality about various features S2 providing, few of them are
Accessing Value Stack using OGNL
Data conversion from server to client and other way around
Features to access other things like request/response/session in most easy and flexible way.
In end when you browser will render the jsp page it will be simple HTML and S2 tags one using in there application will be converted to the HTML as browser will understand HTML.
regarding second part accessing user profile in your jsp do the following gin your Action class
Create an instance of UserProfile in you action class
Create getter and setter for the UserProfile instance
Fill the value in the user-profile (you will fetch that from your DB call)
when your action will send back the response, S2 will place the user-profile instance on top of Value stack and we can access its properties using S2 tags like
<s:textfield name="user_name" value="%{name}"/>
<s:textfield name="user_age" value="%{age}"/>
here name and age are the properties of your user-profile.param in your redirectAction configuration is being used to provide parameters to the result, for more information about what parameters do please read official document.
redirect-action-result
.
Ya i got your question like this,
what is the exact meaning of param tag?
param tag means:
Struts 2 “param” tag is used to parametrize other tags. However, when you declared the “param” tag, the “parameter value” can be define in two ways :
“value” attribute
Text between the start and end of “param” tag.
For Example:
<param name="fruit">Banana</param>
<param name="fruit" value="Banana"/>
In Your example the 1st case i think
Here see this web site it is present complete structure...
http://www.mkyong.com/struts2/struts-2-param-tag-example/
Currently I am having a page with a small content need to be refreshed frequently.
For example:
The jsp content is
Chapter 1 :
section abc:
section def:
section ghi:
Assuming I have a class Chapter and its sections are parameters in it
class Chapter{
Section abc;
Section def;
Section ghi;
}
I am using spring mvc, I am adding the following models
model.addAttribute("chapter", chapter);
model.addAttribute("abc", chapter.getAbc());
model.addAttribute("def", chapter.getDef());
model.addAttribute("ghi", chapter.getGhi());
While calling the main page initially I can load the individual sections by using the jsp:includes , while updating them independently I shall add that particular model to that particular jsp page and update it using ajax.
This works fine.
But
The question is,
How can I change the design so that can I manage the whole with just
model.addAttribute("chapter", chapter);
so that I can use the chapter object to get the abc,def,ghi values instead of explicitly passing them .
The problem is I am not able to pass the individual objects to the included jsps from the chapter object like ..
<jsp:include page="abc.jsp" >
<jsp:param name="abc" value="${ chapter.abc}"/>
</jsp:include>
this is not possible. as I can pass only strings
small problem , long description .. hope I made my point.
You can only pass Strings as request parameters, but you can set any kind of object as request attributes. Request scope (not page scope) beans should also work.
I'm using Spring MVC for my web application. I'm implementing the file upload functionality. Following the tutorial, I was able to send the uploaded file to server through submit action of input type of "file". Then I parsed the uploaded xls file at server side and need to send parsed data (3 lists of custom objects) back to the same form to display. I sent the data back through ModelAttribute.
However, my problem now is that on the client side, I need to use those lists of custom objects in my javascript, but I can only retrieve each field of the custom objects through jstl tag library but I cannot get those custom objects in my javascript where I need them for other logic implementation.
Then I have tried an Ajax file upload plug-in because ajax call can return JSON response which objects can be used in Javascript. But cannot get the plug-in work properly.
I have been stuck on this problem for several days>.< Can anybody help on this? Either a solution on using ModelAttribute in Javascript or a Ajax call solution is ok. Thank you very much!!!
Is there any reason why you can't simply "flatten" your model objects into HTML and then access them from Javascript using the DOM API?
You said you return 3 lists of custom objects. So how about for each list, you build up a (hidden) HTML table, for example if you have a list of Person objects in a ModelAttribute called people:
<table id="people-table">
<c:forEach var="person" items="${people}">
<tr id="${person.id}>
<td class="person-name">${person.name}</td>
<td class="person-age">${person.age}</td>
<td class="person-height">${person.height}</td>
</tr>
</c:forEach>
</table>
Now in your Javascript, you iterate over the rows in people-table, doing whatever you need to do - for example using jQuery:
$("#people-table tr").each(
var personId = $(this).attr("id");
var personName = $(this).find("td.person-name").text();
// etc, etc
// Do something with these as required
);
It's possibly not the most elegant solution but it's easy to debug at least - you can always just inspect the table with Firebug etc to see if the data is correct, and from there you'll know whether to continue debugging the server-side or in the Javascript.
This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 6 years ago.
Up until now, I have always been using JSP to display pages. When a user request for a page such as "Add Item", I will load all Item Category in an Array List and display them as options in select box like this:
<select name="category>
<%
ArrayList<Category> categories = (ArrayList<Category>) request.getAttribute("categories");
for (Category c : data) {
%>
<option value="<%= c.getId() %>"><%= c.getName() %></option>
<%
}
%>
</select>
From the book "JavaServer Faces 2.0, The Complete Reference", I learnt that: "JSF enforces clean Model-View-Controller separation by disallowing the inclusion of Java code in markup pages". Hence, I'd be very grateful if someone could show me how I can handle the above task using JSF since I cannot use Java code as I have always done anymore.
Best regards,
James Tran
JSF 2.0 uses Facelets as the templating method, which in a nutshell is XHTML with some additional elements.
While technically you can perform method calls from Facelets, in general the idea is to access a JavaBean with proper geter/setter methods to perform your data moving. You can accomplish this as the below segment of code shows:
<h:selectOneMenu value="#{backingBean.selectedCategory}">
<f:selectItems value="#{backingBean.categoryList}"/>
</h:selectOneMenu>
On the bean side of things, you want to expose a bean to JSF using either faces-config (which is largely discouraged) or a mechanism such as CDI or the Managed Bean infrastructure. I highly recommend you look into using SEAM if you go the CDI route, as it will unify the (currently really strangely disparate) Managed Bean and CDI frameworks, so you can use JSF scopes in CDI, and have CDI beans available in JSF scopes.
#ManagedBean(name="backingBean")
#ViewScoped
public class MyJavaBackingBean {
#ManagedProperty("#{param.categories}")
protected List<String> categoryList
public void setSelectedCategory(String value) {
this.selectedCategory = value;
}
public String getSelectedCategory() {
return this.property;
}
...
}
You can also make the getters do lazy initialization of your values (for pulling categoryList from a database for example), and use some other JSF annotations to do various initialization tasks.
You can also code action methods which return a String representing the JSF action (this gets coded into your faces-context.xml file) to take after returning. Phase listeners on the backing bean can also be called at various stages of page rendering, validation and submission, getting you very fine grained control.
categoryList in the above example is not limited to basic types of course, and <f:selectItems> also has some syntax for writing out the textual version of your select items, so you can make some quite complex expressions to display each item in a friendly way.
Create a bean and make it known with e.g. #Named so you can refer to it from your JSF script. Then give that bean a method returning the data you want to show, and invoke that method from your JSF script in a location where that data is expected e.g. a loop construct.
Store the data you want to display in a Java list, and expose that list as a property of a backing bean. The use the appropriate JSF tag to display that property.
In JSF 2.0 you can include the tag h:selectOneMenu in which you get the value where you store the item value selected. The value in f:selectItems could be a collection of any object the most of times SelectItem in this object your declare value object and the label to display.
<h:selectOneMenu value="#{backingBean.selectedvalue}">
<f:selectItems value="#{backingBean.List}"/> </h:selectOneMenu>
if you required values and labels of another object in you must declare
<h:selectOneMenu value="#{backingBean.selectedvalue}">
<f:selectItems value="#{backingBean.ListCar}" var="car" itemLabel="#{car.model}" itemValue="#{car.modelId}"/>
</h:selectOneMenu>
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!