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;
Related
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));
This is my current JSP code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<jsp:useBean id="user" class= "uts.wsd.User" scope="session" ></jsp:useBean>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String color = request.getParameter("favcol");
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setGender(gender);
user.setFavouriteColour(color);
%>
<body style="background: <%= color %>;">
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<jsp:forward page="index.jsp" />
<% } %>
</html>
Here I use jsp:forward page="index.jsp" to redirect to index.jsp page. Then, if I want to use response.sendRedirect("index.jsp")? How can I proceed?
I tried this:
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<response.sendRedirect("index.jsp")>
<% } %>
</html>
But it failed. Please help! Thank you!!
response.sendRedirect() is Java code not a tag, so you should not close the scriptlet tags before typing it, and it is not to be preceded by < and closed with >...its just Java code:
<%
}
else
{
response.sendRedirect("index.jsp");
return; //this is to redirect immediately so it doesn't
//run any code below this point before redirecting
}
%>
I have been exporting jasper report to pdf but it opens in the same window which is a problem to me because if i want to go to previous page i cant be able to go to previous page so i thought of opening pdf page in a new window but i dont have any idea of how to open it in a new window.
sample1.jsp
<%# page import="java.io.*"%>
<%# page import="java.sql.Connection"%>
<%# page import="java.sql.DriverManager"%>
<%# page import="java.util.HashMap"%>
<%# page import="java.util.Map"%>
<%# page import="net.sf.jasperreports.engine.*"%>
<%# page import="net.sf.jasperreports.engine.*" %>
<%# page import="java.text.SimpleDateFormat" %>
<%# page import="java.text.ParseException" %>
<%# page import="java.io.File" %>
<%# page import="java.io.FileInputStream" %>
<%# page import="java.io.FileNotFoundException" %>
<%# page import="java.io.InputStream" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.io.FileOutputStream" %>
<%# page import="java.io.ByteArrayOutputStream" %>
<%# page import="java.io.OutputStream" %>
<%# page import="java.util.HashMap" %>
<%# page import="java.util.Map" %>
<%# page import="net.sf.jasperreports.engine.util.*" %>
<%# page import="net.sf.jasperreports.engine.export.*" %>
<%#page import = "net.sf.jasperreports.engine.design.JRDesignQuery"%>
<%#page import = "net.sf.jasperreports.engine.xml.JRXmlLoader"%>
<%#page import = "net.sf.jasperreports.engine.design.JasperDesign"%>
<%#page import = "net.sf.jasperreports.view.JasperViewer"%>
<%#page import = "net.sf.jasperreports.engine.JRException"%>
<%#page import = "net.sf.jasperreports.engine.JRResultSetDataSource"%>
<%#page import = "net.sf.jasperreports.engine.JasperCompileManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperExportManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperFillManager"%>
<%#page import = "net.sf.jasperreports.engine.JasperPrint"%>
<%#page import = "net.sf.jasperreports.engine.JasperReport"%>
<%#page import = "net.sf.jasperreports.engine.data.JRCsvDataSource"%>
<%#page import = "net.sf.jasperreports.engine.export.ooxml.JRDocxExporter"%>
<%#page import = "net.sf.jasperreports.engine.export.JRPdfExporter"%>
<%# 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">
<title>Insert title here</title>
</head>
<body>
<%
Connection conn = null;
String cate=(String)session.getAttribute("cat");
String stat=(String)session.getAttribute("sta");
String dayy=(String)session.getAttribute("da");
String monthh=(String)session.getAttribute("mon");
String yearr=(String)session.getAttribute("yea");
String dayy1=(String)session.getAttribute("da1");
String monthh1=(String)session.getAttribute("mon1");
String yearr1=(String)session.getAttribute("yea1");
System.out.println("2 is:"+cate);
System.out.println("4 is:"+stat);
System.out.println("5 is:"+dayy);
System.out.println("6 is:"+monthh);
System.out.println("7 is:"+yearr);
System.out.println("8 is:"+dayy1);
System.out.println("9 is:"+monthh1);
System.out.println("10 is:"+yearr1);
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
String sql="select * from lead where Status='" + stat.replaceAll("\\'","''") + "'";
sql+=" AND Category='" + cate.replaceAll("\\'","''") + "'";
sql+=" AND DATE(Lead_Date)>='" + yearr + "-" + monthh + "-" + dayy + "'";
sql+=" AND DATE(Lead_Date)<='" + yearr1 + "-" + monthh1 + "-" + dayy1 + "'";
String jrxmlFile ="D:/dev/tools/jasper files/report3.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
JasperDesign jasperDesign = JRXmlLoader.load(input);
System.out.println("Compiling Report Designs");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
System.out.println("Creating JasperPrint Object");
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("sql",sql);
byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, map, conn);
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write(bytes, 0, bytes.length);
outStream.flush();
outStream.close();
}
catch(Exception e)
{e.printStackTrace();}
%>
</body>
</html>
view.jsp
<script type="text/javascript">
function setAction(nPage){
document.forms[0].action = nPage;
}
</script>
</head>
<body>
<form>
<%
String category=request.getParameter("category");
session.setAttribute("cat",category);
String status=request.getParameter("status");
session.setAttribute("sta",status);
System.out.println("status is:"+status);
String day=request.getParameter("day");
session.setAttribute("da",day);
String month=request.getParameter("month");
session.setAttribute("mon",month);
String year=request.getParameter("year");
session.setAttribute("yea",year);
String day1=request.getParameter("day1");
session.setAttribute("da1",day1);
String month1=request.getParameter("month1");
session.setAttribute("mon1",month1);
String year1=request.getParameter("year1");
session.setAttribute("yea1",year1);
%>
<select onchange="setAction(this.value)">
<option value=''> Make a selection </option>
<option value='sample1.jsp'> PDF</option>
<option value='XLS_LEAD.jsp'> XLS </option>
<option value='DOC_LEAD.jsp'> DOC </option>
<option value='XLSX_LEAD.jsp'> XLSX </option>
</select>
<br/>
<input type="submit" value="Submit">
</form>
</body>
Considering your view.jsp
I can see that you already have put all variables into the session you are only using the form to select to which page you need to go.
You can do something like this...
<script type="text/javascript">
function generateReport() {
var e = document.getElementById("idOfYourSelectYouNeedToAddedIt");
var strPage = e.options[e.selectedIndex].value;
window.open(strPage);
return false; //This make you stay on this page;
//return true; //Set the action tag in the form to the page you like to go to!
}
</script>
<form name="myForm" onsubmit="return generateReport()">
<select id = "idOfYourSelectYouNeedToAddedIt">
<option value=''> Make a selection </option>
..... the other option values
</form>
Note if you like to go to another page you can simple add action tag to your form tag and return true in the generateReport() function
example
<form name="myForm" action="thisIsWhereILikeToGo.jsp" onsubmit="return generateReport()">
Note: You should remove the onchange="setAction(this.value) code, it has no use anymore and consider checking that strPage is not empty, no selection...
I have a JSP that includes other JSPs using code like this:
<jsp:include page="include.jsp" />
I simply want to be able catch the exception and show the end user an error message if include.jsp is missing. How can I detect or catch the missing resource condition?
I think JSP has implicits objetcs, one of them is Exception.
Example of tutorialspoint:
<%# page errorPage="ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1) {
throw new FileNotFoundException("Error, one file is missing!!!");
}
%>
</body>
And only you have handle the exception in the error page:
<%# page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
In your original JSP
<%# page errorPage="errorPage.jsp" %>
<html>
<head>
<title>JSP exception handling</title>
</head>
<body>
<jsp:include page="include.jsp" />
</body>
</html>
Then, in your errorPage.jsp
<%# page isErrorPage="true" %>
<html>
<head>
<title>Display the Exception Message</title>
</head>
<body>
<h2>errorPage.jsp</h2>
<i>An exception has occurred. Please fix the errors. Below is the error message:</i>
<b><%= exception %></b>
</body>
</html>
Credits: Examples extracted from this tutorial: http://beginnersbook.com/2013/11/jsp-exception-handling/
You should use java.io.File to check whether the file is missing.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%#page import="java.io.*"%>
<%#page import="java.io.File.*"%>
<%
String filename = "kpisrc/getNowTime2.jsp";
File f = new File(filename);
if(f.exists()){
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
}else{
out.print(filename + " not found.");
}
%>
Or another way to check file exists
if(null == application.getResource(filename))
by using try/catch?
<%
try {
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
} catch(Exception e) {
%>
the file, <%=filename%>, is missing.
<%
}
%>
I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!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">
<title>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>
First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")
use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""
It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!
there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"