i have set value inside my Contexte class.
Below is part of my jsp page code
<%#page language = "java"%>
<%#page session="true" import="collections.*"%>
<%
JspBeansCollection jspbeans = new JspBeansCollection((Contexte)request.getAttribute("ctx"));
session.putValue("jspbeans",jspbeans);
...
%>
Related
I am trying to initalize my repository inside on of my JSP's. I have imported it above the code but yet it still says it is not initilized.
The code below is the top of the page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page import="java.util.List" %>
<%# page import="java.util.ArrayList" %>
<%# page import="co2103.hw2.domain.TestResults" %>
<%# page import="co2103.hw2.repositories.TestResultsRepository" %>
<%# page import="org.springframework.beans.factory.annotation.Autowired" %>
<% TestResultsRepository TRRepo; <! DECLARED HERE
int size = 100;
for (int i = 0; i< size; i++) {
List<String> list = TRRepo.findAllById(i); <! SAYS HERE THAT IT IS NOT INITALIZED
}
System.out.println("List initalized!");
%>
Does anyone know how to fix this? I am new to programming Java so any help would be very appreciated.
TEST RESULTS REPOSITORY CLASS
public interface TestResultsRepository extends CrudRepository<TestResults, String> {
String findAllById(int id);
}
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));
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 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;
I tried created below jsp.. but it is just keep on loading not showing any result... any help on optimizing this jsp Or let me know if this code is correct and it will show an applet on the browser.
As the code shows I am taking dynamic value from database and want to show them in pie chart on browser.
<%# page import="java.util.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.text.SimpleDateFormat" %>
<%# page import= "javax.swing.*" %>
<%# page import= "java.awt.*" %>
<%# page import="java.awt.image.*" %>
<%# page import="org.jfree.chart.*" %>
<%# page import="org.jfree.chart.axis.*" %>
<%# page import="org.jfree.chart.entity.*" %>
<%# page import="org.jfree.chart.labels.*" %>
<%# page import="org.jfree.chart.plot.*" %>
<%# page import="org.jfree.chart.renderer.category.*" %>
<%# page import="org.jfree.chart.urls.*" %>
<%# page import="org.jfree.data.category.*" %>
<%# page import="org.jfree.data.general.*" %>
<%# page import= "org.jfree.chart.title.TextTitle" %>
<%# page import= "org.jfree.data.general.DefaultPieDataset" %>
<%# page import="org.jfree.ui.*" %>
<html>
<head>
</head>
<body>
<%
ResultSet rs = null;
Connection con =null;
Statement st=null;
try
{
String queryactive1 = null;
String queryactive2= null;
String queryactive3 = null;
String queryactive4 = null;
String queryactive5 = null;
String queryactive6 = null;
String queryactive7 = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con= DriverManager.getConnection("jdbc:sqlserver://newine:3468;instanceName=MSSQL2005","eGActiveDB_762","eGActiveDB_762");
st = con.createStatement();
%>
<p style="text-align:center"><B><u>Pie Chart Showing Case Count</u></B></p>
<%
queryactive1="SELECT count(a.case_id)as case_count , b.owner from EGPL_CASE a Right Outer Join (Select distinct OWNER from EGPL_CASE where owner in (1047,1213)) b on b.owner =a.owner and a.when_created BETWEEN '2011-01-01 00:00:00' AND '2011-01-01 1:59:59' group by b.OWNER order by b.owner";
rs=st.executeQuery(queryactive1);
rs.absolute(2);
int ravi_case=rs.getInt("case_count");
rs.absolute(4);
int pradeep_case=rs.getInt("case_count");
%>
<%
JPanel panel = new JPanel(new GridLayout(2, 2));
DefaultPieDataset dataset = new DefaultPieDataset();
DefaultPieDataset dataset1 = new DefaultPieDataset();
dataset.setValue("January "+ravi_case, ravi_case);
dataset1.setValue("January "+pradeep_case,pradeep_case);
JFreeChart chart1 = ChartFactory.createPieChart("Ravi Case", dataset, false, false, false);
JFreeChart chart2 = ChartFactory.createPieChart("Pradeep Case", dataset1, false, false, false);
panel.add(new ChartPanel(chart1));
panel.add(new ChartPanel(chart2));
panel.setPreferredSize(new Dimension(800, 600));
%>
<p style="text-align:center"><B><u>BAr Chart</u></B></p>
<%
}
catch(Exception e)
{
String error = e.toString();
e.printStackTrace();
%>
Error is : <%=error%>
<%
}
finally{
rs = null;
st = null;
con = null;
}
%>
</body>
</html>
No, it's not correct at all. An applet is a Java program, packaged in a jar file, that the browser downloads and executes in the client browser.
A JSP is some dynamically composed page that executes on the server, and outputs HTML which is rendered in the client browser.
If this code would display a JPanel (which id doesn't : it just constructs one), the panel would be displayed on the server screen, where the code is executed.
Finally, a JSP should not contain Java code for decades, but should use the JSTL and other custom tags. Read How to avoid Java code in JSP files?.
Read the Java tutorial about applets, try to create an applet displaying a graph with purely static data and embed it into a static HTML page, then make a JSP that contains the same code as the static JSP to embed the applet, and finally think of a way for the applet to communicate with the server to get the data allowing it to display the graph.