I made a certificate generation software.
However, it can't save files sucessfully.
I mean that the code in the 'RootCertGenerator.java' should generate a 'rootCertificate.cer' file. which is successfully work on pure java.
But when I run 'generateRootCert.jsp' on tomcat it it fails to generate the file
please help me
--generateRootCert.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR"%>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.PreparedStatement" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="myPackage.Utils" %>
<%# page import="myPackage.RootCertGenerator" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Make root Certificate</title>
</head>
<%
RootCertGenerator.execute();
%>
<body>
</body>
</html>
--RootCertGenerator.java
package myPackage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V1CertificateGenerator;
//add 20130424
//import org.bouncycastle.jce.provider.BouncyCastleProvider;
//add 20130427
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
/**
* Basic X.509 V1 Certificate creation.
*/
public class RootCertGenerator
{
public static X509Certificate generateV1Certificate(KeyPair pair)
throws InvalidKeyException, NoSuchProviderException, SignatureException
{
//add 20130424
//Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// generate the certificate
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
certGen.setNotBefore(new Date(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000))); //1 week
certGen.setNotAfter(new Date(System.currentTimeMillis() + (7 * 24 * 60 * 60 * 1000)));
certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
//return certGen.generateX509Certificate(pair.getPrivate(), "BC");
return certGen.generateX509Certificate(pair.getPrivate());
}
//////////added by jeon
public static void pemEncodeToFile(String filename, Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new FileWriter(filename));
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
pw.flush();
pw.close();
}
//////////add 20130427
public static String pemEncodeToString(Object obj, char[] password) throws Exception{
PEMWriter pw = new PEMWriter(new StringWriter(1));
if (password != null && password.length > 0) {
pw.writeObject(obj, "DESEDE", password, new SecureRandom());
} else {
pw.writeObject(obj);
}
String str=null;
pw.write(str);
return str;
//pw.flush();
//pw.close();
}
//////////add 20130427
public static void rootCertUpdate(String rootCert)
{
String sql = "update testca.testca_init set certificate = '"+rootCert+"' where user_id='root'";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
//PreparedStatement pstmt = null;
Statement stmt = null;
//ResultSet rs = null;
String jdbcDriver = "jdbc:mysql://localhost:3306/";
String dbUser = "root";
String dbPass = "forgetmenot";
try{
conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
}catch(Exception ex){System.out.println("Error 2: " +ex);}
}
//////////added by jeon
public static void execute()
throws Exception
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// create the keys
KeyPair pair = Utils.generateRSAKeyPair();
////private key
PrivateKey key = (PrivateKey)pair.getPrivate();
// generate the certificate
X509Certificate cert = generateV1Certificate(pair);
byte[] a = cert.getEncoded();
//System.out.println(a);
//System.out.println(cert);
////////////////////writing root certificate
PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
pemWrt.writeObject(cert);
pemEncodeToFile("rootCertificate.cer", cert, null);
//20130428
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
System.out.println(cert);
//System.out.flush();
pemWrt.flush();
System.setOut(old);
System.out.println("Here: " + baos.toString());
pemWrt.close();
rootCertUpdate(baos.toString());
// show some basic validation
cert.checkValidity(new Date());
cert.verify(cert.getPublicKey());
System.out.println("valid certificate generated");
}
}
You should not only provide the filename of the certificate (rootCertificate.cer), but also the full path where it should be created if you use this class within Tomcat.
You can edit the following line. Instead
pemEncodeToFile("rootCertificate.cer", cert, null);
write something like
pemEncodeToFile("C:/servers/rootCertificate.cer", cert, null);
or
pemEncodeToFile("C:\\servers\\rootCertificate.cer", cert, null);
The file should be created in the mentioned path. Make sure that the folder (in this example "servers") already exists. You could also enhance your method signature by the filename and edit the filename in the JSP.
Related
I have a JSP login page within which I'm taking in username and password and they get passed to my servlet, which validates them using my users table in psaviour database, and then on success or failure, should forward them to the welcome page or back to the login.
Yet I'm stuck trying to connect to my database from my checklogin servlet.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = {"/checkLogin"})
public class checkLogin extends HttpServlet {
private final String DB_URL = "jdbc:mysql://localhost:3306/psaviour";
private final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private final String USER = "root";
private final String PASS = "root";
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");//.toString();
String passkey = request.getParameter("passkey");//.toString();
try {
Class.forName(JDBC_DRIVER);
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt=conn.prepareStatement("SELECT * FROM users WHERE 'username' =
? AND 'passkey' = ?");
stmt.setString(1, username);
stmt.setString(2, passkey);
rs = stmt.executeQuery();
} catch (SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException ce){
ce.printStackTrace();
}
}
while (rs.next()){
//need to point to my welcome.jsp page or
}
//otherwise reload login page....
}
}
How about this?
if (rs.next()){
//need to point to my welcome.jsp page or
RequestDispatcher dispatch = request.getRequestDispatcher("/welcome.jsp");
dispatch.forward(request, response);
} else {
//otherwise reload login page....
request.setAttribute("errorMessage", "Authentication failure!");
response.sendRedirect("/login");
}
if (rs.next()){
response.sendRedirect("success.html");
return;
} else {
//otherwise reload login page...
response.sendRedirect("login.html");
return;
}
How can I retrieve and display images from a database in a JSP page?
Let's see in steps what should happen:
JSP is basically a view technology which is supposed to generate HTML output.
To display an image in HTML, you need the HTML <img> element.
To let it locate an image, you need to specify its src attribute.
The src attribute needs to point to a valid http:// URL and thus not a local disk file system path file:// as that would never work when the server and client run at physically different machines.
The image URL needs to have the image identifier in either the request path (e.g. http://example.com/context/images/foo.png) or as request parameter (e.g. http://example.com/context/images?id=1).
In JSP/Servlet world, you can let a Servlet listen on a certain URL pattern like /images/*, so that you can just execute some Java code on specific URL's.
Images are binary data and are to be obtained as either a byte[] or InputStream from the DB, the JDBC API offers the ResultSet#getBytes() and ResultSet#getBinaryStream() for this, and JPA API offers #Lob for this.
In the Servlet you can just write this byte[] or InputStream to the OutputStream of the response the usual Java IO way.
The client side needs to be instructed that the data should be handled as an image, thus at least the Content-Type response header needs to be set as well. You can obtain the right one via ServletContext#getMimeType() based on image file extension which you can extend and/or override via <mime-mapping> in web.xml.
That should be it. It almost writes code itself. Let's start with HTML (in JSP):
<img src="${pageContext.request.contextPath}/images/foo.png">
<img src="${pageContext.request.contextPath}/images/bar.png">
<img src="${pageContext.request.contextPath}/images/baz.png">
You can if necessary also dynamically set src with EL while iterating using JSTL:
<c:forEach items="${imagenames}" var="imagename">
<img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>
Then define/create a servlet which listens on GET requests on URL pattern of /images/*, the below example uses plain vanilla JDBC for the job:
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
// content=blob, name=varchar(255) UNIQUE.
private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";
#Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageName = request.getPathInfo().substring(1); // Returns "foo.png".
try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {
statement.setString(1, imageName);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
byte[] content = resultSet.getBytes("content");
response.setContentType(getServletContext().getMimeType(imageName));
response.setContentLength(content.length);
response.getOutputStream().write(content);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
That's it. In case you worry about HEAD and caching headers and properly responding on those requests, use this abstract template for static resource servlet.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to upload an image and save it in database?
Simplest way to serve static data from outside the application server in a Java web application
I suggest you address that as two problems. There are several questions and answer related to both.
How to load blob from MySQL
See for instance Retrieve image stored as blob
How to display image dynamically
See for instance Show thumbnail dynamically
I've written and configured the code in JSP using Oracle database.
Hope it will help.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class displayfetchimage
*/
#WebServlet("/displayfetchimage")
public class displayfetchimage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public displayfetchimage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);// Since my data was in first column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
// response.getWriter().append("Served at: ").append(request.getContextPath());
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
}
Try to flush and close the output stream if it does not display.
Blob image = rs.getBlob(ImageColName);
InputStream in = image.getBinaryStream();
// Output the blob to the HttpServletResponse
response.setContentType("image/jpeg");
BufferedOutputStream o = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
o.write(by, 0, index);
index = in.read(by, 0, 32768);
}
o.flush();
o.close();
I used SQL SERVER database and so the answer's code is in accordance. All you have to do is include an <img> tag in your jsp page and call a servlet from its src attribute like this
<img width="200" height="180" src="DisplayImage?ID=1">
Here 1 is unique id of image in database and ID is a variable. We receive value of this variable in servlet. In servlet code we take the binary stream input from correct column in table. That is your image is stored in which column. In my code I used third column because my images are stored as binary data in third column. After retrieving input stream data from table we read its content in an output stream so it can be written on screen. Here is it
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import model.ConnectionManager;
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
Statement stmt=null;
String sql=null;
BufferedInputStream bin=null;
BufferedOutputStream bout=null;
InputStream in =null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = ConnectionManager.getConnection();
int ID = Integer.parseInt(request.getParameter("ID"));
try {
stmt = conn.createStatement();
sql = "SELECT * FROM IMAGETABLE WHERE ID="+ID+"";
ResultSet result = stmt.executeQuery(sql);
if(result.next()){
in=result.getBinaryStream(3);//Since my data was in third column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch=0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(DisplayImage.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
if(bin!=null)bin.close();
if(in!=null)in.close();
if(bout!=null)bout.close();
if(out!=null)out.close();
if(conn!=null)conn.close();
}catch(IOException | SQLException ex){
System.out.println("Error : "+ex.getMessage());
}
}
}
}
After the execution of your jsp or html file you will see the image on screen.
You can also create custom tag for displaying image.
1) create custom tag java class and tld file.
2) write logic to display image like conversion of byte[] to string by Base64.
so it is used for every image whether you are displaying only one image or multiple images in single jsp page.
i have a program that generates a 2 question test from an SQL DB by question and by answers, the questions are selected randomly by a question id. the problem I'm having is when run normally from net beans the the questions don't randomize in fact on a new system that hasn't run before it doesn't show any questions. but when it is debugged with break points it works perfectly fine. i had something like this happen to another program a while ago and not sure how i fixed it, i believe it was an issue between caching and the math Random.
welcome page load to the quizzical controller which on init generates a test in TestDA servlet
package org.citatscc.quiz.controller;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.citatscc.quiz.business.*;
import org.citatscc.quiz.business.TestTaker;
import org.citatscc.quiz.data.TestDA;
public class Quizzical extends HttpServlet {
//the test will be available to all threads
//eventually each TestTaker will store their Test in a Session
private Test myQuiz=null;
#Override
public void init(){
String testName = getServletConfig().getInitParameter("QuizName");
//generate the basic Test which will be used to create each TestTaker's myQuiz
myQuiz = TestDA.generateTest(testName);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("myQuiz", myQuiz);
//here we are simply showing the test generated from the database
String action = request.getParameter("action");
String url = "/QuizView.jsp";
if(action == null)
{
url = "/QuizMain.jsp";
}
else if(action.equals("AddTest"))
{
url = "/QuizAdd.jsp";
}
else if(action.equals("addNewTest"))
{
addNewTest(request);
}
RequestDispatcher dispatch = getServletContext().getRequestDispatcher(url);
dispatch.forward(request, response);
}
public boolean addNewTest(HttpServletRequest request)
{
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
TestDA
package org.citatscc.quiz.data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.citatscc.quiz.business.Question;
import org.citatscc.quiz.business.Test;
public class TestDA{
public static Test generateTest(String testName) {
List<Question> questions = new ArrayList<Question>();
Test test = null;
boolean sameNum = true;
int randNum1 = 0;
int randNum2 = 0;
while(sameNum == true)
{
randNum1 = getRandomNumber();
randNum2 = getRandomNumber();
if(randNum1 == 0 || randNum2 == 0 || randNum1 > 7 || randNum2 > 7 ||
randNum1 == 6 || randNum2 == 6)
{
sameNum = true;
}
else
{
if(randNum1 != randNum2)
{
sameNum = false;
}
}
}
String questionID1 = getQuestionID(randNum1);
String questionID2 = getQuestionID(randNum2);
try {
String questionTxt1 = getQuestionStringByQID(questionID1);
String questionTxt2 = getQuestionStringByQID(questionID2);
questions.add(getAnswers(questionTxt1, questionID1));
questions.add(getAnswers(questionTxt2, questionID2));
test = new Test(testName,questions);
} catch (Exception ex) {
String message = ex.getMessage();
}
return test;
}
public static Question getAnswers(String questionTxt, String questionID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
int counter = 0;
int correctAnswer = 0;
ArrayList<String> answers = new ArrayList<String>();
String preparedQuery = "SELECT * FROM `answers` WHERE `qID` = " + questionID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
while (resultSet.next())
{
answers.add(resultSet.getString(2));
if(resultSet.getInt(3) == 1)
{
correctAnswer = counter;
}
else
{
counter++;
}
}
Question question = new Question(questionTxt, answers, correctAnswer);
return question;
}
public static String getQuestionStringByQID(String qID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
String preparedQuery = "SELECT `question` FROM `questions` WHERE `qID` = " + qID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
String questionText = "";
while (resultSet.next())
{
questionText = resultSet.getString(1);
}
connection.close();
return questionText;
}
public static int getRandomNumber()
{
Random rnd = new Random();
int randomNum = rnd.nextInt(8);
return randomNum;
}
public static String getQuestionID(int randNum)
{
int intqID = randNum * 111;
String qID = "" + intqID;
return qID;
}
public static void insertQuestion(String qID, String qText, List<String>qChoices, int correct)throws SQLException{
String preparedQuestion = "INSERT INTO questions VALUES(?,?)";
}
public static void upDateQuestion(String qID, String qText, List<String>qChoices, int correct) throws SQLException{
}
}
after init is finished it redirects to a menu jsp, after a link to take a test is clicked it hits the quizzical controller before being redirected to QuizView.jsp
<%#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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Quiz View</title>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="cit" uri="/WEB-INF/tld/test.tld" %>
<%#taglib prefix="includes" tagdir="/WEB-INF/tags/" %>
<%# page import="org.citatscc.quiz.business.Test, org.citatscc.quiz.business.Question" %>
<%# page import="java.util.*" %>
<link href="quiz.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="top"><includes:Header image="cit_logo.jpg" alt="cit logo image" tagline="${myQuiz.testName}"/></div>
<div id="leftnav">
</div>
<div id="content">
<form action="Quiz" method="post">
<c:forEach var="question" items="${myQuiz.questionList}" varStatus="qCount">
<h2>${qCount.count}. ${question.questionText} </h2>
<c:forEach var="choice" items="${question.choices}" varStatus="choiceCount" >
<!-- custom tag here -->
<cit:quiz_choiceButton groupName="choice${qCount.count}" text="${choice}" value="${choiceCount.index}" />
</c:forEach>
<br />
</c:forEach>
<input type="submit" name="done" value="Submit" />
</form>
</div>
<div id="footer"><includes:Footer /></div>
</div>
</body>
</html>
any help is appreciated.
The servlet method init() is called once during servlet initialisation. So, you have the same Test for all your following requests.
private Test myQuiz=null;
has the same value for all requests.
More in docs: http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)
I am getting exception for accessing token Socket java.lang.RuntimeException: com.google.apphosting.api.ApiProxy$FeatureNotEnabledException:
Is there any solution to post the request (code) for exchange of token
Here is my code for retrieving code to access token i am using Httpclient is any solution
in index.jsp
response.sendRedirect("https://accounts.google.com/o/oauth2/auth? scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&state=%2Fprofile&response_type=code&client_id=158645513564-88hf7od82d09ipr7uiamd540jpd2da1g.apps.googleusercontent.com&redirect_uri=http://gfksgnbgfcv.appspot.com/index2.jsp");
in index2.jsp
<%#page import="com.login.client.TEST"%>
<%# page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%#page errorPage="errorPage.jsp" %>
<%
String code = request.getParameter("code");
String data=TEST.getParseValue(code);
%>
<%=code%>
<%=data %>
And Java code
package com.login.client;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sourceforge.htmlunit.corejs.javascript.json.JsonParser.ParseException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
public class TEST {
public static String getParseValue(String code) {
String token="no token";
String foros = "code="+code +
"&client_id=<YOUR_CLIENT_ID>" +
"&client_secret=<YOUR_CLIENT_SECRET>" +
"&redirect_uri="+"http://gfksgnbgfcv.appspot.com/index2.jsp" +
"&grant_type=authorization_code";
HttpClient client = new HttpClient();
String url = "https://accounts.google.com/o/oauth2/token";
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
try {
post.setRequestEntity(new StringRequestEntity(foros, null, null));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
String accessToken = null;
try {
client.executeMethod(post);
String jsonTxt = IOUtils.toString(post
.getResponseBodyAsStream());
JSONObject json = (JSONObject) JSONSerializer
.toJSON(jsonTxt);
String resp = post.getResponseBodyAsString();
token = (String) json.getString("access_token");
} catch (HttpException e) {
token=e.getMessage();
throw new RuntimeException(e);
} catch (IOException e) {
token=e.getMessage();
throw new RuntimeException(e);
} catch (Exception e) {
token=e.getMessage();
throw new RuntimeException(e);
}
return token;
}
}
Apache HttpClient is not supported on GAE (at least not without tweaks). You should use URLFetch API.
How can I retrieve and display images from a database in a JSP page?
Let's see in steps what should happen:
JSP is basically a view technology which is supposed to generate HTML output.
To display an image in HTML, you need the HTML <img> element.
To let it locate an image, you need to specify its src attribute.
The src attribute needs to point to a valid http:// URL and thus not a local disk file system path file:// as that would never work when the server and client run at physically different machines.
The image URL needs to have the image identifier in either the request path (e.g. http://example.com/context/images/foo.png) or as request parameter (e.g. http://example.com/context/images?id=1).
In JSP/Servlet world, you can let a Servlet listen on a certain URL pattern like /images/*, so that you can just execute some Java code on specific URL's.
Images are binary data and are to be obtained as either a byte[] or InputStream from the DB, the JDBC API offers the ResultSet#getBytes() and ResultSet#getBinaryStream() for this, and JPA API offers #Lob for this.
In the Servlet you can just write this byte[] or InputStream to the OutputStream of the response the usual Java IO way.
The client side needs to be instructed that the data should be handled as an image, thus at least the Content-Type response header needs to be set as well. You can obtain the right one via ServletContext#getMimeType() based on image file extension which you can extend and/or override via <mime-mapping> in web.xml.
That should be it. It almost writes code itself. Let's start with HTML (in JSP):
<img src="${pageContext.request.contextPath}/images/foo.png">
<img src="${pageContext.request.contextPath}/images/bar.png">
<img src="${pageContext.request.contextPath}/images/baz.png">
You can if necessary also dynamically set src with EL while iterating using JSTL:
<c:forEach items="${imagenames}" var="imagename">
<img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>
Then define/create a servlet which listens on GET requests on URL pattern of /images/*, the below example uses plain vanilla JDBC for the job:
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
// content=blob, name=varchar(255) UNIQUE.
private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";
#Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
private DataSource dataSource;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageName = request.getPathInfo().substring(1); // Returns "foo.png".
try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {
statement.setString(1, imageName);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
byte[] content = resultSet.getBytes("content");
response.setContentType(getServletContext().getMimeType(imageName));
response.setContentLength(content.length);
response.getOutputStream().write(content);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
That's it. In case you worry about HEAD and caching headers and properly responding on those requests, use this abstract template for static resource servlet.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to upload an image and save it in database?
Simplest way to serve static data from outside the application server in a Java web application
I suggest you address that as two problems. There are several questions and answer related to both.
How to load blob from MySQL
See for instance Retrieve image stored as blob
How to display image dynamically
See for instance Show thumbnail dynamically
I've written and configured the code in JSP using Oracle database.
Hope it will help.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class displayfetchimage
*/
#WebServlet("/displayfetchimage")
public class displayfetchimage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public displayfetchimage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);// Since my data was in first column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
// response.getWriter().append("Served at: ").append(request.getContextPath());
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Statement stmt = null;
String sql = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
InputStream in = null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = employee.DbConnection.getDatabaseConnection();
HttpSession session = (HttpSession) request.getSession();
String ID = session.getAttribute("userId").toString().toLowerCase();
try {
stmt = conn.createStatement();
sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
ResultSet result = stmt.executeQuery(sql);
if (result.next()) {
in = result.getBinaryStream(1);
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch = 0;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (bin != null)
bin.close();
if (in != null)
in.close();
if (bout != null)
bout.close();
if (out != null)
out.close();
if (conn != null)
conn.close();
} catch (IOException | SQLException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
}
Try to flush and close the output stream if it does not display.
Blob image = rs.getBlob(ImageColName);
InputStream in = image.getBinaryStream();
// Output the blob to the HttpServletResponse
response.setContentType("image/jpeg");
BufferedOutputStream o = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
o.write(by, 0, index);
index = in.read(by, 0, 32768);
}
o.flush();
o.close();
I used SQL SERVER database and so the answer's code is in accordance. All you have to do is include an <img> tag in your jsp page and call a servlet from its src attribute like this
<img width="200" height="180" src="DisplayImage?ID=1">
Here 1 is unique id of image in database and ID is a variable. We receive value of this variable in servlet. In servlet code we take the binary stream input from correct column in table. That is your image is stored in which column. In my code I used third column because my images are stored as binary data in third column. After retrieving input stream data from table we read its content in an output stream so it can be written on screen. Here is it
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import model.ConnectionManager;
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
Statement stmt=null;
String sql=null;
BufferedInputStream bin=null;
BufferedOutputStream bout=null;
InputStream in =null;
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
Connection conn = ConnectionManager.getConnection();
int ID = Integer.parseInt(request.getParameter("ID"));
try {
stmt = conn.createStatement();
sql = "SELECT * FROM IMAGETABLE WHERE ID="+ID+"";
ResultSet result = stmt.executeQuery(sql);
if(result.next()){
in=result.getBinaryStream(3);//Since my data was in third column of table.
}
bin = new BufferedInputStream(in);
bout = new BufferedOutputStream(out);
int ch=0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
} catch (SQLException ex) {
Logger.getLogger(DisplayImage.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
if(bin!=null)bin.close();
if(in!=null)in.close();
if(bout!=null)bout.close();
if(out!=null)out.close();
if(conn!=null)conn.close();
}catch(IOException | SQLException ex){
System.out.println("Error : "+ex.getMessage());
}
}
}
}
After the execution of your jsp or html file you will see the image on screen.
You can also create custom tag for displaying image.
1) create custom tag java class and tld file.
2) write logic to display image like conversion of byte[] to string by Base64.
so it is used for every image whether you are displaying only one image or multiple images in single jsp page.