I have a slide menu in my jsp Page and After login, I am checking whether user is allowed to view element or not from parameters stored in the database. I need to hide the items based on whether the user is allowed to view or not.
My jsp
<ul style = "display:none">
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
My dao:extract:
public boolean userallowed(username, itemid){
..........................
return true;
}
my servlet extract:
if(userallowed(username, itemid)){
session.setAttribute("userallowed", true);
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
session.setAttribute("userallowed", false);
}
How Can I write a javascript Function to able to hide elements based on user permissions?
You may simply do this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:if test="${true == sessionScope.userallowed}">
<ul>
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
</c:if>
Instead of hiding the element with JavaScript, it's more secure if you put that logic in the JSP file:
<% if ((boolean) session.getAttribute("userallowed")) { %>
<ul>
<li>MyfirstSubmenu</li>
<li>MyfirstSubmenu1</li>
</ul>
<% } %>
Notice how those protected menu items are not sent to the client if they are not allowed to see them.
Also, your servlet code could be simplified a little:
session.setAttribute("userallowed", userallowed(username, itemid));
request.getRequestDispatcher("/mypage.jsp").forward(request, response);
Related
i would like to know if it possible that a JSP (boucle.jsp) include itself when a condition is true
this code trow me java.lang.StackOverflowError exception
<%
for(Callers ck : calls.get(calls.size()-1)){
pageContext.setAttribute("ck", ck);
System.out.print("Test1 " +ck);
if (app.hasChild(ck)== true) {
c = app.childOf(ck);
calls.add(c);
%>
<li><input type="checkbox" id="c<%=i%>" />
<label class="tree_label"for="c<%=i%>">${ck}<></label>
<%i++;%>
<%#include file="/Pclink/boucle.jsp" %>
</li>
<%
}else {
%>
<li><span class="tree_label">${ck}</span></li>
<%
}
}
calls.remove(calls.size()-1);
%>
</ul>*
well , include is a static import , wich means the first thing happends is :
<%#include file="/Pclink/boucle.jsp" %>
brings the content of "Pclink/boucle.jsp " and it put it in our jsp and because boucle.jsp call it selfs so it include it again and again ...
so what we need is a dynamique inclule which is <jsp:include page="boucle.jsp" />
NB: the boucle.jsp in that case must be a full jsp page not only a part of the code that u want it to be recursive;
and if you want to reach data from boucle.jsp
all u have to do is puch data from the initial jsp with
request.setAtrribute("name_ that you_want_to_call_it ",variable);
and u catch it in boucle.jsp with
variable = request.getAttribute("name_ that you_called_it ");
however i'm not tooo good at english , i hope understand something.
i am trying to fetch data from database in spring mvc, this is my code for fetching data
#Override
public List getOrderDetail(Integer shop_id) {
// TODO Auto-generated method stub
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT order_id,shop_id,delivery_address,total_amount FROM master_order WHERE shop_id =" + shop_id);
SQLQuery query1 = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT itm.image,itm.name,itm.brand,odr.quantity,itm.offerprice,(itm.offerprice*odr.quantity) AS Total,modr.cust_id FROM master_order modr\r\n"
+ "INNER JOIN tblorder odr ON modr.order_id = odr.order_id INNER JOIN item itm on odr.item_id = itm.item_id WHERE modr.shop_id ="+shop_id);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
List results1 = query1.list();
results.add(results1);
System.out.println(results);
return results;
}
above System.out.println(results); statement give following output
[{shop_id=1, delivery_address=1, abc, xyz, aaa, USA, order_id=6, total_amount=1800}, [{image=Screenshot (19).png, quantity=8, Total=800, name=DhruvRajkotiya, offerprice=100, brand=gsgsrgs, cust_id=2}, {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2}, {image=Screenshot (19).png, quantity=1, Total=100, name=ewq, offerprice=100, brand=gsgsrgs, cust_id=2}]]
i want print order_id as well as {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2} in jsp page
this is my controller code
#RequestMapping(value = "/notifications", method = RequestMethod.GET)
public String notifications(Model model, HttpServletRequest request) {
if (request.getSession().getAttribute("shopkeeper") == null) {
return "redirect:login";
} else {
Shopkeeper sp = (Shopkeeper) request.getSession().getAttribute("shopkeeper");
model.addAttribute("order", shopkeeperService_shopkeeper.getOrderDetail(sp.getSk_id()));
return "shopkeeper/notifications";
}
}
this is my jsp code
<div class="row">
<c:forEach items="${ order}" var="order">
<div class="col-lg-12">
<div class="card">
<div class="card-header" style="padding-bottom: 5px;">
<h6># ${order.shop_id }</h6>
</div>
<div class="card-body">
<div class="col-lg-2" style="float: left;">Image</div>
<div class="col-lg-2" style="float: left;">Product name</div>
<div class="col-lg-2" style="float: left;">Product brand
</div>
<div class="col-lg-1" style="float: left;">Quantity</div>
<div class="col-lg-1" style="float: left;">Unit Price</div>
<div class="col-lg-1" style="float: left;">Total</div>
<div class="col-lg-3" style="float: left;">Approve of
request</div>
</div>
<div class="card-body">
<div class="col-lg-6" style="float: left;">Delivery
Address</div>
<div class="col-lg-6" style="float: left;">Total Amount</div>
</div>
</div>
</div>
</c:forEach>
</div>
i want to print
my question concept is order_id,address,total_amount one time and multiple bought item that can be one or more
how i can print
The way to "send" some data to a JSP page is to set and pass a request (or session) attribute.
From a Servlet, which handles current request, in a doGet() or doPost() method (depending on the HTTP request method used), you can do:
request.setAttribute("attributeName", attributeObject);
request.getRequestDispatcher("<name_of_your_page>.jsp").forward(request, response);
where the attributeName is a string, which will be treated as a reference to the attributeObject on a JSP page.
Then on the JSP page, you can use JSTL library and Expression Language (see this tutorial regarding JSTL and this one regarding JSP & EL in general). To iterate over the list, which has been passed as a request attribute, use <c:forEach> tag from JSTL.
First of all you need to import the core JSTL tags by placing this line on the top of your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Another useful statement to put under the latter is:
<%# page isELIgnored="false" %>
which tells your web browser to evalue the expressions written in EL instead of including them in HTML body as a plain text.
Provided that you used the string "orders" to name the collection set as attribute, the <c:forEach> tag usage can look similarly as below. You'll probably want to structure it differently and the field names (like order.order_id) can be different in your case, but I think you can get the idea.
<c:forEach item="order" items="${requestScope.orders}">
<p>${order.order_id}</p>
<p>${order.delivery_address}</p>
...
</c:forEach>
You can save the list as a model attribute. For example you want to save the current user:
model.addAttribute("user",user);
and access this attribute in your jsp file inside a div maybe :
<div> ${user.name} </div>
The controller method could look like this:
#RequestMapping( value = "/user", method = RequestMethod.GET )
public String displayUser(final Model model)
{
final User user = userService.findUserById(1); // here you'll provide custom implementation
model.addAttribute("user",user);
return "somejsppage.jsp";
}
If you want to add a List to your model:
final List<User> users = fillUserList(); // your implementation here
model.addAttribute("users",users);
You can access every element in that list via <c:forEach> tag:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<table>
<tr>
<th>First Name</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.firstName}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Currently getting an error that the bankOffer property in my bean cannot be found..
It is from my game.jsp file shown below:
<%#page import="game.Briefcase"%>
<jsp:useBean id="game" class="game.Game" scope="session" />
<%
// If the 'open' parameter is received, it is converted to
// an integer and passed to the method setOpen. The value given
// is the corresponding index for the ArrayList Object.
if (request.getParameter("open") != null) {
game.caseOpen(Integer.parseInt(request.getParameter("open")));
}
// If the 'restart' parameter is given, then the restart method
// is invoked on the game bean.
if (request.getParameter("restart") != null) {
game.newgame();
}
// If the deal parameter is given, then it converts it to a Boolean
// value and performs a conditional test. If the parameter is true,
// then the deal has been made so the page is forwarded to the deal.jsp.
// Otherwise, the gameRound() is incremented cause it is NO DEAL!.
if (request.getParameter("deal") != null) {
if (Boolean.parseBoolean(request.getParameter("deal"))) {
game.setDeal(true);
} else {
game.nextround();
}
}
// If there is a Bank Offer, it will display the amount offered with
// two buttons to either accept or refuse.
if (!game.getDeal()) {
if (game.offerTime()) {%>
<div id="bank_offer">
<div id="bank_offer_title"></div>
<div id="deal_button" onclick="deal(true)"></div>
<div id="bank_offer_text">
<div id="bank_offer_amount">$<jsp:getProperty name="game" property="bankOffer" /></div>
<div id="bank_offer_message">Highest amount left: $<jsp:getProperty name="game" property="highestAmount" /></div>
</div>
<div id="nodeal_button" onclick="deal(false)"></div>
</div>
<%
// Otherwise, the Briefcases will be displayed along with a game message
// above the cases.
} else {
%>
<div id="game_message">
<div id="game_round">
<% if (game.getRound() > 0) { %>
Round: <jsp:getProperty name="game" property="round" />
<% } %>
</div>
<div id="game_text">
<jsp:getProperty name="game" property="message" />
</div>
</div>
<div id="cases">
<%
int index = 0;
// Iterates For Each Briefcase
for (Briefcase briefcase : game.getcases()) {
// If the Briefcase is not opened, then it is displayed as closed with the
// number assigned. Otherwise, if the Briefcase is opened then it is displayed
// as open with the amount value inside.
if (!briefcase.isOpened()) {
// If the Briefcase is the chosen case, then it will be displayed with
// 'Your Briefcase' on the image. The Briefcase's once pressed invokes
// a JavaScript function called openBriefcase() which passes the
// index. The function then invokes an Ajax call to the same .jsp which the
// html is then placed into the game container on the main index.jsp.
%>
<div onclick="openBriefcase(<%=index%>)" class="<%=(((game.getChosen() != null)
&& game.getChosen().equals(briefcase)) ? "briefcase_chosen" : "briefcase_closed")%>">
<div class="briefcase_number"><%=briefcase.getNumber()%></div></div>
<%} else {
// Once the case is opened it gets displayed with an open background
// with the case amount centered.
%>
<div class="briefcase_open">
<div class="briefcase_amount">$<%=briefcase.getValue()%></div>
</div>
<%}
index++;
}%>
</div>
<%
}
} else { %>
<div id="deal_message">
Deal $<jsp:getProperty name="game" property="bankOffer" />
</div>
<%
}
%>
Hmu to link any other files required. The previous file is index jsp, that loads fine with my other dynamic content, but it isnt loading game.jsp.
Help would be greatly appreciated, this is the first time I've had to use jsp in any extensive way so I'm at a loss right now..
Make sure that the class game.Game has a bean property (not just a field) named bankOffer. A java bean property is defined by its getters and setters, so for bankOffer to be a property, the class game.Game must include the public methods getBankOffer (or isBankOffer if a boolean property) and setBankOffer.
Hi I am new to Java world and I am trying to make my own web application with Spring MVC. Now, I am going to read a text file in my local directory, for example, the text file like this:
TestData_FileOne.txt
1,100
2,200
3,300
4,400
5,500
The result I would like to present in a browser page like this (in a table) :
1 2 3 4 5
100 200 300 400 500
so I implemented 1) Controller , 2) Model , and 3)View(.jsp file).
**1) My Controller and 2)Model ([Q1] [Q2]) **
#Controller
public class TestController {
#RequestMapping("/testMVC")
public String testmvc(Model model){
String dirString = "C:/Users/Me/Documents/Test/";
Path testFile;
List<String> testData;
testFile = Paths.get( dirString + "TestData_FileOne.txt");
try {
testData = Files.readAllLines(testFile, StandardCharsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "unable to read...";
return "unable to read...";
}
// ====== changes from here based on Aeseir's answer========
List<String> dataNum = new ArrayList<String>();
List<String> data = new ArrayList<String>();
for(int i=0; i<testData.size()-1;i++){
dataNum.add(testData.get(i).split(",")[0]);
data.add(testData.get(i).split(",")[1]);
}
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
// ======= changes until here ==============
return "testMVC";
}
}
(Read the text file works fine when I checked System.out.println part)
2) testMVC.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<table>
<thread>
<tr>
<th>Table with dynamic data from model</th>
</tr>
</thread>
<tbody>
<c:forEach var="dataNumValue" items="${dataNum}"> [items added but.. Q5]
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items="${data}"> [items added but.. Q5]
<tr>
<td>
${dataValue} --- [Q2']
</td>
</tr>
</c:forEach>
</tbody>
</table>
So..I know Q1/Q1' should be match, and Q2/Q2' as well.
1) however, I am confused about the object in model.addAttribute("", object); in Q1, Q2? and addAttribute is the right choice among model attributes?
2) Do I need var="dataNum" and var="data" in Q3, Q4 and did I do correctly?
I appreciate any advice if I made mistake.
Extra Question
so I have updated Controller code and jsp file like the above after Aeseir's answer (Thanks!!) but I have warning in jsp file after I added items then warning (Q5) and of course, the page is not presented.
[Q5]: warning : "items" does not support runtime expressions
I searched for the warning, then advices like check the jstl version - should be above version 1.0 - My jstl version is 1.2. so shouldn't be any problem....
Can you check my changes part? and What else could cause this warning except jstl version?.
Solution for extra question 5
#taglib directive should be like this in jsp file:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> => /jsp was missing in the middle
This #taglib correction + code changes the above based on Aeseir's answer works all fine!
Q1 and Q2
You were almost there. Model will pass most data you put into it. Its up to your rendering page to determine how to display it.
And you will need to change the types to arrays since you want to output multiple strings.
List<String> dataNum = //populate accordingly
List<String> data = // populate accoridngly
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
Q3 and Q4
Yes you do but you need to complete it this way:
<c:forEach var="dataNumValue" items="${dataNum}">
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items=${data}>
<tr>
<td>
${dataValue}
</td>
</tr>
</c:forEach>
Hope that helps
I just started to use JSTL for my project, but sorry to say it's really confusing to me.
I originally used Number.java
package com.mycompany
public class Number {
private int total;
public static int add (int x, int y) {
return total;
}
And in showNumber.jsp i could just use
<%#page import= "com.mycompany.Number" %>
and inline use <%= Number.add(5,6) %>
How can I rewrite this part in JSTL?
Is that also possible to import the class Number.java?
I tried so many different things, e.g. <c:out value="${Number}.add(5,6)" />, but still cannot find a solution. Thanks.
Edited:
I use #Victor's approach, and it does work. In my case, I need to reuse other's variable from spring framework, say NumberTwo.java and totalTwo as private variable inside. And added "100" to this totalTwo.
For the src where i need to use it is <spring:param name="secondNumber" value ="${NumberTwo.totalTwo}" />.
However, intutively i used (int) pageContext.getAttribute("NumberTwo.totalTwo"), it always returned me null.
The other workaround is
first <c:set var="result" value="${NumberTwo.totalTwo}" />
then <% String result = (String) pageContext.getAttribute("result"); %>
and then <%= Number.add(result, 100) %>
Unfortunately it's not possible to arbitrarily call methods with JSTL, the function capabilities of JSTL are very limited: http://docs.oracle.com/javaee/5/tutorial/doc/bnalg.html . But it's still possible to use your Number class. Here the workaround:
<%#page import= "com.mycompany.Number" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("addResult", Number.add(7, 8));
%>
<html>
<body>
JSP 1.x: Result is: <c:out value="${addResult}" /><br/>
JSP 2.x: Result is: ${addResult}
</body>
</html>
With pageContext.setAttribute() the method result is stored in the page context, and the JSTL tags can access values (attributes) stored in that context.
Note: the second output line "Result is: ${result}" works only with JSP 2 afaik.
You can use the 'usebean' tag as in the following example:
<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- UseBean.jsp
Copyright (c) 2002 by Dr. Herong Yang
-->
<html><body>
<jsp:directive.page import="CacheBean"/>
<jsp:useBean id="b" class="CacheBean"/>
<jsp:setProperty name="b" property="text" value="Hello world!"/>
Property from my Bean:
<jsp:getProperty name="b" property="text"/>
<br/>
Info from my Bean:
<jsp:expression>b.getInfo()</jsp:expression>
</body></html>
</jsp:root>
Where:
/**
* CacheBean.java
* Copyright (c) 2002 by Dr. Herong Yang. All rights reserved.
*/
public class CacheBean {
private String text = "null";
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getInfo() {
return "My JavaBean - Version 1.00"
}
}
CREDIT TO: http://www.herongyang.com/jsp/usebean.html
Please look at EL functions in BalusC's answer at
Hidden features of JSP/Servlet
also
look at "Using Custom Methods in EL" at
http://www.roseindia.net/jstl/jstl-el.shtml
look at Functions at
http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html