I want to implement searching of mails in my mail system. I have used simple procedure to search the mails in the database. I want to know the error in the query, which is given below:
import MyPackage.Message;
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.Blob;
import java.sql.Timestamp;
import java.util.ArrayList;
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;
/**
*
* #author ROHIT
*/
#WebServlet(name="SearchServlet", urlPatterns={"/SearchServlet"})
public class SearchServlet 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();
try {
HttpSession session = request.getSession();
String receiverAddress = (String) session.getAttribute("username");
String searchQuery = request.getParameter("SearchMails");
Connection con=null;
PreparedStatement ptmt=null;
PreparedStatement stmt = null;
ResultSet rs= null;
ResultSet rs1 = null;
String driverclass = "oracle.jdbc.driver.OracleDriver";
String dburl="jdbc:oracle:thin:#ROHIT-PC:1521:XE";
String dbuser="system";
String dbpassword="jaihanuman";
ArrayList messageList = new ArrayList();
Message message;
String fileName = "", fileSize = "";
System.out.print("Inside ");
out.print("Inside ");
try
{
Class.forName(driverclass);
con=DriverManager.getConnection(dburl,dbuser,dbpassword);
String sql="SELECT * FROM mail where receiveraddress = ? AND subject LIKE '%' ? '%' AND body LIKE '%?%' AND senderaddress LIKE '%?%' ";
ptmt=con.prepareStatement(sql);
ptmt.setString(1, receiverAddress);
ptmt.setString(2, searchQuery);
ptmt.setString(3,searchQuery);
ptmt.setString(4,searchQuery);
rs=ptmt.executeQuery();
while(rs.next()){
message = new Message();
message.setMailId(rs.getString(1));
message.setSubject(rs.getString(2));
message.setBody(rs.getString(3));
message.setSenderAdress(rs.getString(4));
message.setReceiverAddress(rs.getString(5));
message.setDate(rs.getDate(6));
message.setTimestamp(rs.getTimestamp(7));
message.setAttachmentFlag(rs.getString(8));
message.setLabel(rs.getString(11));
if(rs.getString(8).equals("1")) {
String sql1 = "Select * From attachfile where mailid = ? ";
stmt=con.prepareStatement(sql1);
stmt.setString(1,rs.getString(1));
rs1= stmt.executeQuery();
rs1.next();
fileName = rs1.getString("filename") ;
fileSize = rs1.getString("filesize");
}
message.setPriorityFlag(rs.getString(9));
message.setReadFlag(rs.getString(10));
message.setFileName(fileName);
message.setFileSize(fileSize);
System.out.print("Mesage" + message.getReceiverAddress());
out.print("Mesage" + message.getReceiverAddress());
messageList.add(message);
}
session.setAttribute("messageList", messageList);
response.sendRedirect("Search.jsp");
ptmt.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println( e.getMessage());
}
}
catch(Exception e){e.printStackTrace();}
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 {
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";
}
}
Don't write
AND subject LIKE '%' ? '%' AND body LIKE '%?%' AND senderaddress LIKE '%?%'
Instead use
AND subject LIKE ? AND body LIKE ? AND senderaddress LIKE ?
and set parameter values by
ps.setString(n, "%your_value%");
UPDATE I've checked, and both '%' || ? || '%' and ? versions are working.
Your error seems to be omitting || in AND subject LIKE '%' ? '%' AND body LIKE '%?%' AND senderaddress LIKE '%?%'
You can't use LIKE as shown in your example.
Instead try to use this approach:
String sql="SELECT * FROM mail where receiveraddress = ? AND subject LIKE ? AND body LIKE ? AND senderaddress LIKE ? ";
and then ensure searchQuery is seto to "%<query>%" -- e.g.
//search for messages with subject containing "Metting"
String searchQuery = "%meeting%";
ptmt.setString( 2, searchQuer );
Related
I have created a simple web application.
I need to check, when someone books a room, that the arrival_date is different.
For instance:
Person A: books a room in data: 12/07/2018
Person B: book a room in data: 12/07/2018 ( HE CAN'T because there is the person A yet).
I have this db:
hotel_booking
cid, cname, email, arrival_date, departure_date, person, room, type_room,comment, status, uid.
and this is my code
HotelBooking.java
package hotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author OOPs
*/
public class Hotelbooking 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();
String s1 = request.getParameter("id");
String s2 = request.getParameter("name");
String s3 = request.getParameter("email");
String s4 = request.getParameter("arrivaldate");
String s5 = request.getParameter("departuredate");
String s6 = request.getParameter("person");
String s7 = request.getParameter("rooms");
String s8 = request.getParameter("type_room");
String s9 = request.getParameter("comment");
String s10 = request.getParameter("status");
// sesson..........
HttpSession session=request.getSession(true);
String s11 = (String)session.getAttribute("sessname");
out.println(s11);
try {
Class.forName("com.mysql.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/HotelReservation","root" ,"123456789");
// out.println("Connect");
Statement st = con.createStatement();
// out.println("conncetion successfull");
int rs = st.executeUpdate("insert into hotel_booking (cname,email,arrival_date,departure_date,person,room,type_room,comment,status,uid)values ('"+s2+"','"+s3+"','"+s4+"','"+s5+"','"+s6+"','"+s7+"','"+s8+"','"+s9+"','"+s10+"','"+s11+"')");
// out.println(s1);
// out.println(s2);
out.println("<h1> Register sucsefulltttt </h1>");
/* if(rs == 1)
{
out.println("<script type=\"text/javascript\">");
out.println("alert('send successfully');");
out.println("</script>");
//response.sendRedirect("home.jsp");
}else{
}*/
response.sendRedirect("thankyoureg.jsp");
}catch(Exception e){
out.println("nahiiiiiiiiiiiii" +e);
}
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 {
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>
}
How can I do in your opinion?? Thanks for the help.
Check if a query like the following returns 0.
SELECT count(*)
FROM hotel_booking
WHERE arrival_date <= $1
AND departure_date > $1,
AND room = $2;
If it returns 0 the room isn't occupied at the day the guest wishes to check in. Otherwise it is.
Substitute $1 with the day the guest wishes to arrive and $2 with the room (number or name or whatever you use).
I assumed that check in/out times are handled like:
Check in at the evening of a given day.
Check out in the morning of a given day. That follows a guest can check in at a day another guest checks out.
If that assumption is wrong, you'd have to tweak the comparison operators accordingly.
Also consider to use parametrized queries instead of string concatenation with unsanitized user input values. The latter is dangerous, your application is vulnerable to SQL injection attacks. Also parametrized queries help to find the right representation for a given data type, thus prevent errors that come from misrepresented values.
registration.java
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 srini
*/
#WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet 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
*/
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequset (request,response);
}
public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String phone =request.getParameter("phone");
String username =request.getParameter("uname");
String password =request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt=con.prepareStatement(
"insert into headwy(phone,uname,pass) values(?,?,?)");
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
int i=pstmt.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
pstmt.close();
con.close();
}
catch (Exception e2) {System.out.println(e2);
}
out.close();
}
}
I am trying to check the existing data in database before inserting the data.
But I don't know how to execute the two SQL statement in servlet program.
Because I am first using sql and servlet.
Please provide the solution or give me the idea for the how to check the aleardy existing data in database.
=> Make store procedure like below sample and then call using java code and get your result in output parameter.
CREATE PROCEDURE InsertName
(
#username varchar(25),
#userpassword varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM MyTable WHERE username = #username)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into MyTable(username, userpassword)
VALUES(#username,#userpassword)
END
I have an interface and a servlet file ,whenever I try to run the application program it gives me following error
SEVERE: Class [ LDir/DirSessionLocal; ] not found. Error while loading [ class DirServlet ]
code for interface
package Dir;
import javax.ejb.Local;
#Local
public interface DirSessionLocal {
String getContact(String name1);
String getDetails(String name2);
void rater(String r);
}
code for servlet
import Dir.DirSessionLocal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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 = {"/DirServlet"})
public class DirServlet extends HttpServlet {
#EJB
private DirSessionLocal dirSession;
/**
* 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();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DirServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DirServlet at " + request.getParameter("name") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("nameD") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("rate") + "</h1>");
String a=request.getParameter("nameD");
if(a.equals("abc"))
out.println("<h1>" + dirSession.getContact(a) + "</h1>");
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 {
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>
}
It means that the JVM running your servlet / webapp cannot find the ".class" file for a class with the name Dir.DirSessionLocal.
Depending on how you are "deploying" your servlet, you either need to add the missing class to a JAR file, an WAR file, the webapp's tree on the web server, etc.
I'm having a hard time with this code, every time I test and run it, I always get the same error but cant seem to fix it. The error I'm getting is, can anyone help? Its the last thing I need to get done to get this project working!
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
Servlets.addFunds.processRequest(addFunds.java:43)
Servlets.addFunds.doPost(addFunds.java:95)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
/*
* To change this template, choose Tools > Templates
and open the template in the editor.
*/
package Servlets;
import beans.UserBean;
import eventaccess.DatabaseConnector;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
*
* #author sberry3
*/
#WebServlet(name = "addFunds", urlPatterns = {"/addFunds"})
public class addFunds 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 {
String url = null;
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
String username = request.getParameter("username");
HttpSession session = request.getSession();
UserBean userSession = (UserBean) session.getAttribute("userSession");
double balance = userSession.getBalance();
balance = balance + addFunds;
userSession.setBalance(balance);
session.setAttribute("userSession", userSession);
DatabaseConnector db = new DatabaseConnector();
String queryString = "UPDATE USERS SET balance=" + balance + " WHERE userID=" + userSession.getUserID();
try {
db.createConnection();
db.pstmt = db.conn.prepareStatement(queryString);
db.pstmt.execute();
db.closeConnection();
url = "/store.jsp";
} catch (Exception e) {
e.printStackTrace();
response.setHeader("dbError", "Coudn't connect to database");
}
request.getRequestDispatcher(url).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 "Short description";
}// </editor-fold>
}
It's hard to tell exactly what line it is where your NullPointerException is happening.
Some possibilities:
Missing request parameters. For example, if you requested the page without including the addFunds parameter, you get a NullPointerException on this line:
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
Missing session attribute:
What does the line
UserBean userSession = (UserBean) session.getAttribute("userSession");
return? Is userSession null? If so then later on:
userSession.setBalance(balance);
would cause a NullPointerException. I thinks that's the most likely problem. Do you something like
session.setAttribute("userSession", new UserSession());
anywhere?
On your first request to this jsp
HttpSession session = request.getSession();
will create a new session since there isn't an existing one. So
UserBean userSession = (UserBean) session.getAttribute("userSession");
will set userSession to null, since no Attribute userSession has been created up to this point.
Servlet Mapping
I am new to java ee 6.I am trying to get a servlet request.Every other mapping works fine except /category mapping. Here is my ControllerServlet class.I have used #webServlet annotion for mapping.I have tried to do the mapping in web.xml but no luck.Using netbeans IDE 7.2,Server Glassfish opensource.
import java.io.IOException;
import java.io.PrintWriter;
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(name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/addToCart",
"/viewCart",
"/updateCart",
"/checkout",
"/purchase",
"/chooseLanguage",
"/category"})
public class ControllerServlet extends HttpServlet {
/**
* 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 {
String userPath = request.getServletPath();
// if cart page is requested
if (userPath.equals("/viewCart")) {
userPath = "/cart";
}
//if category page is requested
else if (userPath.equals("/category")) {
}
// if ckeckout page is requested
else if (userPath.equals("/checkout")){
// System.out.println("check");
}
// if user switches language
else if (userPath.equals("/chooseLanguage")){
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/View" + userPath + ".jsp";
System.out.print(url);
try{
request.getRequestDispatcher(url).forward(request, response);
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 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 {
String userPath = request.getServletPath();
// if addToCart action is called
if (userPath.equals("/addToCart")) {
// TODO: Implement add product to cart action
// if updateCart action is called
} else if (userPath.equals("/updateCart")) {
// TODO: Implement update cart action
// if purchase action is called
} else if (userPath.equals("/purchase")) {
// TODO: Implement purchase action
userPath = "/confirmation";
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Link to image of web-inf directory
/categories is not mapped in your servlet. /category is mapped however.