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
Related
Currently, i have function, which is to convert the data from MYSQL to CSV. The CSV function contain the webconfig where use the viewResolver. The problem is, when i used below function, the page cannot view but the CSV file can be download and vice versa. Is there anything that i need to configure ?
-Configure ContentNegotiatingViewResolver
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
WebConfig- full code
package com.portal.dmtt.csvDownload.config;
import com.portal.dmtt.csvDownload.viewResolver.CsvViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import java.util.ArrayList;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
}
Export Controller
package com.portal.dmtt.csvDownload.controller;
import com.portal.dmtt.repo.dmttDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExportController {
#Autowired
private dmttDAO dmttDAO;
/**
* Handle request to download an Excel document
*/
#GetMapping("/dl")
public String download(Model model) {
model.addAttribute("results", dmttDAO.getAllResultSet());
return "";
}
}
Abstract View
package com.portal.dmtt.csvDownload.view;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public abstract class AbstractCsvView extends AbstractView {
private static final String CONTENT_TYPE = "text/csv";
public AbstractCsvView() {
setContentType(CONTENT_TYPE);
}
#Override
protected boolean generatesDownloadContent() {
return true;
}
#Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
buildCsvDocument(model, request, response);
}
protected abstract void buildCsvDocument(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
CSV View
package com.portal.dmtt.csvDownload.view;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class CsvView extends AbstractCsvView {
#Override
protected void buildCsvDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse
response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"my-csv-file.csv\"");
List<FN_Result_Set> fnResultSetList = (List<FN_Result_Set>) model.get("results");
String[] header = {"SP_ID", "SP_ID", "XFER_XMIT_STATUS", "XFER_FILE_NAME", "UPDATE_TS", "YYMM", "REMARKS"};
try {
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
csvWriter.writeHeader(header);
for (FN_Result_Set user : fnResultSetList) {
csvWriter.write(user, header);
}
csvWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
View Resolver
package com.portal.dmtt.csvDownload.viewResolver;
import com.portal.dmtt.csvDownload.view.CsvView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
public class CsvViewResolver implements ViewResolver {
#Override
public View resolveViewName(String s, Locale locale) throws Exception {
return new CsvView();
}
}
One of the problems is that your CSVViewResolver is resolving a view for any view name. You may want to return null from CSVViewResolver.resolveViewName() if s, the view name, is not empty .
Another issue is that the browser (at least my Chrome) doesn't send text/csv as Accept header, but text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Set the media type explicitly in configureContentNegotiation for CSV:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true)
.mediaType("csv", MediaType.parseMediaType("text/csv"));
}
Remove the Bean contentNegotiatingViewResolver
You shouldn't create a contentNegotiatingViewResolver as one is provided by Spring Boot. If you provide one, you will have two of this type, and yours will not have the Thymeleaf ViewResolver. As your CSVViewResolver will return a view for any view name, the view will be resolved in the ContentNegotiatingViewResolver provided by you, not in the one provided by Spring.
Details:
The csvViewResolver bean will be picked up by the Spring Boot's ContentNegotiatingViewResolver along others like BeanNameViewResolver, ThymeleafViewResolver, ViewResolverComposite, InternalResourceViewResolver.
To debug this set a breakpoint on DispatcherServlet.resolveViewName:
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}
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;
}
this wierd problem is very interrupting me for a long time. I have a class name Connector inside dynamic web application in eclipse, with these code:
public class Connector {
private static final String dbURL = "jdbc:mysql://localhost:3306/";
private Connection con;
public Connector(String userName, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(dbURL, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
System.err.print("Unidentified exception has acurred!");
e.printStackTrace();
}
}
when I'm using it from different Class in the same package, named portal, it works fine, but when I'm trying to use it from servlet in package servlets, named LoginHandle.java, I get ClassNotFoundException.
The Class is in the build path of all classes, and I checked it by trying to import it from the servlet, but when I create new instance, it is not being recognized. I tried to move the servlet to the package of the connector, and vise versa, and it didn't affect. Here is the servlet's code:
package servlets;
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;
import javax.servlet.http.HttpSession;
import portal.Connector;
import portal.UserTableAnalyzer;
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginHandle() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String referer = request.getHeader("Referer");
String pageName = referer.substring(referer.lastIndexOf('/') + 1);
if(pageName.equals("Login.jsp"))
{
HttpSession session = request.getSession(false);
Connector c = new Connector("root", "16180339887");
c.executeUpdate("USE Main");
String id = request.getParameter("id"), password = request.getParameter("password");
String query = "SELECT FROM Users WHERE id ='" + id + "' AND password = '" + password + "'";
String[][] result = c.executeQuery(query);
UserTableAnalyzer uta = new UserTableAnalyzer(result);
if(result.length > 0)
{
session.setAttribute("userID", uta.getID(0));
session.setAttribute("role", uta.getRole(0));
response.sendRedirect("Main.jsp");
}
else
{
request.setAttribute("wrongDetails", new Boolean(true));
response.sendRedirect("Login.jsp");
}
}
else
response.getWriter().print(pageName);
}
}
sorry if my english is bad, or if details are missing
Your driver is not in the server classpath, build path has nothing to do with that.
You didn't write which application server are you using. You also should use DataSource in servlets, rather than DriverManager. Here is sample configuration for Tomcat.
UPDATE
For Tomcat 7 you need to do the following:
Put mysql jar in the $CATALINA_HOME/lib
Configure Datasource in context
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/databaseName"/>
Use Datasource in servlet (pseudo code)
#WebServlet("/LoginHandle")
public class LoginHandle extends HttpServlet {
private static final long serialVersionUID = 1L;
#Resource(lookup="jdbc/testDB")
private DataSource ds;
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection c = ds.getConnection();
...
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.