i had written a jsp page with database connectivity getting the data from the database and printing it json format. And now i want that json data to be sent to the dojo data grid
Any help?
here is my jsp code
<%# page import="javax.security.auth.Refreshable"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="org.json.simple.JSONObject"%>
<%# page import="org.json.simple.JSONArray"%>
<%#page import="java.util.LinkedList"%>
<%#page import="java.util.List"%>
<%
JSONObject responseObj = new JSONObject();
List<JSONObject> data = new LinkedList<JSONObject>();
try {
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "3306";
String userName = "root";
String upassword = "";
String databaseName = "testind";
int datacount = 0;
String connectionURL = "jdbc:" + dbms + "://" + serverName
+ ":" + portNumber + "/" + databaseName;
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
userName, upassword);
System.out.println("connection::" + connection);
String strQuery = "select * from user";
System.out.println(strQuery);
PreparedStatement st = connection.prepareStatement(strQuery);
ResultSet rs = st.executeQuery();
while(rs.next())
{
datacount++;
JSONObject dataobject = new JSONObject();
dataobject.put("sl",(String.valueOf(datacount)));
dataobject.put("name",rs.getString(1));
dataobject.put("email",rs.getString(2));
dataobject.put("mobi",rs.getString(3));
dataobject.put("add",rs.getString(4));
data.add(dataobject);
System.out.println("name&email::"+rs.getString(1) +","+rs.getString(2));
}
responseObj.put("data",data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
//writer.write("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
writer.write(" "+responseObj+"");
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
}`enter code here`
%>
here, i am getting the data from the database in the json format as following:
{"data":[{"sl":"1","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"},{"sl":"2","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"}]}
Remove data object in json
for example,
responseObj.put("data", data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" + responseObj + "}");
writer.write("{\"identifier\":\"Id\",\"label\":\"Organisation\",\"items\":" + responseObj.remove("data") + "}");
//writer.write(" " + responseObj + "");
writer.flush();
writer.close();
Related
I'm trying to display image from MySQL server on to the browser. But the following code works on Internet Explorer but not working on Chrome and Mozilla Firefox browser.
I'm new to JSP and I've already tried code from this question but didn't work .Displaying image in jsp from database
`<%# include file="connect.jsp" %>
<%#page import="java.sql.*,java.io.*"%>
<%# page import="java.sql.*,java.io.*,java.util.*" %>
<%
try{
int id = Integer.parseInt(request.getParameter("id"));
Statement st=connection.createStatement();
String strQuery = "select image from user where id="+id+"" ;
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next())
{
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next())
{
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st.close();
response.reset();
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}%>
To retrieve multiple images from the SQL database and display in JSP pages you can do this:
<%
int id = Integer.parseInt(request.getParameter("imgid"));
try {
Connection con=DriverManager.getConnection("jdbc:sqlserver://XXXXX\\SQLEXPRESS14;databaseName=Student;user=XX;password=XXXXX");
Statement st = con.createStatement();
String strQuery = "select image from login_users where id='" + id + "'";
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next()) {
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next()) {
byte[] bytearray = new byte[4096];
int size=0;
InputStream sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1) {
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
sImage.close();
rs.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
I have documents saved in a SQL Server database as varbinary(MAX).
I am trying to retrieve the document from the database with below code. The problem I am facing is that no matter the browser I use, I don't get any response back. No dialog the browser just displays the turning circle.
Any suggestions would be highly appreciated..
if (e.ButtonID != "Download")
return;
int id = 2;
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["bexsConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Title, WillData, MIMEType from Will_documents where Doc_id = #Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["WillData"];
contentType = sdr["MIMEType"].ToString();
fileName = sdr["Title"].ToString();
Response.Buffer = true;
Response.Charset = "";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
con.Close();
}
}
Eventually got it Working.
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", name));
Response.AddHeader("Content-Length", documentBytes.Length.ToString());
Response.BinaryWrite(documentBytes);
Response.Flush();
Response.Close();
This is my JSP coding, I am using link to redirect to JSP page :
Excel.jsp
<%#page import="java.sql.*"%>
<%#page import="java.sql.SQLException"%>
<%#page import="org.apache.poi.hssf.usermodel.*"%>
<%#page import=" java.io.*"%>
<%
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url + dbName", "userName",
"password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from openstock");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("fisocon");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("iname");
rowhead.createCell((short) 1).setCellValue("wname");
rowhead.createCell((short) 2).setCellValue("catname");
rowhead.createCell((short) 3).setCellValue("class");
rowhead.createCell((short) 4).setCellValue("unit");
rowhead.createCell((short) 5).setCellValue("nname");
int i = 1;
while (rs.next()){
out.println("hai2");
HSSFRow row = sheet.createRow((short) i);
row.createCell((short)
0).setCellValue(Integer.toString(rs.getInt("iname")));
row.createCell((short) 1).setCellValue(rs.getString("wname"));
row.createCell((short) 2).setCellValue(rs.getString("catname"));
row.createCell((short) 3).setCellValue(rs.getString("class"));
row.createCell((short) 4).setCellValue(rs.getString("unit"));
row.createCell((short) 5).setCellValue(rs.getString("nname"));
i++;
}
String yemi = "d:/xls/test.xls";
FileOutputStream fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
%>
In this coding, createcell is strikeout. I don't know why it is.
There is no errors in coding. I also add poi 3.14 jar file in library.
My output page displays as empty. Please help me. Thanks in advance.
Page is empty because everything You made is outside of page.
BTW doing such in JSP is the worst idea.
Move this code to servlet, here is tip how to return binary data.
java servlet response returning data
Add
response.contentType = "application/vnd.ms-excel"
and JPS page should only have link
The additional effect: servlet code is more, more friendly to debugging.
This is the code of my index.jsp:
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="org.apache.tomcat.jdbc.pool.DataSource"%>
<%#page import="org.apache.tomcat.jdbc.pool.PoolProperties"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div id="query">
<%
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#localhost:1521:XE");
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("scott");
p.setPassword("tiger");
p.setMaxActive(100);
p.setInitialSize(10);
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
con = datasource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 777 from dual");
while (rs.next()) {
System.out.println(rs.getString(1));;
}
rs.close();
st.close();
%>
</div>
</body>
</html>
This is the error im getting for running that code:
I dont understand why this code runs for oracle:
<%
String dcn = "oracle.jdbc.OracleDriver";
Class.forName(dcn);
String serverName = "localhost";
String portNumber = "1521";
String sid = "orcl";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
String username = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stm = conn.createStatement();
String query = "SELECT * from emp";
ResultSet data = stm.executeQuery(query);
while (data.next()) {
String number = data.getString("EMPNO");
String name = data.getString("ENAME");
%> <%=number%> <%=name%> <br> <%
}
%>
Dispite the fact that I imported the drivers properly. How should i do this in mysql ? Tried replacing driver but doesnt work either.
MYSQL Code:
<div id="query">
<%
String username = "j2ee";
String password = "j2ee123456";
String dbName = "testjava";
String dbHost = "localhost";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException msg) {
out.println("Error loading driver:" + msg.getMessage());
}
try {
String url = "jdbc:mysql://" + dbHost + ":3306/" + dbName;
Connection Conn = DriverManager.getConnection(url, username, password);
Statement Stmt = Conn.createStatement();
String query = "SELECT * FROM example_autoincrement";
ResultSet rs = Stmt.executeQuery(query);
while (rs.next()) {
int numExp = rs.getInt("id");
String nombre = rs.getString("data");
%> <%=numExp%> <%=nombre%> <%
}
} catch (SQLException e) {
String err1Msg = e.getMessage();
%>
<STRONG><EM> <%=err1Msg%> </EM></STRONG>
<%
}
%>
The error im getting on VPS
Error loading driver:com.mysql.jdbc.Driver No suitable driver found for jdbc:mysql://localhost:3306/testjava
However I dont get this error with XAMPP running same code...
Solved: after putting the mysql driver in the WEB-INF/lib folder had to restart tomcat.
I am new to jsp.I have a table named employee now I want to insert image to datatase using a name as request parameter.The table already have name,age,id,phonenumber,email,password as fields.image is my new field I created now.When updating image field with new blob image it is not showing error but image is not inserting. Here's my try :
// My form to fileupload
<form name="frm" action="Image.jsp" method="post">
<center>Name:<input type="text" name="name"><br></center><br>
<center><br><br> <input type="submit" value="Submit"></center>
</form>
//(Image.jsp )My pgogram to get file from client and store in database
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="org.apache.commons.io.output.*"%>
<%# page import="org.apache.commons.fileupload.servlet.*"%>
<%# page import="org.apache.commons.fileupload.disk.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = null;
int insertQuery = 0;
byte[] b = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
String sql = "update employee set image=? where name=? ";
pstatement = connection.prepareStatement(sql);
pstatement.setString(2, request.getParameter("name"));
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
pstatement.setBytes(1, b);
insertQuery = pstatement.executeUpdate();
pstatement.close();
connection.close();
%>
<input type="submit" value="Login">
</body>
</html>
<% # page import="java.io.*" %>
<% # page import="java.sql.*" %>
<% # page import="java.util.zip.* "%>
<%
String saveFile="";
String contentType=request.ContentType();
if((contentType != null) &&(contentType.indexOf("multipart/form-data")>=0))
{
DataInputStream in= new DataInputStream(request.getInputStream());
int formDataLength=request.getContentLength();
byte dataBytes[]= new byte[formDataLength];
int byteread=0;
int totalbyteread=0;
while(totalbyteread<formDataLength)
{
byteread=in.read(dataBytes,totalbyteread,formDataLength);
totalbyteread =byteread+1;
}
String file= new String(dataBytes);
saveFile=file.subString(file.indexOf("filename=\"")+10);
saveFile= saveFile.subString(0,saveFile.indexOf("\n"));
saveFile=saveFile.subString(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int lastIndex=contentType.lastIndexOf("=");
String boundry=contentType.subString(lastIndex+1,contentType.length());
int pos;
pos=file.indexOf("filename=\"");
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
int boundrylocation=file.indexOf(boundry,pos)-4;
int startpos=((file.subString(0,pos)).getBytes()).length;
int endpos=((file.subString(0,boundryloction)).getBytes()).length;
File ff= new File(saveFile);
FileOutputStream fileout= new FileOutputStram(ff);
fileout.write(dataBytes,startpos,(endpos-startpos));
fileout.flush();
fileout.close();
%>
<Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<%out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = fis;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
File f= new File(saveFile);
pstatement=connection.prepareStatement("insert into employee(name of image cloumn) values(?)");
pstatement.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = pstatement.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){e.printStackTrace();}
}
}
%>