Why won't doGet run processRequest? - java

The way that the program is supposed to work is that there is a javaDB in the background that the servlet can pull from. The servlet gets a keyword from index.jsp and uses that to search the DB to get the information related to that keyword. But the doGet method is not even attempting to run anything in a try/catch block. I know the doGet method is running because I have tried loading test code in there and it does display it, just will not run through the try/catch.
DBConnector.java
package edu.uwf.cs.dsa;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Bernd
*/
public class DBConnector extends HttpServlet {
private Context env;
#Override
public void init(ServletConfig config)
throws ServletException {
super.init(config);
try {
env = (Context) new InitialContext().lookup("java:comp/env");
} catch (NamingException e) {
throw new ServletException(e.getMessage());
}
}
private String getUrl() throws NamingException
{
return (String)env.lookup("jdbc:derby://localhost:1527/JA112");
}
private Connection getConnection()
throws NamingException, ServletException, ClassNotFoundException, SQLException
{
Class.forName((String)env.lookup("org.apache.derby.jdbc.EmbeddedDriver"));
return DriverManager.getConnection(getUrl());
}
private void getMovies(Connection conn, PrintWriter out) throws SQLException
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from Student");
while (rs.next()) {
out.print(rs.getString(1)); out.println("<br />");
out.print(" " + rs.getString(2)); out.println("<br />");
out.print(" " + rs.getString(3)); out.println("<br />");
out.print(" " + rs.getString(4)); out.println("<br />");
out.println(" " + rs.getString(5)); out.println("<br />");
}
}
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, NamingException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = getConnection();
// out.print("<html>\n <head>\n <body>\n<h1>test</h1>\n</body>\n</head>\n</html>");
try {
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DBConnector</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DBConnector at " + request.getContextPath() + "</h1>");
out.println((String)env.lookup("driver"));
out.println("<br />");
out.println(getUrl());
out.println("<br />");
out.println(conn);
getMovies(conn,out);
out.println("<br />");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception e) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, e);
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (NamingException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
index.jsp
<%--
Document : index
Created on : Nov 21, 2012, 9:20:16 PM
Author : Bernd
--%>
<%#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>
<form method="GET" action="/DBServlet/DBConnector">
<h1>Movie Search</h1>
Enter Keyword <input type="text" name="keyword" id="keyword">
<input type="submit" value="submit" id="button">
</form>
</body>
</html>

My best guess is that the env variable it's been initialized to null in normal testing, you need to add the catch block on the processRequest() method so it will became clear this is the error, for now you only have the finally block, so the Exception it's hidden and unclear.
Once you add the block and see the exception, you'll need to check your config file where you defined the java:comp/env , maybe a typo or something like that could be causing the real problem.

Related

while retrieving the image from the DB only the first image is getting displayed in all the row

When i retrieve the image from the DB only the first image
what is inserted is displayed in all the row,
The second and third image is not been retrieved ,
i had attached the screen shot as well for reference.
When i checked the DB all the images are inserted successfully.
New.html
This is my html code
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body><form action="emp" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
Employee ID: <br>
<input type="text" size="20" name="id">
<br>
Employee First Name : <br>
<input type="text" size="20" name="fname">
<br>
Employee Last Name :<br>
<input type="text" name="lname"><br>
Date of Birth :<br>
<input type="date" name="ddate"><br>
Image Upload:<br>
<input type="file" name="myfile"><br>
<script>
function myfunction()
{
var x=document. getElementById("myfile")
}
</script>
<input type="submit" value="Submit">
<iframe name="ifs" src="display" style="width:550px; height:300px" > </iframe>
</form>
</body>
</html>
Emp.java
This is my code to insert the data's into the DB and this was inserted successfully.
package form;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.annotation.MultipartConfig;
/**
* Servlet implementation class emp
*/
#WebServlet("/emp")
#MultipartConfig(maxFileSize = 16177215)
public class emp extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public emp() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#getServletConfig()
*/
//public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
//return null;
//}
/**
* #see Servlet#getServletInfo()
*/
//public String getServletInfo() {
// TODO Auto-generated method stub
//return null;
//}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String id=request.getParameter("id");
String firstname=request.getParameter("fname");
String lastname=request.getParameter("lname");
String date=request.getParameter("ddate");
//String imagename=request.getParameter("myfile");
InputStream input=null;
Part load=request.getPart("myfile");
input=load.getInputStream();
//InputStream fileupload= null;
//Part doc=request.getPart("mydoc");
//fileupload=doc.getInputStream();
//byte[] file=new byte[fileupload.available()];
//fileupload.read(file);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection y=DriverManager.getConnection("jdbc:mysql://localhost:3306/fileupload","root","password");
PreparedStatement x=y.prepareCall("insert into empimage values(?,?,?,?,?)");
x.setString(1, id);
x.setString(2,firstname);
x.setString(3,lastname);
x.setString(4,date);
x.setBlob(5,input);
//x.setString(5,imagename);
//x.setBytes(5,file);
x.executeUpdate();
System.out.println("Date inserted");
request.getRequestDispatcher("new.html").include(request, response);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Display.java
This is my display code to display all the information that was inserted in the data base
package form;
import java.io.IOException;
import java.io.OutputStream;
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.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Blob;
/**
* Servlet implementation class display
*/
#WebServlet("/display")
public class display extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public display() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter out=response.getWriter();
//ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/fileupload","root","password");
PreparedStatement pre=con.prepareCall("select id,firstname,lastname,DOB from fileupload.empimage");
//select * from fileupload.empimage
ResultSet rs=pre.executeQuery();
out.println("<html>");
out.println("<head>");
//out.println("<title> Display Data </title>");
/*out.println("<style>");
out.println("<table>");
{
out.println("<table font-family:arial,sans-serif;>");
out.println("<table border-collapse:collapse;>");
out.println("<table width:100%;>");
}
out.println("<td><tr>");
{
out.println("<td,th border:1px solid #dddddd;>");
out.println("<td,th text-align: left;>");
out.println("<td,th padding: 8px;>");
}
out.println("</style>");*/
out.println("</head>");
out.println("<body>");
out.println("<table style=width:100%;height:auto;>");
out.println("<tr><th>id</th><th>fname</th><th>lname</th><th>date</th><th align='center'> image </th></tr>");
while(rs.next())
{
out.println("<tr>");
int id=rs.getInt(1);
out.println("<td>" + id + "</td>" );
out.println("<td>" + rs.getString(2) + "</td>" );
out.println("<td>" + rs.getString(3) + "</td>");
out.println("<td>" + rs.getString(4) + "</td>");
out.println("<td style='width:150px; height:125px;'><img src="+ "retrieve?"+ id +" style='width:150px;height:125px;'</td>");
out.println("</tr>");
}
// o.write(imgdata);
//o.flush();
//o.close();
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Retrieve.java
This is my code to retrieve the image from the data base and display in the table.
package form;
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 javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Blob;
/**
* Servlet implementation class retrieve
*/
#WebServlet("/retrieve")
#MultipartConfig(maxFileSize = 16177215)
public class retrieve extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public retrieve() {
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
//response.getWriter().append("Served at: ").append(request.getContextPath());
Blob image=null;
byte[] rawbyte=null;
ServletOutputStream out = response.getOutputStream();
try
{
//response.setContentType("text/html; charset=UTF-8");
//String id=request.getQueryString();
//out.println("query string" + id);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/fileupload","root","password");
PreparedStatement pre=con.prepareCall("select image from fileupload.empimage");
//pre.setInt(0,Integer.parseInt(id));
ResultSet rs=pre.executeQuery();
//int id=rs.getInt(1);
//pre.setInt(1,Integer.parseInt(id));
rs.next();
rawbyte=rs.getBytes(1);
out.write(rawbyte);
out.flush();
pre.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
displayed output
Just a guess if you are calling doget() method from Display class and as your code is as below:
<img src="+ "retrieve?"+ id +" style='width:150px;height:125px;'</td>");
so here you have passed the parameter id to retrieve api, but in Retrieve.java class that parameter is not used.
In short you need to update your query as
select image from fileupload.empimage where id=<the parameter>
Hope this post will help you
In your retriever, you should use the id parameter from the HTTP request :
String query = "select image from fileupload.empimage where id = ?";
PreparedStatement pre = con.prepareCall(query);
pre.setString(1,request.getParameter("id"));
ResultSet rs = pre.executeQuery();

JSP Upload file error

I made a JSP that is supposed to upload a file into a directory and it shows me an error when trying to connect:
Here you can see my codes:
If anyone can help me i would appriciate it.
package src;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class Controller extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
String saveFile="c:\\uploaddir\\";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String actiune="afiseaza";
PrintWriter out=response.getWriter();
if (request.getParameter("actiune")!=null)
{
actiune = request.getParameter("actiune");
}
if (actiune.equals("afiseaza"))
{
doAfiseaza(request, response);
}
if (actiune.equals("sterge"))
{
doDeleteFile(request, response);
}
try{
boolean ismultipart=ServletFileUpload.isMultipartContent(request);
if(!ismultipart)
{
}
else
{
FileItemFactory factory= new DiskFileItemFactory();
ServletFileUpload upload= new ServletFileUpload(factory);
List items=null;
try{
items=upload.parseRequest(request);
}catch(Exception e)
{
}
Iterator itr=items.iterator();
while(itr.hasNext())
{
FileItem item= (FileItem)itr.next();
if(item.isFormField())
{
}
else
{
String itemname=item.getName();
if((itemname==null)||itemname.equals(""))
{
continue;
}
String filename=FilenameUtils.getName(itemname);
File f=checkExist(filename);
item.write(f);
}
}
}
}catch(Exception e)
{
}
finally{
out.close();
}
}
private void doDeleteFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String fName=URLDecoder.decode(request.getParameter("fis"));
File f = new File("c:\\uploaddir\\"+fName);
f.delete();
doAfiseaza(request, response);
}
private void doAfiseaza(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String dir = "c:\\uploaddir";
int er = 0;
File[] lista = null;
try
{
File f = new File(dir);
lista = f.listFiles();
}
catch(Exception ex)
{
er=-1;
}
request.setAttribute("eroare", new Integer(er));
request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/lista.jsp");
rd.forward(request, response);
}
// <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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Prima aplicatie";
}// </editor-fold>
private File checkExist(String fileName) {
File f=new File(saveFile+"/"+fileName);
if(f.exists())
{
StringBuffer sb=new StringBuffer(fileName);
sb.insert(sb.lastIndexOf("."), "-"+new Date().getTime());
f=new File(saveFile+"/"+sb.toString());
}
return f;
}
}
so now i have no errors but it doesnt upload my folder so i dont know what to do.
Since your original question was about JSP, here is some demonstration code.
<%# page import="java.util.*,
java.io.*,
org.apache.commons.fileupload.*,
org.apache.commons.fileupload.servlet.*,
org.apache.commons.fileupload.disk.*,
org.apache.commons.fileupload.util.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.print("Request content length is " + request.getContentLength() + "<br/>");
if(isMultipart){
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
FileItemStream item = null;
String name = "";
InputStream stream = null;
while (iter.hasNext()){
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(item.isFormField()){out.println("Form field " + name + " with value "
+ Streams.asString(stream) + "<br/>");}
else {
name = item.getName();
if(name != null && !"".equals(name)){
String fileName = new File(item.getName()).getName();
out.println("Client file " + item.getName() + " <br/>with file name "
+ fileName + " uploaded.<br/>");
File file = new File("C:/uploaddir/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
long fileSize = Streams.copy(stream, fos, true);
out.print(fileName
+ " was uploaded to the fileUploads folder. Size was " +
fileSize + "<br/>");
}
}
}
} else out.print("Wrong request type!");
%>
call that JSP with
<html><body>
<form enctype="multipart/form-data" action="fileUpload3.jsp" method="post">
<input type='file' name='file1'/><br/>
<input type='file' name='file2'/><br/>
<input type='file' name='file3'/><br/>
Type message:<input type="text" name="message" /><br/>
<input Type='submit' value='Submit'/>
</form>
</body></html>
Put both files in your web app's root folder.

java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). why such exception is occurring and how to resolve it

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
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 java.sql.Statement;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author hp
*/
#WebServlet(name = "Getdetails", urlPatterns = {"/Getdetails"})
public class Getdetails extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
Connection con = null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs = null;
String debitcard = new String();
String debitcardno = new String();
String accountno = new String();
String account = new String();
String cvv = new String();
String pin = new String();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bussinesssolutions?zeroDateTimeBehavior=convertToNull", "root", "root");
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, card.pin from card inner join regsiter on card.edebitcardno = regsiter.debitcardno");
ps.setString(1, debitcard);
ps.setString(2, account);
ps.setString(3, cvv);
ps.setString(4, pin);
rs = ps.executeQuery();
debitcardno = rs.getString("debitcardno");
accountno = rs.getString("accountno");
cvv = rs.getString("cvv");
pin = rs.getString("pin");
request.getSession().setAttribute("debitcardno", debitcardno);
request.getSession().setAttribute("accountno", accountno);
request.getSession().setAttribute("cvv", cvv);
request.getSession().setAttribute("pin", pin);
RequestDispatcher rd = request.getRequestDispatcher("Getdetails");
rd.forward(request, response);
} catch (ClassNotFoundException | SQLException | ServletException | IOException e) {
out.print(e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
ps.close();
st.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Bankdetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
// <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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
`return` "Short description";
}// </editor-fold>
}
I am getting the above mentioned exception. Don't know why.why such exception is occurring and how to resolve it. I want to fetch the details from the database of the above details but maybe some mistake in code that it is not happening
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, " +
"card.pin from card inner join regsiter on card.edebitcardno = regsiter.debitcardno");
There's no ? parameters in this statement. None of the following would work.
ps.setString(1, debitcard);
ps.setString(2, account);
ps.setString(3, cvv);
ps.setString(4, pin);
You need to actually provide parameters to assign.
ps = con.prepareStatement("select card.debitcardno, card.accountnno, card.cvv, " +
"card.pin from card inner join regsiter on " +
"card.edebitcardno = regsiter.debitcardno " +
"where card.debitcardno=? AND card.accountno=? AND card.cvv=? AND card.pin=?");

