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.
Related
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
I know I am not supposed to use this code on JSP, but I just wanna check the connectivity to the database. So I am using this to check with a JSP page. But when I checked it, it threw me an error like this:
Error: No suitable driver found for jdbc:mysql://localhost:3306/wt
Source code of database.jsp:
<section>
<h3><code>Users</code> Table</h3>
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/wt";
String user = "root";
String password = "";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
%>
</section>
I have also included mysql-connector-java-5.1.34-bin.jar to the list of libraries. I am using the following stack:
MySQL 5.6.17
Eclipse Luna (J2EE Perspective)
JBoss 6.1 Distribution Server
Please guide me where I am going wrong. Thanks in advance.
Load the class:
Class.forName(mysqlDriverClass).newInstance();
Before you invoke any jdbc methods?
UPDATE
Include the SQL JSTL class using <%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> and set your datasource <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/TEST" user="root" password="pass123"/> to whatever you need. Be sure to include the jstl jar.
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).
How to configure JSON jar files in jsp?
I am getting error in JSONObject class.
In Java:
// Assuming 'request' is HttpServletRequest
String jsonString = request.getParameter("jsonData");
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
JSONObject jo=new JSONObject(jsonString);
will do the trick.
#user2866902 Do you have jar file in your classpath? Here i used json_simple-1.1.jar for my purpose. You need to import the jar file in jsp, like
<%#page import="org.json.simple.JSONObject"%>
Then you can get the json object like this,
<% net.sf.json.JSONObject responcedata = new net.sf.json.JSONObject(); %>
Hope this helps you..
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;