exception in iText pdf creation - exception

I Am trying to generate a table using iText (for testing only, thats why i am not using any servlet and class).I have used this tutorial as my reference.
The code doesnt shows any errors but am getting an exception in run time
org.apache.jasper.JasperException: getOutputStream() has already been called for this response
I use itext version 5.3.2,java 5. my code is given below.
MY CODE
<%#page import="java.io.DataOutputStream"%>
<%#page import="com.itextpdf.text.DocumentException"%>
<%#page import="java.io.DataOutput"%>
<%#page import="com.itextpdf.text.pdf.PdfPTable"%>
<%#page import="com.itextpdf.text.pdf.PdfWriter"%>
<%#page import="java.io.ByteArrayOutputStream"%>
<%#page import="com.itextpdf.text.Document"%>
<%
response.setContentType("application/pdf");
Document document = new Document();
try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
PdfPTable table = new PdfPTable(2);
table.addCell("1");
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
document.close();
DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for(int i = 0; i < bytes.length; i++)
{
dataOutput.writeByte(bytes[i]);
}
}catch(DocumentException e){
e.printStackTrace();
}
%>
EXCEPTION
org.apache.jasper.JasperException: getOutputStream() has already been called for this response
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.catalina.connector.Response.getWriter(Response.java:606)
org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:195)
org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:124)
org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:117)
org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:191)
org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:115)
org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:75)
org.apache.jsp.generatepdf_jsp._jspService(org.apache.jsp.generatepdf_jsp:99)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

on the top of the page use the this
<%# page trimDirectiveWhitespaces="true" %>
we should also add flush/close for you dataOutput.
dataOutput.flush();
dataOutput.close();
return;

Related

Why do I need [Class.forName("org.mariadb.jdbc.Driver");]?

https://mariadb.com/kb/en/about-mariadb-connector-j/
https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html
In that site, Class.forName is no longer needed.
(that file based Java11, JavaEE8 with gradle)
but In my case.
If I didn't use this.
Class.forName("org.mariadb.jdbc.Driver")
HTTP:500 error occurred and that error message is
java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/mydb
Otherwise when I use that code, It work well.
Class.forName("org.mariadb.jdbc.Driver")
Why do they need [Class.forName]?
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%
Connection conn = null;
Class.forName("org.mariadb.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/mydb", "root", "1234");
} catch (SQLException e) {
throw new RuntimeException(e);
}
conn.setAutoCommit(false);
%>
The JDBC 4 standard introduced automatic registration of JDBC drivers. Earlier drivers had to manually be registered by forcing the classloader to load them, e.g., by calling Class.forName.
It seems you're using an older version of the driver that still requires the Class.forName call.

JSP function error

I'm new to JSP and I'm trying to write a function that executes a query and then returns the metadata. I'm getting an error that reads:
Generated servlet error:
Syntax error on token ")", Block expected after this token
Here is my code:
<%! ResultSetMetaData test(ResultSet rs, Statement s){
try{
rs = s.executeQuery("SELECT * FROM students WHERE name = 'Alice Wood'");
}
catch(SQLException e);
return rs.getMetaData();
}
%>
Firstly you should not write your Java code in JSP file, especially SQL queries, you should do it in your Servlet.
Secondly you used declaration tag: <%! %> which is suitable only for declarations, you need Scriptlet tag here: <% your code here %>, but as I said it is not good too, at least you should transfer your code into Servlet.
Here is good tutorial for JSP tags and overall about JSP: http://www.tutorialspoint.com/jsp/jsp_syntax.htm

How to Include and Use GSON library in Eclipse project

