This is the servlet code where I get the Nullpointer exxception.There are no objects that I need to get Initialized. What would be the problem?
package sms.controller;
import sms.model.DbConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class StaffManagementServlet extends HttpServlet {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PrintWriter out;
JSONArray jsonArray;
JSONObject jsonObject;
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public StaffManagementServlet() {
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
doPost(request, response); //line 50
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
System.out.println(action+"--------");
if (action.equalsIgnoreCase("registration")) { //line 63
userRegistration(request, response);
}
if (action.equalsIgnoreCase("login")) {
userLogin(request, response);
}
if (action.equalsIgnoreCase("section")) {
getSection(request, response);
}
if (action.equalsIgnoreCase("question")) {
getQuestion(request, response);
}
if (action.equalsIgnoreCase("semister")) {
getSemister(request, response);
}
if (action.equalsIgnoreCase("branch")) {
getBranch(request, response);
}
if (action.equalsIgnoreCase("forget")) {
forgetPassword(request, response);
}
if (action.equalsIgnoreCase("setPass")) {
setPassword(request, response);
}
}
This is the error I get when I run the sevlet on the server.
java.lang.NullPointerException
sms.controller.StaffManagementServlet.doPost(StaffManagementServlet.java:63)
sms.controller.StaffManagementServlet.doGet(StaffManagementServlet.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Your action is NULL so when you call action.equalsIgnoreCase("registration"). It throws NullPointerException.
BEST practice for this case is using CONSTANT as first variable when compare.
if ("registration".equalsIgnoreCase(action)) {
// ....
} else if ("login".equalsIgnoreCase(action)) {
// ....
}
// ....
else {
throw new ServletException("Invalid action");
// OR process default action here if action missing
}
action is null. So calling a method on it throws a NullPointerException. You need to pass an action parameter to your request, or to deal with the possibility of action being null in the doPost() method.
Related
This question already has answers here:
Should I override service() or doPost()?
(5 answers)
Overriding HttpServlet service method
(2 answers)
Closed 12 months ago.
I am fresher in java web application development .
I tried just running the servlet file(not even through html file just servlet file) .
Service method is executing and displaying the statement (I commented in order to execute the get method print statement)
but doGet and doPost is not been called.
Will anyone can help me
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Myservlet
*/
#WebServlet("/Myservlet")
public class Myservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Myservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/*PrintWriter out = response.getWriter();
out.print("In service method");*/
//response.getWriter().println("Hello Server service method");
}
/**
* #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());
response.getWriter().println("Hello Server, Get method");
}
/**
* #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);
response.getWriter().println("Hello Server, Post method");
}
}
I am trying to do long polling in a struts web application. I start an AsyncContext inside an ActionSupport action method, do some time-consuming work async, and then would like to send the SUCCESS response to struts.
I know that I can do PrintWriter pw = asyncContext.getResponse().getWriter(); and write a raw response, but I would like to somehow signal struts to proceed with the predefined result in struts.xml. Is this possible?
<action name="myAction" method="action1" class="myActionClass">
<result name="success" type="redirectAction">
/pages/myPage.jsp <!-- I want to run this from async --->
</result>
</action>
In non-async action I can simply return SUCCESS and struts takes care of everything, but I am having trouble with achieving a similar effect with async action. This is what I have so far:
public void action1() {
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
final AsyncContext asyncContext = req.startAsync(req, res);
asyncContext.start(new Runnable() {
public void run() {
// Some time-consuming polling task is done here
asyncContext.complete();
// Can I somehow proceed to predefined struts result from here?
}
});
}
Currently it seems cannot be done clearly. I am working if I can import this support to Struts but for now, I have a hack which works. I extended StrutsExecuteFilter as below:
package me.zamani.yasser.ww_convention.utils;
import org.apache.struts2.dispatcher.PrepareOperations;
import org.apache.struts2.dispatcher.filter.StrutsExecuteFilter;
import org.apache.struts2.dispatcher.filter.StrutsPrepareFilter;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Created by user on 8/31/2017.
*/
public class MYStrutsAsyncExecuteFilter extends StrutsExecuteFilter {
public final int REQUEST_TIMEOUT = 240000;//set your desired timeout here
private ExecutorService exe;
#Override
public void init(FilterConfig filterConfig) throws ServletException {
int size = 41;//set your desired pool size here
exe = Executors.newFixedThreadPool(
size,
new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "My Struts Async Processor");
}
}
);
super.init(filterConfig);
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
if (excludeUrl(request)) {
chain.doFilter(request, response);
return;
}
// This is necessary since we need the dispatcher instance, which was created by the prepare filter
if (execute == null) {
lazyInit();
}
final ActionMapping mapping = prepare.findActionMapping(request, response);
//if recursion counter is > 1, it means we are in a "forward", in that case a mapping will still be
//in the request, if we handle it, it will lead to an infinite loop, see WW-3077
final Integer recursionCounter = (Integer) request.getAttribute(PrepareOperations.CLEANUP_RECURSION_COUNTER);
if (mapping == null || recursionCounter > 1) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
/* I ADDED THESE */
final AsyncContext context = req.startAsync();
context.setTimeout(REQUEST_TIMEOUT);
context.addListener(new AsyncListener() {
public void onComplete(AsyncEvent asyncEvent) throws IOException {
}
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Request Timeout");
}
public void onError(AsyncEvent asyncEvent) throws IOException {
context
.getResponse()
.getWriter().write("Processing Error");
}
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
}
});
exe.execute(new ContextExecution(context, mapping));
}
}
private boolean excludeUrl(HttpServletRequest request) {
return request.getAttribute(StrutsPrepareFilter.class.getName() + ".REQUEST_EXCLUDED_FROM_ACTION_MAPPING") != null;
}
#Override
public void destroy() {
exe.shutdown();
super.destroy();
}
class ContextExecution implements Runnable {
final AsyncContext context;
ActionMapping mapping;
public ContextExecution(AsyncContext context, ActionMapping mapping) {
this.context = context;
this.mapping=mapping;
}
public void run() {
try {
execute.executeAction((HttpServletRequest) context.getRequest(),
(HttpServletResponse) context.getResponse(), mapping);
context.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
then
<filter>
<filter-name>struts2asyncexecute</filter-name>
<filter-class>me.zamani.yasser.ww_convention.utils.MYStrutsAsyncExecuteFilter</filter-class>
<async-supported>true</async-supported>
</filter>
then put your desired async actions in a specific package and exclude them from Strut's original filter but map them to above filter in your web.xml.
I'm working to improve this to be more configurable and clear then import to Struts.
Could you please test in your app? and please feel free to let me know any idea.
i trying to open a pdf right after i created.
I want to see the result in my browser, but i dosen't.
By the way, the programm runs on a server.
If i try to open the pdf there, no problem - all works fine.
Just the client can't see the pdf if he clicks, for example, on a button.
Here's my code:
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final int id = Integer.parseInt(request.getParameter("id"));
makePdf(request, response, "POST",id);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void makePdf(HttpServletRequest request,
HttpServletResponse response, String methodGetPost, int id)
throws ServletException, IOException {
response.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Test"));
document.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
I using the iText library.
EDIT:
Now i have change my servlet code, but still not working for me.
I can't see the pdf in my browser. Firefox and IE both are show nothing.
package de.WorldCheckCustomer.model;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
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 com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
makePdf(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
makePdf(request, response);
}
public void makePdf(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set content type to application / pdf
// browser will open the document only if this is set
response.setContentType("application/pdf");
// Get the output stream for writing PDF object
OutputStream out = response.getOutputStream();
try {
Document document = new Document();
/* Basic PDF Creation inside servlet */
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
document.add(new Paragraph(
"PDF Created Using Servlet, iText Example Works"));
document.close();
} catch (DocumentException exc) {
throw new IOException(exc.getMessage());
} finally {
out.close();
}
}
private static final long serialVersionUID = 6067021675155015602L;
}
I wrote a java class to run a simple XQuery on a XML database (Using Saxon xqj). The query works well in this class. But I want to access this class from a servlet. The problem is that the servlet doesn't find the java class, It gets java.lang.ClassNotFoundException: javax.xml.xquery.XQException when I run the servlet. Any Ideas please?
The Java class is as simple as This:
import java.util.Properties;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import javax.xml.xquery.XQSequence;
import javax.xml.namespace.QName;
import net.sf.saxon.xqj.SaxonXQDataSource;
import org.xml.sax.SAXException;
public class XMLClass {
public static String xmldata() throws XQException{
XQConnection con;
String output = null;
final String sep = System.getProperty("line.separator");
String fileName= "cd_book.xml";
con = new SaxonXQDataSource().getConnection();
System.out.println("Connected");
String queryString = "declare variable $docName as xs:string external;"+sep +
"for $x in doc($docName)/*" +
" return $x";
XQPreparedExpression expr = con.prepareExpression(queryString);
expr.bindObject(new QName("docName"), fileName, null);
XQResultSequence rs = expr.executeQuery();
String result =rs.getSequenceAsString(new Properties());
return result;
}
}
And the Servlet is:
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.xml.xquery.XQException;
public class ServletXML extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletXML() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
XMLClass.xmldata();
} catch (XQException e) {
e.printStackTrace()
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Then xml your class may be missing from your classpath. How are you compiling and running this?
Also it is good practice to place both into one or more packages and import your class from your servlet if it is in a different package.
I have develop servlet for generate Captcha code & add session name code
Generate Capta-code
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
Random rnd;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rnd=new Random();
rep.setContentType("image/jpeg");
String random_String=getRandomNumbers();
HttpSession ses=req.getSession();
ses.setAttribute("code",random_String);
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
private String getRandomNumbers()
{
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Use Generate capta-image in other servlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
HttpSession ses=req.getSession();
String original=(String)ses.getAttribute("code");
if(original!=null)
{
out.println("<h1>Original Value "+original+"</h1>");
}
ses.invalidate();
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Both servlet work fine but I am not getting the session value which is generate in Capta-code servelt(added in servlet)
I am getting session value which is generate in previous capta-image.
See output :
Output - 1
Output - 2
Output - 3
Thank you ..
Put the random number generation logic in capta_test servlet and put that number in session. Because you are rendering HTML, the capta servlet will be called after the page load like this and do not invalidate the session.
Random number generator
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String original=getRandomNumbers();
HttpSession ses=req.getSession(false);
ses.setAttribute("code",random_String);
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
out.println("<h1>Original Value "+original+"</h1>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
private String getRandomNumbers()
{
Random rnd=new Random();
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
}
Image generator servlet
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
HttpSession ses=req.getSession(false);
String random_String=(String)ses.getAttribute("code");
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rep.setContentType("image/jpeg");
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Your program flow is wrong , the session value is null because the capta_test servlet is called even before the capta servlet.
Have a look at this simple tutorial. Hope this helps you move in the right path
Captcha in JSP and Servlet