Checking if a value is contained in an array in JSP - java

I have an if statement like so:
<c:if test="${id == '1' || id == '2' || id == '3' || id == '4'}">
and I'm wondering if there is a way that I can simplify this by checking if id is contained within an array/list/set, sort of like
<c:if test="${id isContainedIn {'1','2','3','4'}}">
Obviously this isn't correct, but it demonstrates what I am looking for. Is there anything similar to this? Thanks!

If you can create a String that contains your list, then you could use something like the following code.
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>
<%
pageContext.setAttribute("listString", "1234");
%>
<c:set var="id" value="3"/>
<c:if test='${fn:contains(listString, id)}'>
Yes id is contained
</c:if>

You can do something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.

Related

How to change Map value dynamically in JSTL

One of our application built using Spring MVC + JSP.
Please refer below JSP.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page import="java.util.ArrayList"%>
<%# page import="java.util.HashMap"%>
<%
ArrayList<HashMap<String, String>> listOfMap = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < 3; i++) {
map = new HashMap<String, String>();
map.put("key1", "value1" + i);
map.put("key2", "value2" + i);
listOfMap.add(map);
}
request.setAttribute("listOfMap", listOfMap);
%>
<html>
<body>
<c:forEach items="${listOfMap}" var="maps">
<c:forEach items="${maps}" var="mapItem">
${mapItem.key} ${mapItem.value} <br />
</c:forEach>
</c:forEach>
</body>
</html>
As you can see in this jsp that i am trying to iterate map and display key and value on page.
But what should be done in case if i want to change the value of mapItem.key and mapItem.value while iterating inside the loop.
So it would like below.
<c:forEach items="${listOfMap}" var="maps">
<c:forEach items="${maps}" var="mapItem">
<!--Basically i would write a code (in scriplet) to prevent cross site scripting here -->
${mapItem.key} ${mapItem.value} <br />
</c:forEach>
</c:forEach>

c:forEach doesn't print map contents in JSP

Disclaimer: I've spent today researching this simple problem inside and out all across stachoverflow and beyond so please bear with me.
I have the following code on JSP:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="com.contrast.db.Manager"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.util.Map"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
Integer age = Integer.valueOf(request.getParameter("age"));
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<%
Manager db = new Manager();
Connection conn = db.getConnection();
if (null == conn) {
out.println("Connection to MySQL failed");
} else {
out.println("Connection to MySQL succeeded");
}
Map<String, Integer> namesAndAge = db.findByAge(age);
%>
<h1>List of users older then <% out.println(age); %></h1>
<% out.println(namesAndAge); %>
<c:forEach items="${namesAndAge}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
</body>
</html>
This code for intents and purposes should print out the contents of the HashMap returned by db.findByAge(age) but it doesn't
Understandably one could assume that HashMap could be empty, but it's not (please see screen shot below)
As you can see the HashMap is not empty but is not working
Any ideas what am I missing?
On the scriplets you declare objects, while in EL expressions what are referenced are attributes in a context (pageContext, request, session or application).
change this line:
Map<String, Integer> namesAndAge = db.findByAge(age);
For this:
request.setAttribute("namesAndAge", db.findByAge(age));

how to change the scriplet to JSTL display string array

how to change the scriplet to JSTL
<%String sentenceArray[] = (String[])request.getAttribute("displaySentenceArray"); %>
<% for (int i=0; i< sentenceArray.length;i++){ %>
<p> The Result IS : <%=sentenceArray[i] %> </p>
<%} %>
I am new to JSTL
Your JSTL should look like this
<c:forEach var="sentence" items="${requestScope.displaySentenceArray}" >
<p> The Result IS :<c:out value="${sentence}"></c:out></p>
</c:forEach>
Here requestScope.displaySentenceArray will get the whole array from request.'sentence'will be a single element of array, <c:forEach> tag will iterate the array and <c:out> will print the element to JSP.

how to add " span " <span> </span> to each words in the arraylist?