I'm from the PHP background, so pardon my noobness. I'm required to use JSON in one of my projects and I cannot, for the life of me, determine how to import and use the GSON library.
I followed Adding library to Eclipse and Using GSON threads but for some reason my code isn't working.
The aim is to pass an ArrayList object back as a JSON array so that I can use Jquery (inside Ajax success function) to iterate over it.
But when I use the following (This is not a class, simply a jsp file which connects to database, pulls some info, and stores it in an ArrayList):
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%
String kw = request.getParameter("key");
try {
java.sql.Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abcd", "root", "pass");
st = con.createStatement();
rs = st.executeQuery("SELECT DISTINCT t.tckid FROM ticket t WHERE t.tckid LIKE '%"+kw+"%'");
ArrayList<String> tickets = new ArrayList<String>();
while(rs.next()) {
String TCKTID = rs.getString(1);
tickets.add(TCKTID);
}
rs.close();
st.close();
con.close();
Gson gson = new Gson(); // this is giving me Gson cannot be resolved to a type
So of what I can gather, the Gson class didn't get imported at all. Is there a way to verify the successful import of the library? Or do I also need to use some import *** code on the top of the file?
The problem is that you are not importing the Gson package in your current JSP.
<%
Gson gson=new Gson();
%>
importing in JSP
<%# page import="com.google.gson.Gson" %>
but please keep in mind to avoid using scriptlets in your JSPMVC pattern to separate the server side with the client side actions/purpose. if you want to display values coming from the database you could always use JSTL and using different scopes(request scope,session scope, etc).

Error in JSON Array create using JSP

I am trying to create a JSON Array using the following code; I have downloaded gson-2.2.4.jar and extracted the com directory in the same location where my JSP file resides
<%# page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.* " %>
<%# page import="java.io.*" %>
<%#page import="com.google.gson.JSONObject"%>
<%
try {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/CATCHINFO";
String username = "postgres";
String password = "123";
String myDataField = null;
String category = null;
String myQuery = "SELECT * FROM cruce order by cruce_no";
Connection myConnection = null;
PreparedStatement myPreparedStatement = null;
ResultSet myResultSet = null;
Class.forName(driver).newInstance();
myConnection = DriverManager.getConnection(url,username,password);
myPreparedStatement = myConnection.prepareStatement(myQuery);
myResultSet = myPreparedStatement.executeQuery();
JSONObject json = new JSONObject();
while(myResultSet.next()){
category = myResultSet.getString("cruce_no");
json.put("city", category);
out.print(category);
}
}
catch(Exception e){
out.print(e);
}
%>"
But I am getting errors:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 16 in the generated java file
Only a type can be imported. com.google.gson.JSONObject resolves to a package
An error occurred at line: 21 in the jsp file: /loadCruceNo.jsp
JSONObject cannot be resolved to a type
An error occurred at line: 21 in the jsp file: /loadCruceNo.jsp
JSONObject cannot be resolved to a type
Please help me.
It doesn't sound right that you "extracted the com directory in the same location where my JSP file resides".
The jar should either be in the WEB-INF/lib directory of your web application or if you decide to unpack all the classes (as you have the described) the com directory should be in the WEB-INF/classes directory.

How to include external HTML in my .aspx page from a JSP+JSTL equivalent

I have this code in JSP+JSTL (Java) to insert some HTML into the page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="caasPath" value="http://wwww.MyExampleSite.com/header/default"/>
<c:import url="${caasPath}/header?contentType=html"/>
I need to do the same but in ASP.NET Web Forms (.aspx file). I have tried with an .ascx but I don't know how to insert html directly in the page without using an iframe.
Here is an example from MSDN about how to convert the Java code and use Web Form Controls http://msdn.microsoft.com/en-us/library/aa478990.aspx
What is the Asp.Net (.aspx) equivalent to this code?
I have tried something like this, but it doesn't work (http://msdn.microsoft.com/en-us/library/sbz9etab%28v=vs.85%29.aspx)
<%# Register Src="http://wwww.MyExampleSite.com/header/default/header?contentType=html" TagName="header" Tagprefix="cta" %>
<cta:header ID="headerSection" runat="server"/>
Thanks a lot.
As far as I know there is not a nice 1-liner available to you. But you can create a method (lets call it 'dotnetImport') that makes a web request and call it like so:
<%= dotnetImport("http://wwww.ExampleSite.com/header/default/header?contentType=html"); %>
where dotnetImport is defined:
public string dotnetImport(string address) {
WebRequest request = WebRequest.Create (address);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
// dispose the above... use best practices to avoid memory leaks.
return responseFromServer;
}
Disclaimer, I didn't test this, it is meant to be a starting point, not a ready-to-go-paste-in solution.
Enjoy