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.
Related
I am using Retrofit to connect to my REST API. Please check the below code
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
*
* #author The Ace
*/
public class SignUpLoaderServlet 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(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("RUNNING!!!!!!!!!!!");
try {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.MESSAGING_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProfesionalBodyList>> call = endPoint.getAllProfesionalBodyLists();
call.enqueue(new Callback<List<ProfesionalBodyList>>() {
#Override
public void onResponse(Call<List<ProfesionalBodyList>> call, Response<List<ProfesionalBodyList>> rspn)
{
try {
List<ProfesionalBodyList> body = rspn.body();
for(int i=0;i<body.size();i++)
{
System.out.println(body.get(i).getProfessionalBody());
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
requestDispatcher.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(Call<List<ProfesionalBodyList>> call, Throwable ex) {
ex.printStackTrace();
}
});
} finally {
}
}
// <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);
}
}
This code fires the below exception
java.lang.NullPointerException
at com.tekhinno.xxx.signup.SignUpLoaderServlet$1.onResponse(SignUpLoaderServlet.java:80)
at retrofit2.OkHttpCall$1.callSuccess(OkHttpCall.java:132)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:111)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
However if I replace the below code line into the finally() block, the issue is gone.
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
requestDispatcher.forward(request, response);
I am not sure why it is not working inside the onResponse(). It is imporant to run there because I load items from the REST API before the forward action take place.
Any idea?
The issue is mainly because the call was Asynchronous and the requestDispatcher object was already executed. Then the answer is to stay until the REST call complete its work load. That means, do it Synchronous.
Retrofit can be done in Synchronous manner as well. Below is the code.
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("RUNNING!!!!!!!!!!!");
try {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.MESSAGING_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProfesionalBodyList>> call = endPoint.getAllProfesionalBodyLists();
body = call.execute().body();
for (int i = 0; i < body.size(); i++) {
System.out.println(body.get(i).getProfessionalBody());
}
} finally {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
request.setAttribute("ProfesionalBodyList", body);
requestDispatcher.forward(request, response);
}
}
Simpy pay attention to the place where it says call.execute().body();. This is the Synchronous call.
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.
I have JAVA EE Application I,m trying to call EJB from servelate but everytime I have this error
HTTP Status 404 - Not Found
type Status report
messageNot Found
descriptionThe requested resource is not available.
I check the glassfish log I see this
SEVERE: Class [ Lejbexercises/StatlessFundManagerBean; ] not found. Error while loading [ class controllers.TestStatelessEJB ]
ejb class
/*
* 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 ejbexercises;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
/**
*
* #author
*/
#Stateless
#LocalBean
public class StatlessFundManagerBean {
public double addFunds(double balance, double amount) {
balance += amount;
return balance;
}
public double withdrawFunds(double balance, double amount) {
if (balance < 0) {
return 0.0;
} else {
balance -= amount;
return balance;
}
}
}
/*
* 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 controllers;
import ejbexercises.StatlessFundManagerBean;
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;
/**
*
* #author
*/
#WebServlet(name = "TestStatelessEJB", urlPatterns = {"/TestStatelessEJB"})
public class TestStatelessEJB extends HttpServlet {
#EJB(name = "sfm")
private StatlessFundManagerBean sfm;
/**
* 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 {
double balance = 1200;
balance = (double) sfm.addFunds(balance, Double.parseDouble("1200"));
out.println("1st balance=" + balance );
} 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>
}
From EJB Documentation (http://docs.oracle.com/cd/E13222_01/wls/docs100/ejb30/annotations.html#wp1416481):
name - Specifies the name by which the referenced EJB is to be looked up in the environment.
You are using (name = "sfm") and this means that container will lookup bean known to it as "sfm" which is wrong in your case unless you have defined bean name in beans.xml (but you didn't mention it, so I assume, you haven't).
Just remove the (name="sfm ) part and do not forget to redeploy your app.
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 );