spring mvc addAttribute to model, how to get it from jsp javascript - spring

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.

Related

Bind a form object to a ModelAttribute with a prefix?

I have a legacy application that contains lots of forms from a previous framework that required a prefix for the entity. For example, an Item object with a name would have a form field of:
<input name="item.name" ... />
In my spring controller, I use a ModelAttribute as normal:
#ModelAttribute Item item
But the binding fails because spring does not expect the prefix for the item. Is there some way I can tell spring to ignore the prefix and bind without having to create a wrapper object or having to change the prefix from every form field?
If you are using jsp as your view, you will also need to add modelAttribute in your form as well, and make sure that you have declared getters for your form fields in Item object. Ex: getName()
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form id="new-item-form"
method="post"
modelAttribute="item" ...>
<input name="item.name" ... />
</form:form>
If you're using Thymeleaf , then you have to add its XML namespace to your html, and then you can access model attributes in views with Thymeleaf using Spring EL as follows:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
...
<p th:text="${item.name}">Name</p>
...
</html>

How to do numeric comparison but return false if can't parse to number?

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.

Servlet to jsp communication best practice

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?

How to get sessionScope attributes on JSTL?

The task is to retrieve parameters from session via JSTL. The session parameter name is "programId" .
I tried:
<c:if test="${sessionScope.programId != null}" >
please execute
</c:if>
Then I tried:
<c:if test="${sessionScope:programId != null}" > please execute </c:if>
Here I get: The function applicationScope:programId is undefined
On top I have:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Oracle has in examples:
http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL5.html
<c:if test="${applicationScope:booklist == null}" >
<c:import url="${initParam.booksURL}" var="xml" />
<x:parse doc="${xml}" var="booklist" scope="application" />
</c:if>
where applicationScope can be swapped by sessionScope.
again "trivialism" complexity drives me nuts. Why corp. examples never work?
Thank You Guys,
You're reading the wrong tutorial page. The <c:xxx> tags does not belong to the JSTL XML taglib which supports XPath syntax. Instead, it belongs to the JSTL Core taglib for which the proper tutorial page is here.
You need to use the normal ${bean.property} notation instead.
<c:if test="${applicationScope.booklist == null}">
<c:import url="${initParam.booksURL}" var="xml" />
<x:parse doc="${xml}" var="booklist" scope="application" />
</c:if>
In normal EL (not XPath!) syntax, the : identifies the start of an EL function. See also the JSTL Functions taglib for several EL function examples for which the tutorial page is here.
See also:
Our JSTL tag wiki page
Our EL tag wiki page
I don't find in your code you have set your variable programID somewhere in your SessionScope using EL something like the one shown below.
<c:set var="programID" value="SomeValue" scope="session"/>
If you indeed didn't set that variable, try setting it first like the above then try the following.
<c:if test="${sessionScope:programId != null}" > please execute </c:if>
It should work.
if you have set session in your controller
session.setAttribute("programID",someValue);
then you should try this
${sessionScope.programID} in your jsp
which is part of jstl core library
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
and if you are getting exception
"${sessionScope:programId != null}" contains invalid expression(s): javax.el.ELException: Failed to parse the expression [${sessionScope:programId != null}]
include jasper.jar in your lib folder
java brushup for basic concepts of java

MVC Multiple ViewPage items in aspx required

I need to pass in 2 objects to a page to access Model.NewsItems and Model.Links
(the first is a class of news item objects with heading, content etc and the Links are a set of strings for hyperlink depending on whether the system is up or down.
This is the page declaration
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Tolling.Models.NewsItems>" %>
If I refer to Model.Items - I am fine.
However, if I refer to Model.HyperLink1, I am not.
How can you pass in multiple objects into the page?
I have tried importing both namespaces without success - i.e.
<%# Import Namespace="Tolling.Models.News" %>
<%# Import Namespace="Tolling.Models.HyperLinks" %>
Create a ViewModel class that contains both of your model collections and then pass that too the view:
Sample Controller:
var myNewModel = new MyNewModel()
{
NewsItems = new List<NewItem>(),
HyperLinks = new List<HyperLink>()
}
return View(myNewModel);
View page declaration:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyNewModel>" %>
Then you can access them in your view with your new ViewModels properties:
<%= Model.NewsItems %>
<%= Model.Hyperlinks %>
You can pass extra data into the View by using ViewData, TempData, Session or Cache. I'd suggest you use ViewData. As described by MSDN:
Gets or sets a dictionary that
contains data to pass between the
controller and the view.

Resources