jfreechart in jsp - java

i want to create a pie chart in jsp using jfree chart, i am using this code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.awt.*" %>
<%# page import="java.io.*" %>
<%# page import="org.jfree.chart.*" %>
<%# page import="org.jfree.chart.entity.*" %>
<%# page import ="org.jfree.data.general.*"%>
<%
final DefaultPieDataset data = new DefaultPieDataset();
data.setValue("One", new Double(43.2));
data.setValue("Two", new Double(10.0));
data.setValue("Three", new Double(27.5));
data.setValue("Four", new Double(17.5));
data.setValue("Five", new Double(11.0));
data.setValue("Six", new Double(19.4));
JFreeChart chart = ChartFactory.createPieChart
("Pie Chart ", data, true, true, false);
try {
final ChartRenderingInfo info = new
ChartRenderingInfo(new StandardEntityCollection());
final File file1 = new File("../webapps/jspchart/
web/piechart.png");
ChartUtilities.saveChartAsPNG(
file1, chart, 600, 400, info);
} catch (Exception e) {
out.println(e);
}
%>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<IMG SRC="piechart.png" WIDTH="600" HEIGHT="400"
BORDER="0" USEMAP="#chart">
</body>
</html>
The problem is that i am getting this exception "java.io.FileNotFoundException: ../webapps/jspchart/web/piechart.png (No such file or directory) "
any thoughts??

Exception clearly says "java.io.FileNotFoundException: ../webapps/jspchart/web/piechart.png (No such file or directory)"
Here the piechart.png(../webapps/jspchart/web/piechart.png) or web directory is not exists.
Verify these info and fix it.
Fix can be:-
Creating a Web folder under jspchart folder OR
Placing a piechart.png file under Web folder
Then try to compile and run application once again.

i got this.Actually i needed the pie chart to fetch values from a database.
The database's first column is the name and second its value.
The code is:
Table name is chart and database is maj
<%# page import="java.io.*"%>
<<%# page import="java.awt.*" %>
<%# page import="java.io.*" %>
<%# page import="java.sql.*" %>
<%# page import="org.jfree.data.jdbc.JDBCPieDataset" %>
<%# page import="org.jfree.chart.plot.PlotOrientation" %>
<%# page import="org.jfree.chart.JFreeChart" %>
<%# page import="org.jfree.chart.ChartUtilities" %>
<%# page import="org.jfree.chart.ChartFactory" %>
<%# page import="org.jfree.data.general.DefaultPieDataset" %>
<%# page import="org.jfree.chart.*"%>
<%# page import="org.jfree.chart.entity.*"%>
<%# page import="org.jfree.data.general.*"%>
<%# page import="org.jfree.chart.plot.PiePlot;" %>
<%
String query = "SELECT * from chart";
JDBCPieDataset dataset = new JDBCPieDataset("jdbc:mysql://localhost:3306/maj", "com.mysql.jdbc.Driver","root", "password");
dataset.executeQuery(query);
JFreeChart chart = ChartFactory.createPieChart("File System",dataset, true, true, false);
//chart.setBackgroundPaint(new Color(222, 222, 255));
final PiePlot plot = (PiePlot) chart.getPlot();
plot.setBackgroundPaint(Color.white);
plot.setCircular(true);
try {
final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
final File file1 = new File(getServletContext().getRealPath(".") + "/piechart.png");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
} catch (Exception e) {
System.out.println(e);
}
%>
<html>
<body>
Heading
<IMG SRC="piechart.png" WIDTH="500" HEIGHT="400" style="border:4px solid orange;" USEMAP="#chart" alt="image">
</body>
</html>

Did you check this path? is the file there? (i bet not).
Copy the file under that directory and your problem will be solved.

Related

How to display List results in JSP Page?

I Have a class that find Google search results. And i have a JSP page that i want to show the results in. But i can't do it.
Heres my UrlOku class :
public static void GetUrl() {
final String keyword = "emre varol";
final String url = "https://www.google.com/search?q="+keyword;
try {
final Document document = Jsoup.connect(url).get();
List<String> myList = new ArrayList<String>();
for(Element row: document.select("div[class=g]")) {
final String title = row.select("div[class=TbwUpd NJjxre]").text();
myList.add(title);
}
}
And heres my JSP page :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="urlpaket.Urloku" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<%
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
WELCOME ${username}
<%
Urloku oku = new Urloku();
oku.GetUrl();
%>
<c:forEach items="${myList}" var="item">
<tr>
<td><c:out value="${item.title}" /></td>
</tr>
</br>
</c:forEach>
And there is nothing in the welcome.jsp file.
Any help would be appreciated!
How is myList variable available in you JSP? This needs to be set in pageContext before accessing it using ${myList}.
You can change the signature to public static List GetUrl()
and do something like this
Urloku oku = new Urloku();
List<String> myList = oku.GetUrl();
pageContext.setAttribute("myList ",myList );
Now it should be available.

SAP BO login using custom.jsp

I'm using custom.jsp in order to avoid the login screen and load the home screen directly, but still it's asking for login credentials after restarting the tomcat. The path of the custom.jsp file is "SAP BusinessObjects\tomcat\webapps\BOE\WEB-INF\eclipse\plugins\webpath.InfoView\web"
I don't know what I'm missing here and I'm new to this. Below is my jsp code. Thanks.
<%# page import="com.crystaldecisions.sdk.exception.SDKException" %>
<%# page import="com.crystaldecisions.sdk.framework.*" %>
<%# page import="com.crystaldecisions.sdk.occa.infostore.*" %>
<%# page import="com.crystaldecisions.sdk.occa.security.*"%>
<%# page import="java.net.*"%>
<%# page import="com.crystaldecisions.enterprise.*"%>
<%# page import="com.crystaldecisions.sdk.plugin.admin.*"%>
<%# page import="java.sql.*"%>
<%# page import="com.businessobjects.webutil.Encoder" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
IEnterpriseSession enterpriseSession;
final String BO_CMS_NAME = "BI98svr";
final String BO_AUTH_TYPE = "secEnterprise";
final String BO_USERNAME = "user121";
final String BO_PASSWORD = "pass121";
ILogonTokenMgr logonTokenMgr;
String defaultToken = "";
boolean loggedIn = true;
try {
enterpriseSession =
CrystalEnterprise.getSessionMgr().logon(BO_USERNAME,BO_PASSWORD,
BO_CMS_NAME,BO_AUTH_TYPE);
logonTokenMgr = enterpriseSession.getLogonTokenMgr();
defaultToken = logonTokenMgr.createWCAToken("", 20, 1);
response.sendRedirect("http://"+BO_CMS_NAME+":8080/BOE/BI/logon/start.do?ivsLogonToken="+Encoder.encodeURL(defaultToken));
}
catch (Exception error)
{
loggedIn = false;
out.println(error);
}
%>
<!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>
</body>
</html>

java.io.FileNotFoundException:<Excel FileName> the system cannot find the file specified

I'm getting the following error. I am going to insert the excel sheet data into MYSQL database. When I upload the Excel sheet and press submit button ,the following exception occured.
java.io.FileNotFoundException: studentsdetails1.xls (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
Here is my code. In this I am going to insert the excel file data into database.
index.jsp-
<%# 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>
<form action ="Excel.jsp" method="post" >
<input type="file" name= "excelfile" size="20" id="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Excel.jsp-
<%# 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>
<%# page import ="java.util.Date" %>
<%# page import ="java.sql.*" %>
<%# page import ="java.io.*" %>
<%# page import ="java.io.FileNotFoundException" %>
<%# page import ="java.io.IOException" %>
<%# page import ="java.util.Iterator" %>
<%# page import ="java.util.ArrayList" %>
<%# page import ="javax.servlet.http.HttpServletRequest"%>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%# page import ="akshay.Exceltest" %>
<%# page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<%!
Connection con;
PreparedStatement ps=null;
Statement stmt= null;
public static ArrayList readExcelFile(String fileName)
{
/** --Define a ArrayList
--Holds ArrayList Of Cells
*/
System.out.println(fileName);
ArrayList cellArrayLisstHolder = new ArrayList();
try{
/** Creating Input Stream**/
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList=new ArrayList();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
cellArrayLisstHolder.add(cellStoreArrayList);
}
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}%>
<%
String file = request.getParameter("excelfile");
String fileName=""+file+""; //testExcel.xls Excel File name
//Read an Excel File and Store in a ArrayList
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/<dtatabse>", "name", "password");
stmt =con.createStatement();
String query="insert into students12(id,name,age) values(?,?,?)";
ps=con.prepareStatement(query);
int count=0;
ArrayList cellStoreArrayList=null;
//For inserting into database
for(int i=1;i<dataHolder.size();i++) {
cellStoreArrayList=(ArrayList)dataHolder.get(i);
ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
count= ps.executeUpdate();
//out.print(((HSSFCell)cellStoreArrayList.get(2)).toString() + "\t");
}
//For checking data is inserted or not?
if(count>0)
{
%>
Following deatils from Excel file have been inserted in student table of database
<table>
<tr>
<th>Student's Name</th>
<th>Class</th>
<th>Age</th>
</tr>
<%
for (int j=1;j < dataHolder.size(); j++) {
cellStoreArrayList=(ArrayList)dataHolder.get(j);%>
<tr>
<td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(2)).toString() %></td>
</tr>
<%}
}
else
{%>
<center> Details have not been inserted!!!!!!!!!</center>
<% }
}catch(Exception e)
{}%>
</table>
</body>
</html>
Add enctype="multipart/form-data" in form like.
<form action ="Excel.jsp" method="post" enctype="multipart/form-data" >
Rest looks fine.

How to retrieve image from mysql db and show it inside <td> and <img> tag in HTML?

How to retrieve image from mysql db and show it inside tag in HTML and that img tag should be placed inside ? Here s my code:
It displays only the image . Its not showing any content other than image.
Thanks in advance.
<%# 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>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
%>
<table border='1'>
<tr>
<td>Name:</td><td>
</td>My Name</td>
</tr>
<tr>
<td>Image:</td>
<td width=10px;>
<%
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
out.println("Retrieved Successfully!");
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</td></tr>
</table>
</body>
</html>
Images are loaded as separate requests to the request that loaded the html. As such you need to:
establish a URL encoding scheme that you use when specifying the src of the img element.
map a servlet (or similar) to that URL. The servlet loads the image based on the parameters of the URL returning that image in its response.
I found out.
r.jsp:-
<%# 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>
<table border=2>
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>hi</td></tr>
<tr><td>
<img src="retrieve.jsp" width=130 height=130>
</td></tr>
</table>
</body>
</html>
retrieve.jsp:-
<%# 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">
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</body>
</html>

Why won't print in jsp?

The code below doesn't print in jsp (the out.println in while{} ) but it works like a charm in Java program. Can you please explain me why won't print in jsp and what should I change in code? Thank you!
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<!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>
Test
<%try{
URL url = new URL("http://gesi-ro-test.banat.enelro:8010/dynamic/gesi/ri/elab/endcallrequest/wind.ser?id=008201dfa306f4a6&es=&is=2011/04/20%2013:09:46.593&rt=RE");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
in.close();
}catch(Exception e){
out.println(e);
}%>
</body>
</html>
Check your url again. I tried your code with another site and it works:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Test</title>
</head>
<body>
<%
URL url;
try {
url = new URL("http://www.w3schools.com/xml/note.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
%>
<c:out value="<%=inputLine%>"/>
<%
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
</body>
</html>
Personally, I dont like to put a lot of "if", "while" command in the jsp file (it will makes your system later become a big mess), so, try to handle eveything in your business logic and then send the result to the jsp as a attribute
This URL returns XML markup and it is not displayed. You have to add <pre> </pre> tag to show XML markup.
out.println("<pre>");
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
out.println("</pre>");
in.close();
You must have to use JSTL's <import/> instead of Java code in JSPs.
<c:import var="xmlData" url="http://your.url" />
<c:out var="${xmlData}"/>

Categories

Resources