I have one arraylist
ArrayList al = new ArrayList();
al.add("tree good has");
al.add("ok go by");
al.add("see good");
al.add("dog");
how to add " span " to each words??? For example:
<li>
<span>tree</span>
<span>good</span>
<span>has</span>
</li>
<li>
<span>ok</span>
<span>go</span>
<span>by</span>
</li>
<li>
<span>see</span>
<span>good</span>
</li>
<li>
<span>dog</span>
</li>
what i tried was:
the result of this statement was wrong. because the result is add " span " to each row , not earch word.
<% for (int i=0; i< al.size();i++){ %>
<li><span><%=al.get(i) %><br></span></li>
<%} %>
how to add " span " to each words???
You need further split each line into words. Find below code -
<% for (int i=0; i< al.size();i++){
%>
<li>
<%
for(int j=0;j<al.get(i).split(" ").length;j++){
%>
<span><%=al.get(j) %><br></span>
<% }%>
</li>
<%}%>
You can use the split method and can add the inner loop to achieve the desired result. it will look like
<% for (int i=0; i< al.size();i++){
String[] splitArray = al.get(i).split();%><li>
<% for (int j=0; j< splitArray.length;j++){ %>
<span><%=splitArray[j] %></span>
<%} %>
</li>
<%} %>
<% for (int i=0; i< HighlightTermList.size();i++){ %>
<li> <%String str=HighlightTermList.get(i); %>
<% String[] splitArray = str.split(" ");
for(int j=0;j<splitArray.length;j++){ %>
<span><%=splitArray[j] %></span>
<%} %>
</li>
<%} %>
I combine two answer together. I worked
You can solve this problem with JSTL. JSTL is better way to using java operations in jsp page. First off all you need to import required libraries to your jsp.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<ul>
<c:forEach items="${al}" var="mWord">
<li>
<c:forEach items="${fn:split(mWord,' ')}" var="word">
<span>${word}</span>
</c:forEach>
</li>
</c:forEach>
</ul>
</body>
</html>
You can learn detailed differences and advantages between JSTL and JSP Scriptlet in this link.

Reused of JSP code

I have lots of JSPs containing code which have statements which could be reused like this select statements, inputs, etc.
Here is a sample of a JSP
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
(needed includes)
<%
ArrayList<Student> studentList = (from database)
%>
<html>
<head>
<title>Students</title>
</head>
<body>
<form>
(other inputs)
...
<select class="combobox">
<%for (Student studentObj:studentList) { %>
<option value="<%=studentObj.getId()">
<%=studentObj.getLastName() %>, <%=studentObj.getFirstName() %>
</option>
<%} %>
</select>
...
(other inputs)
</form>
</body>
</html>
What I did do is make a function as follows. This allows me to be able to pass an object parameter and get html code back.
public static getStudentSelect(ArrayList<Student> studentList) {
String htmlCode = "<select class=\"combobox\">";
for (Student studentObj:studentList) {
htmlCode += "<option value=\"" + studentObj.getId() + "\">" +
studentObj.getLastName() + ", " + studentObj.getFirstName() +
"</option>";
}
htmlCode += "</select>"
return htmlCode;
}
Is there a better way of doing this? Because escaping quotes can get messy.
I can't send objects through jsp includes.
I was thinking of using Gagawa
Please don't use scriptlets in JSP. You should use tag files, JSTL and EL to make your own tag library. This way you can easily pass variables as parameters into the reusable components, unlike with JSP fragments and these are much simpler than writing custom tags, when you're dealing with simple logic like looping or creating a table.
Below is an example based on your sample JSP code in the question.
/WEB-INF/tags/student/select.tag:
<%# taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
<%# attribute name="studentList" required="true" type="java.util.List" %>
<select class="combobox">
<c:forEach var="student" items="${studentList}">
<option value="${student.id}">
<c:out value="${student.lastName}" />,
<c:out value="${student.firstName}" />
</option>
</c:forEach>
</select>
sample.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix=”student” tagdir=”/WEB-INF/tags/student” %>
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
</head>
<body>
<form>
(other inputs)
...
<student:select studentList="${sessionScope.studentList}" />
...
(other inputs)
</form>
</body>
</html>
To avoid escaping issues.
Better try using plain javascript to create html like
var el = document.createElement('select');
el.className = "combobox";
for (Student studentObj:studentList) {
var optel = document.createElement('option');
optel.value = studentObj.getId();
optel.text = studentObj.getLastName() + ", " + studentObj.getFirstName();
el.append(optel);
}
return el;

Categories

Resources