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'm new programming and I'm having many problems... I was just trying to create a JTable to export it afterwards to an excel. The code I'm using is:
<%# page import="java.sql.*" %>
<%# page import = "java.util.Properties"%>
<%# page import = "java.util.ArrayList"%>
<%# page import = "java.io.*" %>
<%# page import = "java.util.Iterator" %>
<%# page import = "javax.swing.*" %>
<%# page import = "java.awt.*" %>
<%# page import = "javax.swing.table.*" %>
<%# page import = "javax.swing.JScrollPane" %>
DefaultTableModel model = new DefaultTableModel();
for(int col=1; col<=numberOfColumns; col++)
{
columnName = rsMetaData.getColumnName(col);
model.addColumn(columnName);
}
while (rs.next())
{
Object [] fila = new Object[numberOfColumns];
for (int i=0;i<numberOfColumns;i++)
fila[i] = rs.getObject(i+1);
model.addRow(fila);
}
JTable tabla = new JTable(model);
If I bug the code I'm able to see that I have information in the different lines and columns, but nothing appears in tabla... I've been searching in several websites and it's the only structure I've found that I more or less undesrtood. In some of those webs kept going with the code with sentences like that:
JScrollPane scrollpane = new JScrollPane(tabla);
but I'm not able to go further with the tabla problem...
I m trying to display an image in html page calling a jsp page in <img /> tag as follows.
I have created dynamic web project, have added index.html under webcontent folder, timeseries.jsp under webcontent → jsp folder.
When I run the project on server, adding apache tomcat 6.0.18, its synchronised, but when I enter url localhost:8080/jfree it displays only hello doctor and image icon on the page but no image there.
My HTML is,
<!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>
<body>
Hello doctor
<img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" />
</body>
</html>
My JSP is,
<%# page import="java.awt.Image" %>
<%# page import="java.awt.*"%>
<%# page import="java.text.SimpleDateFormat"%>
<%# page import="java.awt.BasicStroke"%>
<%# page import ="org.jfree.ui.ApplicationFrame"%>
<%# page import="java.io.*" %>
<%# page import="java.io.File"%>
<%# 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.data.time.Minute"%>
<%# page import="org.jfree.data.time.Hour"%>
<%# page import="org.jfree.data.time.TimeSeries"%>
<%# page import="org.jfree.data.time.TimeSeriesCollection"%>
<%# page import="org.jfree.data.xy.XYDataset"%>
<%# page import="org.jfree.chart.plot.XYPlot"%>
<%# page import="org.jfree.chart.renderer.xy.StandardXYItemRenderer"%>
<%# page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.PreparedStatement" %>
<%# page import="java.sql.ResultSet" %>
<%# page import=java.sql.Statement" %>
<%# page import="javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="java.awt.image.BufferedImage"%>
<%
try
{
File image = File.createTempFile("image", "tmp");
//chart class instance
Fms fm = new Fms("Graph");
JFreeChart chart = fm.createChart(fm.dataset);
ChartUtilities.saveChartAsPNG(image, chart, 500, 400);
//get input stream
FileInputStream fileInStream = new FileInputStream(image);
//output stream foe returning chart as image
OutputStream outStream = response.getOutputStream();
long fileLength;
byte[] byteStream;
fileLength = image.length();
byteStream = new byte[(int)fileLength];
//read chart image
fileInStream.read(byteStream, 0, (int)fileLength);
//returns chart image whenever called
response.setContentType("image/png");
response.setContentLength((int)fileLength);
response.setHeader("Cache-Control","no-store,no-cache, must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
fileInStream.close();
outStream.write(byteStream);
outStream.flush();
outStream.close();
}
catch (IOException e)
{
System.err.println("Problem occurred creating chart.");
}
%>
<%!
public class Fms extends ApplicationFrame {
//Main class
XYDataset dataset= null;
public Fms(final String title) {
super(title);
dataset= createDataset();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(700, 570));
chartPanel.setMouseZoomable(true, false);
setContentPane(chartPanel);
}
//chart creation method
JFreeChart createChart(final XYDataset dataset) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Speed Chart",
"Time",
"Speed",
dataset,
true,
true,
false
);
chart.setBackgroundPaint(Color.white);
final XYPlot plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(false);
final XYItemRenderer renderer = plot.getRenderer();
if (renderer instanceof StandardXYItemRenderer) {
final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
rr.setShapesFilled(true);
renderer.setSeriesStroke(0, new BasicStroke(1.0f));
renderer.setSeriesStroke(1, new BasicStroke(1.0f));
}
final DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("dd:MM"));
try{
final ChartRenderingInfo info = new ChartRenderingInfo
(new StandardEntityCollection());
final File file1 = new File("c:/Documents and Settings/accounts/WebApplication2/web/barchart.png");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
}catch(Exception e){ }
return chart;
}
//data set generation method
private XYDataset createDataset() {
final TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.setDomainIsPointsInTime(true);
final TimeSeries s1 = new TimeSeries("Series 1", Minute.class);
s1.add(new Minute(0, 0, 7, 7, 2003), 10.2);
s1.add(new Minute(30, 12, 7, 8, 2003), 23.0);
s1.add(new Minute(15, 14, 7, 9, 2003), 48.0);
final TimeSeries s2 = new TimeSeries("Series 2", Minute.class);
s2.add(new Minute(0, 0, 7, 7, 2003), 23.0);
s2.add(new Minute(30, 12, 7, 8, 2003), 9.0);
s2.add(new Minute(15, 14, 7, 9, 2003), 36.0);
dataset.addSeries(s1);
dataset.addSeries(s2);
return dataset;
}
}
%>
but its not dispaying the image in jsp? any help?
This is possible, and it's also pretty simple. And you can set the response type of your JSP page with the following tag:
<%#page contentType="image/png" pageEncoding="UTF-8"%>
Furthermore, there's no need to save these charts to the server's file system. They can be written directly to the response's output stream using the ImageIO class. Here's an example JSP page which I've named Chart.jsp:
<%#page import="javax.imageio.*"%>
<%#page import="org.jfree.data.xy.*"%>
<%#page import="org.jfree.chart.*"%>
<%#page import="java.awt.image.*"%>
<%#page contentType="image/png" pageEncoding="UTF-8"%>
<%
DefaultXYDataset data = new DefaultXYDataset();
data.addSeries("Set 1", new double[][] {
{1, 2, 4, 5, 6, 7},
{0, 10, 20, 30, 20, 10}
});
JFreeChart chart = ChartFactory.createXYLineChart("Title", "X Label", "Y Label", data);
BufferedImage bi = chart.createBufferedImage(640, 480);
ImageIO.write(bi, "png", response.getOutputStream());
%>
And here's index.html which refers to it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>body { text-align: center; }</style>
</head>
<body>
<h1>A Chart:</h1>
<img src="Chart.jsp" alt="Chart" />
</body>
</html>
And this is the result:
First this statement would not work: <img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" />
I guess here your thought process is that the JSP would return an image and you could display the image in html <img ... tag. Well this is not like a method call where something is responded back to the caller.
For your HTML, when it will load, it would try to locate a file with /jfree/jsp/Timeseries.jsp assuming that this file is a image format file like jpeg, bmp etc. It will actually not going to execute any JSP call on the server.
Since this file is simple ascii file containing some bytes(even though a valid jsp code, but not an image bytes); the bytes does not actually represent any image. So HTML is not working.
Edit 1:
Whatever you want to accomplish could be done like this:
Create a servlet, which will build the image at runtime, and then save that on a server location.
Test this application and see, if the servlet is creating the image file at a server location say /apps/html/images/yourImage.jpg.
Make sure that the image location is a location where html has access. For the timebeing generate the image in the same directory as
of HTML.
Once your image is producing and you could open the image using a image editor, set the same image name(with relative location) in the
HTML.
Edit the servlet code to add a redirect code, such that the servlet redirect you to the html page.
Since by the time HTML is loaded, the image is already present, your HTML should work fine.
I hope these step would achieve your goal.
If I am understanding your problem correctly, You are creating a chart image using JfreeChart and wanna display this chart image on one of your JSP ?
Recently I worked with JFreeChart library to create lots of charts for case study and analysis for a website users.
If this is the requirement try below things:
Create chart and save as png to any folder inside web-root folder of
your web-application. (If needed store the names of created images
in db accordingly)
In your jsp use image tag and simply provide path upto your required
image with name of image including your context path.
Edit : Below lines in your code will automatically save your chart into a png image. So no need to worry about saving your images . just give the proper path, where you have to save chart as image. Give me 20 min I will keep entire code.
JFreeChart chart = fm.createChart(fm.dataset);
ChartUtilities.saveChartAsPNG(image, chart, 500, 400);
Edit 2 : Suppose in your application's web-root folder you have a folder name "Images"
Now below piece of code will give the path upto my Images folder(Including context path of my application) and if that "chart_folder" is not available inside "Images" it will create a new one with this name:
//Get the servers upload directory real path name
String filePath = req.getRealPath("/Images");
//create the chart_folder folder if do not exists...
File folder = new File(filePath);
if(!folder.exists())
{
folder.mkdir();
}
Now with below code I will use this path to save my chart image with required name and will keep the entire path with chart image name in request attribute to get it on my JSP page(You can do according to your requirement i.e. use ServletContext.getContextPath()+"/Images/chart_folder"+<your image name her> etc..):
path=filePath+"/chart_folder";
ChartUtilities.saveChartAsPNG(new File(path +"/chart3.png"), chart ,no, 400);
filePath= path+"\\chart3.png";
req.setAttribute("graph_path3",filePath);
Now in your JSP you can get this entire path with image name to use in tag to display your image.
For any further query feel free to ping.
May be error is occurring in below line.
FileInputStream fileInStream = new FileInputStream(image);
First check image exists or not by using image.exist(). Because it is working fine for static image, then we will move forward.