I am learning JSF and was trying to implement a small exercise on EL (with JSF page and JSP2). i found a strange behavior and completely clueless of the reason behind it. Please find my code below and scenario
Backing bean class
package task2;
public class FavortiteColors_1 {
private String firstName = "Tarun";
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Below is the snapshot of faces config xml which is required for this example
Faces config.xml
<managed-bean>
<managed-bean-name>favColors_1</managed-bean-name>
<managed-bean-class>task2.FavortiteColors_1</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
JSP Code
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Accessing Bean Properties</TITLE>
<LINK REL="STYLESHEET"
HREF="./css/styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<tr><B>Accessing Bean Properties using JSP 2 EL: version 1<B></tr>
<% System.out.println("Accessing Bean Properties using JSP 2 EL: version 1"); %>
<OL>
<LI>First Name ${favColors.firstName}
</OL>
<BR><BR>
<tr><B>Accessing Bean Properties using JSF 1.1 EL <B></tr>
<% System.out.println("Accessing Bean Properties using JSF 1.1 EL"); %>
<UL>
<LI>First Name = <h:outputText
value="#{favColors.firstName}"/>
</UL>
<BR><BR>
<tr><B>Accessing Bean Properties using JSF 1.1 with JSP2EL: version 2<B></tr>
<% System.out.println("Accessing Bean Properties using JSF 1.1 with JSP2EL: version 2"); %>
<OL>
<LI>First Name ${favColors.firstName}
</OL>
<BR><BR><BR>
<P>
</f:view>
*The output is as below: *
Accessing Bean Properties using JSP 2 EL: version 1
First Name
Accessing Bean Properties using JSF 1.1 EL
First Name = Tarun
Accessing Bean Properties using JSF 1.1 with JSP2EL: version 2
First Name Tarun
With this the background below are my questions
Q1: I am trying to fetch a string from the backing bean using JSF 1 El and JSP 2 EL. I am trying to fetch the name using three expressions. First and 3rd one are JSP2 EL and the funny thing is that the first one is not able to fetch the name where as the third one (with the exactly same syntax is able to fetch the name. Using the SOP, I am getting the that first expression is unable to trigger the backing bean whereas the second and third one are doing it successfully. Why is such a scenario happening? Looking forward for your explanation.
Regards Tarun
Related
I was trying to write a JSP page. But i have read many times that source code within JSP page is a bad practice. So then I tried to write a different class in the same package and call it within that JSP page.
Here's the JSP code:
<jsp:useBean id="link" scope="application" class = "tms.TestJava" />
<%
TestJava t=new TestJava();
t.test();
%>
and here's the class code:
public class TestJava {
public void test() throws IOException
{
System.out.println("sdds");
}
}
I have imported the class into JSP page.
Now the problem is that when I use System.out.println in the class (test method), it gets printed onto the console and I want it to print it to the JSP page. How can I achieve this? Is there a seperate method? Do I have to make the class a servlet?
Thanks!
Try using a tag library: JSTL
Specifically:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:out> Tag Example</title>
</head>
<body>
<c:out value="${'<tag> , &'}"/>
</body>
</html>
Or better yet, since you are using JavaBeans already, refactor so that you aren't using System.out() anymore. The idea is that you want to display properties of your bean in your page. Consider: JavaBeans So Do something like this:
Java
public class Course{
private String code = "Math";
public String getCode(){
return code;
}
}
Jsp
<jsp:useBean id="course" class="com.javaBeans.Course" />
<jsp:getProperty name="course" property="code"/>
Chiefly, you don't want to just System.out() to a page. The page should be a view of the data of components on the sever which in this case is the bean.
I think you're going about this the wrong way, but here is a possible solution...
<head>
<%# page language="java" import="tms.TestJava"%>
</head>
<body>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
<%=TestJava.getAString()%>
</body>
public String getAString(){
return "<li></li>";
}
If your goal is to build dynamic JSPs, you will probably want to look into JSTL as someone above mentioned, look into defining your own tags, etc. I don't think very much new dev is using scriplet code.
I've read most of the online resources for building a simple "Hello World" app using Java and Struts 2. I understand the simple stuff. My problem is that I'm trying to expand that learning and build a large scale app, and I just don't see how to connect the dots.
Scenario:
I've got three views to begin with: Home.jsp, MyAccount.jsp, Contact.jsp. Each has the following HTML:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
...
</head>
<body>
<!-- If logged in, says "hello <s:property name="username">"
Else displays link to .show() #loginPane -->
<div id="accountHeader">...</div>
<!-- Displays <s:textfield> tags and <s:submit> tag to accept username and password -->
<div id="loginPane" style="display: none">...</div>
<header>...</header>
<nav>...</nav>
<!-- Displays view-specific content that includes Struts 2 tags -->
<div id="content">...</div>
<footer>...</footer>
</body>
</html>
So, obviously there is a lot of code common to each view (anything not in #content div).
How do I architect these views for code reuse?
What I've tried:
Placing common code in common.js and using jQuery .html() calls to populate <div>s. [Doesn't work because jQuery cannot generate code with <s:> tags.]
Using only one .jsp view file and placing view-specific code in common.js to be generated with jQuery .html() calls. [Doesn't work for the same reason -- jQuery cannot generate code with <s:> tags.]
Placing all view components in .jspf files and loading each with jQuery .load() calls from common.js. [Doesn't work -- I'm guessing the .jspf files need the Struts 2 <%taglib ...%> included in each, but jQuery .load() treats the <%taglib ...%> as text to be displayed in the <div>... and also fails to properly generate the <s:> tags.]
What is the proper way to do this? How do I architect my view(s) for code reuse?
My apologies if this isn't the proper forum to ask for architecture help, but I'm really struggling here... Perhaps point me to a more appropriate forum or an online tutorial that addresses this type of architecture?
Thanks in advance!
I've used several methods to accomplish this type of re-use of code including Tiles and tooling around with Sitemesh and other template frameworks. What I've found is that, much as Steven Benitez, in the end I preferred to use JSP taglibs, native Struts2 taglibs, and JSTL to essentially build out my own templating routines. The main reason I prefer this is that there tends to be less overhead and it's been a lot easier to maintain and extend in the long run.
Generally What I do is define my base template, index.jsp for example, and then in each independent Struts controller class I will define what page fragment is used. I try to split my controllers up in such a way that each page or function is handled by a single controller and I implement the Preparable interface. This way I can set a parameter for the page to reference. Sometimes I set it as a variable in the controller class, sometimes a sessions variable depending on what type of stating I need for the application.
Once I have a variable with the page to reference, I can just use a JSTL import or Struts include tag to load the page fragment.
The controller class would look something like this:
#Results({
#Result(name = "success", location = "/WEB-INF/content/index.jsp")
})
public class IndexController extends RestActionSupport implements Preparable{
private String page;
private String pageTitle;
#Override
public void prepare() throws Exception {
page = "home";
pageTitle= "My Home Page";
}
...
}
And then the JSP would look something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title> ${pageTitle}</title>
</head>
<body>
<c:import url="${page}.jsp" />
</body>
</html>
EDIT: Fragment page example:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<h1>Welcome Home!</h1>
</div>
<script type='text/javascript'>
$(document).ready(function() {
// page specific scripting if needed
);
</script>
You can encapsulate common template code in JSP tag files, as explained in this answer or you can also use decorator frameworks such as Tiles or SiteMesh to do this.
Personally, I prefer JSP tag files. Do not attempt to write out HTML with jQuery or to put all of your code into a single JSP.
i am trying to include a java code into the value of the inputText in my jsf page but an error occur
according to tld or attribute directive in tag file attribute value
does not accept any expressions
Here is my jsf page.
<%# page contentType="text/html" %>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="html" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="core" %>
<%# page language="java" %>
<core:view>
<html:form>
<html:outputLabel value="Informations " style="FONT-SIZE: xx-large;"/>
<br />
<br />
<%
final String property=System.getProperty("jboss.server.home.dir");
%>
<html:outputLabel value="RĂ©pertoire de configuration: " />
<html:inputText value='<%=property%>'/>
</html:form>
</core:view>
Doesn ' t work either with double quote or nothing
How to resolve this problem please ?
Thank you very much
The problem is with this line of code:
<html:inputText value='<%=property%>'/>
JSF uses Expression Language to populate/read values to/from a JavaBean. You will have to create a POJO action (called ManagedBean) with a variable property and link it there.
E.g.
public class ConfigurationAction {
private String property = System.getProperty("jboss.server.home.dir");
/**NOTE: MUST create a getter and setter. **/
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
Don't forget to map the ManagedBean. In JBoss Seam, you will just add an #Name annotation above the class like, #Name("configurationAction").
Finally, render this in JSF with Expression Language (EL)
<html:inputText value="#{configurationAction.property}"/>
Where configurationAction is the name of your ManagedBean, and property is the instance of the ManagedBean.
How do I access a JSP tag's attribute value within a JSTL tag? In the code below, I would like to access the url attribute and test if it's empty. I am using the JSTL 1.0 specification.
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%# attribute name="url" required="false"%>
<c:if test="${!empty url}">
...
</c:if>
If you're creating tag files, then you're using at least JSP 2.0 - which means you should be using at least JSTL 1.1. At any rate, the attribute directive should create a page-scoped var with the same name as its name attribute (unless it's optional and not provided). So, can you provide any more detail on the errors and/or output you're observing?
I've experienced rather strange behavior of JSTL forEach tag.
I have some bean called SessionBean:
public class SessionBean {
private Collection<MyObject> objects;
public Collection<MyObject> getObjects() {return objects;}
...
}
And a simple JSP page like that:
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%#taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<f:view>
<h:form>
<c:forEach var="myObject" items="#{SessionBean.objects}">
<h:outputText value="#{myObject}" /> <br />
</c:forEach>
</h:form>
</f:view>
</body>
And, it doesn't work. Exeption thrown is
javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:255)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:219)
....
Why?
And then I change items="#{SessionBean.objects}" to items="${SessionBean.objects}", and there's no exception. Except for MyObjects aren't printed.
Then, I make the same change to <h:outputText value="#{myObject}" />, and it's invalid value for this attribute.
Finally, replacing JSF outputText tag with just ${myObject} works as expected.
Could somebody explain, what happens here on each phase, please?
U: SessionBean is managed by JSF, and surely was created, for it performs some actions in the header.
RESOLUTION: The problem proved to be due to incompatibility between JSTL and JSF in J2EE 1.4. Switching to J2EE 5 made the first variant work just fine.
Thanks!
This article explains the difference between the unified EL and the EL. Here is a snippet
Evaluation of EL
Evaluation of EL is categorized as immediate evaluation and deferred evaluation. Immediate evaluation means a JSP page evaluates the expression when the page is rendered. With immediate evaluation, all values are always read-only. JSP EL expressions take the form of ${imExpr}. JSP expressions are evaluated immediately.
Deferred evaluation means that the technology using the unified EL takes over the responsibility of evaluating the expression from the JSP engine and evaluates the expression at the appropriate time during the page lifecycle. The EL takes control from the JSP container to evaluate the expression at the appropriate time. JSF EL expressions take the form of #{defExpr}. JSF expressions work in this way.
The following example shows a JSF inputText tag, which represents a text field component into which a user enters a value. The inputText tag's value attribute references an expression that points to the name property of the book bean.
<h:inputText id="name" value="#{student.name}"/>
For an initial request of the page containing this tag, the JSF implementation evaluates the #{student.name} expression during the "render response" phase of the lifecycle. During this phase, the expression merely accesses the value of quantity from the book bean, as is done in immediate evaluation.
For a postback, the implementation evaluates the expression during the "apply request values," "process validations," and "update model" phases, during which the value is retrieved from the request, validated, and propagated to the book bean.
I am wondering if the problem is from the fact that an instance of SessionBean was not created?
Try this:
<jsp:useBean class="packagename.SessionBean" id="sb"/>
<c:forEach var="myObject" items="${sb.objects}">
<h:outputText value="${myObject}" /> <br />
</c:forEach>
[Update] I wonder if this article might help then. It explains how the two EL's work together.