I would like to have a JSTL file of "constants" and reference them in other files.
e.g.
constants.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="colour" value="blue"/>
<c:set var="car">Audi</c:set>
Other file:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:import url="constants.jsp"/>
<p>I drive an ${car} which is ${colour}</p>
The code above (obviously) does not work. How can I get something similar to work?
Bonus points if I can use namespaces as well.
You could use an include directive:
<%#include file="/constants.jsp" %>
Or you could use a dynamic include, but then the variables would have to be stored in the request, rather than the page scope:
<jsp:include page="/constants.jsp" />
<c:set var="colour" value="blue" scope="request"/>
<c:set var="car" scope="request">Audi</c:set>
But the best way would probably be to put all these constants in an object, and store this object in the request (or session, or application) from a servlet or filter:
private class Constants {
private String color = "blue";
private String car = "Audi";
public String getColor() {
return color;
}
public String getCar() {
return car;
}
}
...
request.setAttribute("constants", new Constants());
...
<p>I drive an ${constants.car} which is ${constants.color}</p>
Related
i am new to Spring Mvc,so i have this simple question below
Code1:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hello","message",str);
}
In hello.jsp View Page ,when i print str then i get result as ${message}
code2:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hellopage","message",str);
}
but in hellopage.jsp i get result as Be happy!!!!!
so why above code1 does not print str string?
below is my view page jsp code and it is same for both hello.jsp and hellopage.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
${message}
</body>
</html>
In hello.jsp put this expression <%# page isELIgnored="false"%> at the top. Sometimes expression language automatically off for page
The EL expression doesn't get evaluated? That can have one or more of the following causes:
Application server in question doesn't support JSP 2.0.
The web.xml is not declared as Servlet 2.4 or higher.
The #page is configured with isELIgnored=true.
The web.xml is configured with true in .
In your case it looks like case no 3. Try to put isElIgnored=false in your jsp file.
Broadly: I want the test in a JSTL Core <c:when> tag to return false if either:
- A variable can't be parsed as a number; or
- Comparison of the same variable to a number-literal is false.
I know that the variable won't be parsable as a number in some cases; this should not cause an error.
Details of the use-case follow...
I have the following in a JSP file on a WebSphere Portal v7 server. This JSP is rendered by a Web Content portlet configured to use an IBM Web Content Manager JSP component.
<%# page session="false" buffer="none" %>
<%# page trimDirectiveWhitespaces="true" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v7.0/json" prefix="json" %>
<%# taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v7.0/portal-fmt" prefix="portal-fmt" %>
<%# taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v7.0/portal-core" prefix="portal-core" %>
<%# taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v7.0/portal-navigation" prefix="portal-navigation" %>
<%# page import="com.isw.portal.theme.SideNav" %> <%!
SideNav iswSideNav=SideNav.getInstance();
%>
<portal-navigation:navigation startLevel="${navTabsLevel}" stopLevel="${navTabsLevel+3}">
<%=iswSideNav.getNavHTML(wpsNavModel,wpsSelectionModel,request,response) %>
</portal-navigation:navigation>
This works consistently on normal page views.
However, when the Portal Search collection is being updated (which occurs automatically once every 6 hours and takes about 2 minutes), this JSP produces several exceptions every second.
The exceptions are always the same two repeated as below. The second exception always includes a stack trace, which I've omitted except for the line stating the NumberFormatException message.
NavigationTag E com.ibm.wps.engine.tags.NavigationTag setStartLevel EJPEJ0027E: StartLevel less than 1 is ignored.
NavigationTag E com.ibm.wps.engine.tags.NavigationTag setStartLevel EJPEJ0026E: StartLevel is not a valid number.
java.lang.NumberFormatException: For input string: ""
As these exceptions don't seem to cause any functional problems, I want to wrap the <portal-navigation:navigation> element inside a <c:choose> element, such that the navigation is rendered when navTabsLevel is parsable as a number and that number is >= 1, but otherwise show a 1-line warning.
How do I do this without causing a "string cannot be parsed to number" error?
You can use <c:catch> for that.
<c:catch var="exception">
<portal-navigation:navigation startLevel="${navTabsLevel}" ... />
</c:catch>
<c:if test="${not empty exception}">
Handle fail.
</c:if>
Alternatively, and better, create a custom EL function like matches(), isNumber(), etc.
<c:choose>
<c:when test="${my:isNumber(navTabsLevel)}">
<portal-navigation:navigation startLevel="${navTabsLevel}" ... />
</c:when>
<c:otherwise>
Handle fail.
</c:otherwise>
</c:choose>
There's at least nothing available in standard JSTL functions set for that.
I'm learning how to write java servlets and jsp pages on google app engine. I'm attempting to use an MVC model but I'm not sure if I'm doing it right. Currently, I have a servlet that is called when a page is accessed. The servlet does all the processing and creates a HomePageViewModel object that is forwarded to the jsp like this:
// Do processing here
// ...
HomePageViewModel viewModel = new HomePageViewModel();
req.setAttribute("viewModel", viewModel);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/home.jsp");
reqDispatcher.forward(req, resp);
Over on the jsp side, I have something like this:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="viewmodels.HomePageViewModel" %>
<%
HomePageViewModel viewModel = (HomePageViewModel) request.getAttribute("viewModel");
pageContext.setAttribute("viewModel", viewModel);
%>
<html>
<body>
<% out.println(((HomePageViewModel)pageContext.getAttribute("viewModel")).Test); %>
</body>
</html>
So my question is two fold. First, is this a reasonable way to do things for a small webapp? This is just a small project for a class I'm taking. And second, in the jsp file, is there a better way to access the viewmodel data?
If you adhere the Javabeans spec (i.e. use private properties with public getters/setters),
public class HomePageViewModel {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
then you can just use EL (Expression Language) to access the data.
<%# page pageEncoding="UTF-8" %>
<html>
<body>
${viewModel.test}
</body>
</html>
See also:
Our Servlets wiki page
Our JSP wiki page
Our EL wiki page
How to avoid Java code in JSP files?
Got a homework assignment that is giving me problems.... Its modifying a JSF project with two pages and a bean to fit MVC2 by adding two more pages and a controller servlet and another bean for the two additional pages. the new main page forwards to either the second new page or the old first page. My issue is response.getParameter() always results in null.
<%#page session="false" import="java.util.Iterator"%>
<%#taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%#taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<jsp:useBean id="status" scope="request" class="JSFRegistration.Status" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<% if (status!=null && !status.isSuccessful()){%>
<font color="red">Processing errors:
<ul><%Iterator errors=status.getExceptions();
while (errors.hasNext()){
Exception e = (Exception) errors.next();%>
<li><%= e.getMessage()%><%}%></ul></font><%}%>
<form action="LoginServlet" method="POST">
<% String username = request.getParameter("username");
if (username==null) username="";%>
<input type="text" name="usernameTF" value="<%=username%>" />
<% String password = request.getParameter("password");
if (password==null) password="";%>
<input type="password" name="passwordTF" value="<%=password%>" />
<input type="submit" value="Login" />
</form>
</body>
</html>
this is basically a direct copy from our book but the fields I need for the new main page. Same for the controller servlet, a direct copy except only contains the fields I need.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher view = null;
Status status = new Status();
request.setAttribute("status", status);
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username==null || username.length()==0)
status.addException(new Exception("Please enter username"));
if (password==null)
status.addException(new Exception("Please enter password"));
if (!status.isSuccessful()){
view = request.getRequestDispatcher("Login.jsp");
//view.forward(request, response);
}
else
try{
request.setAttribute("username", username);
request.setAttribute("password", password);
view = request.getRequestDispatcher("Registration.jsp");
} catch (Exception e) {
status.addException(new Exception("Error"));
view = request.getRequestDispatcher("Login.jsp");
}
view.forward(request, response);
}
and the Status class, again a direct copy from the book.
public class Status {
private ArrayList exceptions;
public Status(){
exceptions = new ArrayList();
}
public void addException(Exception exception) {
exceptions.add(exception);
}
public boolean isSuccessful(){
return (exceptions.isEmpty());
}
public Iterator getExceptions(){
return exceptions.iterator();
}
regardless of what is typed into the two boxes, stepping through a debug shows the values not getting passed to the parameters. I get the created exceptions printed above the screen for both fields if both have text, if only one has text and when both are empty.
Your request parameter names do not match the input field names. You've assigned the input fields a name of usernameTF and passwordTF. They are then available by exactly those names as request parameter, but you're attempting to get them using the names username and password. So you need either to fix the input field names, or the request parameter names so that they match each other.
By the way, why falling back from a modern MVC framework like JSF to awkward 90's style JSP with mingled business code? Is that really what the homework assignment is asking you? Also the HTML <font> element is deprecated since 1998. Where did you learn about it? Is the quality of the course really good?
i have a controller with a model which i do addAttribute("show", "yes");
how do I retrieve this value inside javascript?...assuming I have jstl
Inserting it in a javasript would be the same as showing it in the html code of the jsp.
Try to do this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
Show value is <c:out value="${show}"/>
if you can see the value in the JSP then JSTL is working. In any other case there may be another problem. For example that your configuration ignores EL. You can add this at the top of your JSP:
<%# page isELIgnored="false" %>
When you see the value in the HTML code then the JSTL is working in that case you can use it in Javascript. As your setting the value for tha variable "show" to yes it cannot be used as a boolean value (because it should be true or false). In this case you should use it as a string adding quotations
<script type="text/javascript">
var showVar = '<c:out value="${show}"/>';
alert("The variable show is "+showVar);
</script>
You can use Firebug to check that your javascript is working and you don't have any error on it.