I am calling a Servlet using its URL address. This is the URL I am typing
http://localhost:7001/ryan/olympics?action=selectCatalog&id=1
This is the Servlet's URL for sure; if I change the address I get
page not found
This is the code for the Servlet.
public class Servlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("*** initializing controller servlet.");
super.init(config);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("selectCatalog")) {
String categoryId = request.getParameter("id");
ProductModelDAO dao4 = new ProductModelDAOImpl("jpac");
if (categoryId != null && !categoryId.trim().equals("")) {
CategoryDAO dao1 = new CategoryDAOImpl("jpac");
try {
Category category = dao1.getCategoryName(categoryId);
request.setAttribute("category", category);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
#SuppressWarnings("unchecked")
List<Product> products = dao4
.getProductsByCategory(categoryId);
request.setAttribute("products", products);
} catch (Exception e) {
e.printStackTrace();
}
url = "SelectCatalog.jsp";
RequestDispatcher requestDispatcher =
getServletContext().getRequestDispatcher(url);
requestDispatcher.forward(request, response);
I get the NullPointerException pointing to the RequestDispatcher's line. Any help?
Try changing "SelectCatalog.jsp" to "/SelectCatalog.jsp", because, as I understand, You want to use an absolute path.
If you want to use a relative path you have to use:
request.getRequestDispatcher(url);
in place of:
getServletContext().getRequestDispatcher(url);
request.getParameter("action");
code is written in doPost method. Are you invoking this servlet from doPost method of calling servlet? URL parameters will not be used by doPost method.
Related
Say, I need to access in JSP exactly 3rd element from the array new int[] {1,2,3,4} passed from a Servlet below:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
request.setAttribute("attr2", new int[] {1,2,3});
RequestDispatcher rd = getServletContext().getRequestDispatcher("/my.jsp");
try {
rd.forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I know about <c:forEach> JSTL tag, but I need something like <c:out value="${attr2[2]}">
I'm developing an application for sending bulk emails from multiple senders in a continuous loop. Sender email-ID's are stored in a csv file and I am reading that in ReadFile class and calling it in servlet class where I am also calling an email utility class which have email sending functions.
ReadFile.java
CsvReader senders;
public List<String> read(){
ArrayList<String> al=new ArrayList<String>();
try {
senders = new CsvReader("C:/Users/dc/Documents/Senderlist.csv");
senders.readHeaders();
while (senders.readRecord()) {
String SenderID = senders.get("SenderID");
// perform program logic here
System.out.println("Sender ID is: "+SenderID );
al.add(SenderID);
}
senders.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return al;
}
Servlet.java:
public class MailController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String ExchangeIP;
private String port;
ReadFile rf;
/**
* #throws IOException
* #see HttpServlet#HttpServlet()
*/
public MailController() throws IOException {
rf=new ReadFile();
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
ExchangeIP = context.getInitParameter("ExchangeIP");
port = context.getInitParameter("port");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
String resultMessage = ""; //null
try {
List sendersInput = rf.read();
// print all the elements in the list
Iterator itr = sendersInput.iterator();
while(itr.hasNext()) {
EmailUtility.sendEmail(ExchangeIP, port, itr.next(), recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail has been sent successfully";
}
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext()
.getRequestDispatcher("/Result.jsp")
.forward(request, response);
}
}
}
While running this I am getting an error:
java.lang.ClassNotFoundException: com.csvreader.CsvReader
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at com.project.util.ReadFile.read(ReadFile.java:20)
at com.project.controller.MailController.doPost(MailController.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
How to resolve this error.
You're missing the opencsv.jar library.
Specify it in your java command with
java -cp opencsv.jar:...
By adding servlet-api.jar from apache tomcat library in to projects->properties->java build path, Solved the error.
The init method gets called again and again on every request in servlet.
Here is the code:
public class PersonInfoController extends HttpServlet {
private static final long serialVersionUID = 1L;
public PersonInfoController() {
super();
}
public void init() throws ServletException {
Connection connection = Database.getConnection();
System.out.println("init method");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<PersonInfoServiceI> myList = new ArrayList();
PersonInfoServiceI instance = new PersonInfoServiceImpl();
myList = instance.getdata();
String jsonstring = new Gson().toJson(myList);
request.setAttribute("List", jsonstring);
RequestDispatcher rd = request.getRequestDispatcher("showdata.jsp");
rd.forward(request, response);
}
public void destroy() {
System.out.println("the destory");
}
}
According to your code init() should call only once when servlet will load on first request. Then after its destruction init() will be called again on new request. In between only your service method will be called. Your code is good having no logical mistakes.
Are you calling init method outside the servlet?
Can you attach you deployment descriptor?
I'm been writing a small login servlet. The login part works just fine, but when I press logout submit button - nothing happens.
Servlet code down bellow:
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7638796169158385551L;
private Database database = Database.getInstance();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.write("<html><head><title>Login form</title></head>");
if (!database.connected) {
outLoginForm(out);
} else {
out.write("Hello " + database.getLoginName() + "!");
outLogoutForm(out);
}
out.write("</body></html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("loginsub") != null) {
if (isParameterEmpty(request, "login")
|| isParameterEmpty(request, "pass")) {
response.getWriter().write("Some fields are empty");
doGet(request, response);
}
try {
database.connect(request.getParameter("login"),
request.getParameter("pass"));
} catch (ExceptionInInitializerError ex) {
response.getWriter().write("Login or password is incorrect");
}
} else if (request.getParameter("logoutsub") != null) {
database.disconnect();
}
doGet(request, response);
}
private boolean isParameterEmpty(HttpServletRequest request,
String parameter) {
if (request.getParameter(parameter).isEmpty())
return true;
return false;
}
protected void outLoginForm(PrintWriter out) {
out.write("<FORM method =\"POST\">");
out.write("Login:<input type=\"text\"name=\"login\"><br>");
out.write("Password:<input type=\"password\"name=\"pass\"><br>");
out.write("<input type=\"submit\"name=\"loginsub\" value=\"Login\"/><br>");
out.write("</FORM><br>");
}
protected void outLogoutForm(PrintWriter out) {
out.write("<FORM method =\"POST>\">");
out.write("<input type=\"submit\"name=\"logoutsub\" value=\"Logout\"/><br>");
out.write("</FORM><br>");
}
}
Can anyone help me find out what's wrong? I'm new to JSP and java servlets.
There is one problem is below line (one extra > after POST
out.write("<FORM method =\"POST>\">");
replace it with
out.write("<FORM method =\"POST\">");
I throw NullPointerException in a java bean and catch the exception in FacesServletWrapper.
in FacesServletWrapper I gets always only ServletException.
how can I catch the specific exception that I throw?
How can I continue from where I throws the exception?
in my bean:
public String getSize() {
try {
Object object = null;
object.equals("");
} catch (Exception e) {
throw new NullPointerException();
}
}
my servlet:
public class FacesServletWrapper extends MyFacesServlet {
public static final String CONFIG_FILES_ATTR = "javax.faces.CONFIG_FILES";
public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
private ServletConfig servletConfig;
private FacesContextFactory facesContextFactory;
private Lifecycle lifecycle;
#Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
FacesContext facesContext = facesContextFactory.getFacesContext(servletConfig.getServletContext(), request, response, (javax.faces.lifecycle.Lifecycle) lifecycle);
try {
super.service(request, response);
} catch (Throwable e) {
Locale locale = (Locale) facesContext.getExternalContext().getSessionMap().get(Constants.LOCALE);
ServletContext context = servletConfig.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/errors/error.jsf");
if (e instanceof NullPointerException) {
//here I catch only ServletException
String error = ResourceUtil.getMessage("Login_failed", locale);
facesContext.getExternalContext().getSessionMap().put("error", error);
dispatcher.forward(request, response);
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/errors/error.jsf");
}
}
}
public void destroy() {
servletConfig = null;
facesContextFactory = null;
lifecycle = null;
}
public ServletConfig getServletConfig() {
return servletConfig;
}
private String getLifecycleId() {
String lifecycleId = servletConfig.getServletContext().getInitParameter(LIFECYCLE_ID_ATTR);
return lifecycleId != null ? lifecycleId : LifecycleFactory.DEFAULT_LIFECYCLE;
}
#Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
this.servletConfig = servletConfig;
facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
lifecycle = (Lifecycle) lifecycleFactory.getLifecycle(getLifecycleId());
}
}
Thanks!
You're calling FacesServlet#service() here:
try {
super.service(request, response);
} catch (Throwable e) {
// ...
}
Here's an extract from its javadoc to learn what kind of exception it may throw:
If a FacesException is thrown in either case, extract the cause from the FacesException. If the cause is null extract the message from the FacesException, put it inside of a new ServletException instance, and pass the FacesException instance as the root cause, then rethrow the ServletException instance. If the cause is an instance of ServletException, rethrow the cause. If the cause is an instance of IOException, rethrow the cause. Otherwise, create a new ServletException instance, passing the message from the cause, as the first argument, and the cause itself as the second argument.
In other words, it will always throw either ServletException or IOException. You need to use Throwable#getCause() to extract the desired cause from the catched ServletException and then determine it further. E.g.
if (e.getCause() instanceof NullPointerException) {
// ...
}