display username after login in jsp

i have a login page which connects to a database for validation through a servlet.
in the servlet after successful login i'm using request dispatcher to login-success.html
here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* Servlet implementation class DoLogin
*/
#WebServlet("/DoLogin")
public class DoLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DoLogin() {
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
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
//Browser Back Button Disable Script After Logout
out.println("<script>");
out.println("javascript:window.history.forward(1)");
out.println("</script>");
out.println("<body style=\"background-color : rgb(41,85,153);\">");
//Invalidate The Session.
HttpSession session = request.getSession(false);
try
{
session.invalidate();
out.println("<h3><font family=\"Times New Roman\" color=\"white\">Successfully Logout</font></h3>");
out.println("<form action=\"/CloudMoV/login.html\" method=\"post\">");
out.println("<br />");
out.println("<input type=\"submit\" alt=\"submit\" value=\"Login Again!\"/>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
catch (Exception ee)
{
out.println(ee);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// out.println("<html>");
// out.println("<head>");
// out.println("<title>");
// out.println("<html>");
// out.println("</title>");
// out.println("</head>");
// out.println("<body style=\"background-color : black;\">");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet res = null;
//variable for checking the values true and false.
boolean success=false;
//creating session
HttpSession session = request.getSession(true);
try{
DbConnection db = new DbConnection();
con = db.connDb();
//Receiving Values From HTML FORM
String thisname=request.getParameter("username");
String thispwd=request.getParameter("password");
stmt = (Statement) con.createStatement();
//Query for selecting user name and password from database.
String q = "select username, password from register where username='"+thisname+"'";
res = stmt.executeQuery(q);
while(res.next())
{
if ((thisname.equals(res.getString("username"))) && (thispwd.equals(res.getString("password"))))
{
// out.println("<br /><br /><h3><font family=\"Times New Roman\" color=\"white\">You're successfully logged in. <br />Welcome "+res.getString("username")+"</font></h3>");
success = true;
}
}
}
catch (SQLException e)
{
throw new ServletException("Servlet Could not display records.", e);
}
catch (Exception e)
{
throw new ServletException("Exception.", e);
}
// if(success==true)
// {
// out.println("<font color=\"white\">session Id: " + session.getId() + "</font><br><br>");
// session.setAttribute("username", request.getParameter("username"));
//
// //Logout Button
// out.println("<form onclick=\"doGet("+request+","+ response+")\" >");
// out.println("<input type=\"submit\" value=\"logout\">");
// out.println("</form>");
// }
if(success==true)
{
session.setAttribute("username", request.getParameter("username"));
RequestDispatcher rd = request.getRequestDispatcher("/login-success.html");
rd.forward(request, response);
}
if(success==false)
{
// out.println("<br /><h3 style=\"text-align:center;color:#FFFFFF;margin-top:150px\">Invalid User Name or Password</h3>");
// out.println("<br /><h3 style=\"text-align:center;color:#FFFFFF;text-decoration:underline\">Go Back</h3>");
session.invalidate();
RequestDispatcher rd = request.getRequestDispatcher("/login.html");
rd.forward(request, response);
}
//
// out.println("</body>");
// out.println("</html>");
}
}
in the login-success i want to display the username. how do i do it?
i believe i should first change the login-success.html to login-success.jsp
You are setting user name value to session attribute "username" so you can use this EL expression ${sessionScope.username}
in your jsp. You should use it in jstl tag
Create http sesson and push login dto with user information and access the session variable from any jsp page and retrieve user/login information.thats it
After authentication success, set username attribute in session
session.setAttribute("loggedInUser_userName", userName);
Since HTML is static page, it needs ajax call to update page, Prefer JSP over HTML.
Use El Expression ${} to print username. No need of JSTL tag library for El Expression.
And in your username span
<span>${loggedInUser_userName}</span>

Call Java servlet from Android

I'm trying to get the output from a servlet on an Android phone.
This is my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Bert Verhelst <verhelst_bert#hotmail.com>
*/
public class servlet1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>processing...</h1>");
out.println("</body>");
out.println("</html>");
}
// <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
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>doget...</h1>\n"
+ "</body></html>");
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>dopost...</h1>\n"
+ "</body></html>");
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is my Android main page:
package be.smarttelecom.MyTest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView output = (TextView) findViewById(R.id.output);
try {
output.append("starting\n");
RestClient client = new RestClient("http://10.0.0.188:8084/Servlet_1/servlet1");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
output.append("after execute\n");
String response = client.getResponse();
output.append("class - " + response + "\n" );
output.append(response);
output.append("done\n");
}
catch (Exception ex) {
output.append("error: " + ex.getMessage() + "\n" + ex.toString() + "\n");
}
}
}
And finally we have the RestClient:
package be.smarttelecom.MyTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Unfortunately this doesn't work. Here is what I get for output (null),
What am I doing wrong?
I request the DoGet method of my servlet and convert the output to a string, but it appears to be empty.
I allowed the Internet connection in the manifest file just after the closing bracket of application,
<uses-permission android:name="android.permission.INTERNET" />
Romain Hippeau wrote in a comment:
Does the call ever get to the servlet? What does the server see is being sent? What is the server sending back?
That was the problem! I disabled my firewall and now it works :)

Categories