How to access environment variables from JSP page - java

How can I access environment variables from a JSP page? Does one of the implicit objects give access to them? I couldn't find an example addressing this specific issue. Ideally I'm looking for something like:
<c:set var="where" value="${myEnvironment.machineName}">

You can read the properties file at the server start-up using ServletContextListener and store it as application scoped attribute to access it from anywhere in the application.
Steps to follow:
.properties:
machineName=xyz
web.xml:
<listener>
<listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>
AppServletContextListener.java:
public class AppServletContextListener implements ServletContextListener {
private static Properties properties = new Properties();
static {
// load properties file
try {
// absolute path on server outside the war
// where properties files are stored
String absolutePath = ..;
File file = new File(absolutePath);
properties.load(new FileInputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().
setAttribute("myEnvironment", properties);
}
}
JSP:
Then you can just treat it as Map in EL.
${myEnvironment['machineName']}
or
${myEnvironment.machineName}
Read more about JSTL Core c:set Tag
The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.
The <c:set> tag has following attributes:
If target is specified, property must also be specified.
Read more about it HERE
If you are looking for sample code then find it here. Please find it at below posts. It might help you.
Acces value between two jsp with jstl
JSP - Standard Tag Library (JSTL) Tutorial
More samples on other scopes.
<%-- Set scoped variables --%>
<c:set var="para" value="${41+1}" scope="page" />
<c:set var="para" value="${41+1}" scope="request" />
<c:set var="para" value="${41+1}" scope="session" />
<c:set var="para" value="${41+1}" scope="application" />
<%-- Print the values --%>
<c:out value="${pageScope.para}" />
<c:out value="${requestScope.para}" />
<c:out value="${sessionScope.para}" />
<c:out value="${applicationScope.para}" />
In your case you have set an attribute where in default page scope.

Related

Java JSP Using Include with Variable Parameters

I'm trying to pass a parameter to the jsp file that I am including in my main jsp. From what I've seen online the way to do this using c:set
approot/index.jsp
<c:set var="Arg01" value="Argument01"/>
<jsp:include page="include/other.jsp">
<jsp:param name="myArg01" value="${Arg01}"/>
<jsp:param name="myArg02" value="Argument02"/>
</jsp:include>
Although when I try to use the variables in the included jsp page only the one argument seems to be coming through (the second one which is not using c:set)
approot/include/other.jsp
<!-- this doesn't work -->
<p>${param.myArg01}</p>
<!-- this does -->
<p>${param.myArg02}</p>
Nothing crashes but I can see that myArg01 is blank
This way of getting around it is probably awful but it's the only way I could find to get around the issue.
I used a different kind of include in my main JSP
public static String myArg01 = "Argument01";
public static String myArg02 = "Argument02";
<%# include file="include/other.jsp" %>
Then I could reference the variables directly inside the included JSP file
<p><%= myArg01 %></p>
<p><%= myArg02 %></p>

jsp pass bean parameter into scriplet function

On my JSP page I import a java class as
<%#page import="org.model.MyConstants"%>
In the MyConstants class I have a public function
public static String getBookTypeName(int bookTypeId){
//lots of if's based on id
String bookName = 'Fantasy';
return bookName;
}
Now from my JSP page I am trying to call this function passing in a request bean value as the parameter.
Essentially one property of my bean is an integer which I used to display, now I want to display the String that goes along with it but want to do so in a way where I dont need to modify the bean and can just use my MyConstants method to get the string.
I have been outputting my bean value before using
<bean:write name="BookNotifyForm" property="bookTypeId" />
I have been able to use scriplets in the past but have never had to pass a bean value into it.
<c:out value="<%=MyConstants.SOME_STRING_OUTPUT %>" />
I think I have the idea down but the syntax is what is killing me. I believe I should be able to use c:set to store the bean variable, and then use c:out calling the method passing in the variable I stored. Something along the lines of....
<c:set var="bookTypeId" value="${BookNotifyForm.bookTypeId}" />
//help with syntax, trying
<c:out value="<%=MyConstants.getBookTypeName(bookTypeId) %>" />
<c:out value="<%=MyConstants.getBookTypeName(${bookTypeId}) %>" />
It must be possible to do something like this !?

JSP class attribute invalid

I am attempting to get to grips with a decent level of JSP quickly to build an interface. I found what seems a good tutorial at this URL.
Reference link
While following the tutorial to the word, on page 35 it covers jsp:getProperty Action. I successfully created the TestBean.java file and it compiled to produce TestBean.class. But what I found was that my Tomcat's webapps directory did not contain a folder named "WEB-INF" and so no directory "webapps\WEB-INF\classes\action" so I added the "WEB-INF\classes\action" myself. Then when I run the main.jsp file the browser states the following error
"The value for the useBean class attribute action.TestBean is invalid"
What I am doing wrong?
Here is the Java "TestBean.class" code;
/* File: TestBean.java */
package action;
public class TestBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
And here is the JSP "main.jsp" code
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="action.TestBean" />
<jsp:setProperty name="test" property="message" value="Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name="test" property="message" />
</center>
</body>
</html>
I am assuming you are working on eclipse.
If Web-INF is not created that means you are not working in a dynamic web project.
Go to NEW in eclipse. Go to Dynamic web project. It will create all you folders needed for a JSP/WEB project itself including Web-INF. This will stream line the process.
Other option is place your class files in required folder which is quite tedious job. Hope it helps.

How JSP Expression sets bean property of type Object

I have a jsp file and a bean file. I learnt how primitive data types are converted using 'valueOf' method and the bean property is set , however i am still confused how class type values are set. The code below will make the query more clear.
Bean.java :
private Object myObject ;
public Object getMyObject() {
return myObject;
}
public void setMyObject(Object myObject)
{
System.out.println("my object - " + myObject);
File file = (File)myObject;
System.out.println("path - " + file.getPath());
this.myObject = myObject;
}
Index.jsp :
<jsp:useBean id="aBean" class="com.Bean" />
<%
File file = new File("some path");
%>
<jsp:setProperty name="aBean" property="myObject" value="<%= file %>" />
I am quite confused with how the thing value="<%= file %>" works.
Thanks.
File extends Object (like all classes do). So the above is simply compiled by the JSP container to something like
com.Bean aBean = new com.Bean();
File file = new File("some path");
aBean.setMyObect(file);
There's nothing to convert, since a File is an Object.
Note that jsp:useBean and jsp:setProperty are obsolete for a looooong time. You shouldn't use these directives anymore. Use an MVC controller (or at least a self-implemented MVC pattern), and use the JSTL and the JSP EL to access beans created and stored in request attributes by the controller. The view (i.e. the JSP) shouldn't create and populate beans. That's not its job.

Variable refering in two different jsp pages

If i declare a variable in my A.jsp and i am trying to include A.jsp to B.jsp.So my question stands here whether the variable declared in A.jsp is acessable in B.jsp?
Please explain me for both the cases Dynamic include and static include.
When you include a jsp template using <%#page include=""> the source will actually be inserted and compiled into the including file. This is what makes you able to use variables declared in the parent file.
When doing a "dynamic" include it will use RequestDispatcher.include which will invoke the calling page as a new Servlet. This makes you unable to use declared variables.
I would recommend you to pass variables on the request scope using request.setAttribute("name", obj); when doing this
You can't pass server-side parameters using the <%# include %> directive. This directive does a static include. The contents of the included file are statically inserted into the including page. That is, during translation time from jsp to servlet.
Use the <jsp:include> tag instead, it is processed at runtime, and with it you can pass parameters using <jsp:param>.
For instance, if you have a.jsp with
<jsp:include page="b.jsp" />
<jsp:param name="param1" value="value1" />
<jsp:param name="param2" value="value2" />
</jsp:include>
You can get those parameters as request parameters in b.jsp
<% String v = request.getParameter("param1"); %>
Take into account you can still get request parameters available on a.jsp in b.jsp.

Categories