Java servlet doPost method not working - java

Edit:
I pointed the post request to /vault/Login but the servlet was on /vault/index and vault/login
when pointing it towards index it worked.
I'm trying to make a login system.
I have an html file which a post method is requested from but the doPost method is never fired when requested.
When the submit button is clicked the url changes with the parameters in it but nothing happens.
Every time the doPost() is executed the first statement writes something to the console but neither does that happen.
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("fired");
HttpSession session = request.getSession();
session.setAttribute("loginFailed", false);
RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is another test");
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
String password = (String)session.getAttribute("password");
System.out.println(username + " " + password);
boolean succes = false;
if (!"".equals(username) && !"".equals(password)){
try {
succes = Authentication.checkCredentials(username, password);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
switch ((String)session.getAttribute("platform")){
case "browser":
RequestDispatcher rd = request.getRequestDispatcher("Lobby.jsp");
rd.forward(request, response);
break;
case "desktop":
int id = Tracker.getIdByUsername(username);
List vaults = (List)VaultManagement.getVaultsByUserId(id);
int[] vaultIds = new int[vaults.size()];
if (vaults.isEmpty()){
vaultIds[0] = -1;
}else{
int x = 0;
for (Object vault : vaults){
Vault v = (Vault)vault;
vaultIds[x] = v.getId();
x++;
}
}
DAL.Entities.Account account = AccountManagement.getAccountByUsername(username);
LoginPackage pack = new LoginPackage(username, password, account.getEmail(), vaultIds);
String json = JSON.dataPackageToJson(pack);
PrintWriter writer = response.getWriter();
writer.print(json);
break;
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Post
<div class="jumbotron" width="10%">
<form id="form" action="/vault/Login.jsp">
<h6>Username:</h6>
<input type="text" class="form-control" id="username" name="username">
<h6>Password:</h6>
<input type="password" class="form-control" id="password" name="password"><br>
<button type="button" onclick="location.href='vault/Register.jsp'" class="btn btn-secondary">Register</button>
<input type="hidden" name="platform" value="browser"/>
<input type="submit" value="Login"/>
</form>
</div>

You forgot to specify the method attribute to be post:
<form id="form" action="/vault/Login.jsp" method="post">
<!-- Here ---------------------------------^ -->

Related

request.getParameter is returning null ,I have surfed a lot for this but i didn't got the proper solution

So basically, when I try submitting my jsp, the control wents to the servlet , but the values of all the control in jsp becomes null
"ViewBook.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#include file="Header_1.jsp" %>
<form action="<%=request.getContextPath()%>/BookServlet" method="post"
enctype="multipart/form-data">
<table>
<th colspan="2"></th>
<tr>
<td>
ID:
</td>
<td>
<input type="number" name="id">
</td>
</tr>
<tr>
<td>
Title:
</td>
<td>
<input type="text" name="title">
</td>
</tr>
<tr>
<td>
Author
</td>
<td>
<input type="text" name="author">
</td>
</tr>
<tr>
<td>
Price:
</td>
<td>
<input type="number" name="price">
</td>
</tr>
<tr>
<td>
Book image:
</td>
<td>
<input type="file" name="book_img">
</td>
</tr>
<tr>
<td>
Publish date:
</td>
<td>
<input type="date" name="pub_date">
</td>
</tr>
<tr>
<td>
<input type="submit" value="add" formaction="
<%=request.getContextPath()%>/BookServlet?action=add">
<input type="submit" value="delete"
formaction="G:\sem5\AJT\Q-4\src\java\BookServle?action=delete">
<input type="submit" value="update" formaction="
<%=request.getContextPath()%>/BookServlet?action=update">
<input type="submit" value="view" formaction="
<%=request.getContextPath()%>/BookServlet?action=view">
</td>
</tr>
</table>
</form>
<%#include file="Footer.jsp" %>
"BookServlet.java"
#WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
}
}
// processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String title=request.getParameter("title");
String author=request.getParameter("author");
String price=request.getParameter("price");
System.out.println("price=="+price);
String book_img=request.getParameter("book_img");
System.out.println("book:imagre===="+book_img);
String pub_date=request.getParameter("pub_date");
String action=request.getParameter("action");
SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
Date d = null;
try {
d = (Date) sdf.parse(pub_date);
} catch (Exception ex) {
System.out.println("Exception ex="+ex);
}
Part filepart=request.getPart("book_img");
System.out.println("part====="+filepart);
InputStream is=filepart.getInputStream();
BookBean bb=new BookBean();
// ResultSet rs=bb.ViewAllBooks();
if(action.equals("add"))
{
Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
bb.add(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
// processRequest(request, response);
}else if(action.equals("update"))
{ Book b=new
Book(0,title,author,Integer.parseInt(price),d,is);
// boolean flag= bb.update(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
}else if(action.equals("delete")){}
else if(action.equals("view")){}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is what I got in my catch block
-Exception ex=java.lang.NullPointerException
StackTrace:
java.lang.NullPointerException
at BookCrud.BookServlet.doPost(BookServlet.java:136)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke
(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke
(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke
(StandardHostValve.java:139)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke
(AbstractAccessLogValve.java:668)
at
org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service
(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process
(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process
(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun
(NioEndpoint.java:1388)
at
org.apache.tomcat.util.net.SocketProcessorBase.run
(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
any help from your side
also, I have surfed a lot for this on StackOverflow and other websites but
I didn't get any proper solution for this.......
For all those who are facing the same error ::You can use jar files as mentioned by #secret super star ,But if you dont want to do so here is a tip :
Just
import javax.servlet.annotation.MultipartConfig;
in your servlet and add
#MultipartConfig(maxFileSize = 16177215) //Length of the file
annotation ,That's it
Note: In my case following will be my servlet
#WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
#MultipartConfig(maxFileSize = 16177215)
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
}
}
// processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String title=request.getParameter("title");
String author=request.getParameter("author");
String price=request.getParameter("price");
System.out.println("price=="+price);
String book_img=request.getParameter("book_img");
System.out.println("book:imagre===="+book_img);
String pub_date=request.getParameter("pub_date");
String action=request.getParameter("action");
SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
Date d = null;
try {
d = (Date) sdf.parse(pub_date);
} catch (Exception ex) {
System.out.println("Exception ex="+ex);
}
Part filepart=request.getPart("book_img");
System.out.println("part====="+filepart);
InputStream is=filepart.getInputStream();
BookBean bb=new BookBean();
// ResultSet rs=bb.ViewAllBooks();
if(action.equals("add"))
{
Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
bb.add(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
// processRequest(request, response);
}else if(action.equals("update"))
{ Book b=new
Book(0,title,author,Integer.parseInt(price),d,is);
// boolean flag= bb.update(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
}else if(action.equals("delete")){}
else if(action.equals("view")){}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
you can not directly get parameters by using request.getParameter(name);. While using it, form fields aren't available as parameter of the request, they are included in the stream, so you can not get it the normal way.
Refer this: http://commons.apache.org/proper/commons-fileupload//using.html, under the section Processing the uploaded items.

Next button will generate a new set of questions

I am trying to create an online quiz system using jsp and servlets.
When the user chooses the topic, it goes to the first question. After the user chooses their choice, and clicks on the next button, it is supposed to show a new set of questions and choices. I am not sure how to do that part. Here is my code so far:
Database:
public static MathQuestion getQuestionInfo(int questionNum)
{
MathQuestion math = new MathQuestion();
// int questionNum = 1;
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM MathQuestions where QuestionNumber = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setInt(1, questionNum);
// questionNum++;
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
math.setQuestionNum(rs.getInt("QuestionNumber"));
math.setQuestion(rs.getString("Question"));
String questionOptions = rs.getString("QuestionOptions");
String[] splittedValues = null;
for(int i = 0; i < 4; i++)
{
splittedValues = questionOptions.split(",");
}
math.setQuestionOptions(splittedValues);
math.setCorrectAnswer("CorrectAnswer");
}
}
catch (Exception e)
{
System.out.println(e);
}
return math;
}
JSP
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Math</title>
</head>
<body>
<h1>Math Section</h1>
<%
String email = (String) session.getAttribute("email");
int questionNum = (Integer) request.getAttribute("questionNum");
MathQuestion math = new MathQuestion();
if(email != null)
{
math = MathService.getQuestionInfo(questionNum);
}
String[] questionOptions = math.getQuestionOptions();
%>
<form name="MathForm" action="Math" method="post">
Question <input type="text" value="<%=math.getQuestionNum()%>"> <br/>
<input type="text" value="<%=math.getQuestion()%>"> <br/>
<input type="radio" name="options" value="OptionA"><%=questionOptions[0]%> <br/>
<input type="radio" name="options" value="OptionB"><%=questionOptions[1]%> <br/>
<input type="radio" name="options" value="OptionC"><%=questionOptions[2]%> <br/>
<input type="radio" name="options" value="OptionD"><%=questionOptions[3]%> <br/>
<input type="button" name="Next" value="Next">
</form>
</body>
</html>
Servlet:
#WebServlet(name = "Math", urlPatterns =
{
"/Math"
})
public class Math extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (SessionService.validateSession(request, response))
{
RequestDispatcher dispatcher = request.getRequestDispatcher("math-page.jsp");
request.setAttribute("questionNum", 1);
dispatcher.forward(request, response);
}
else
{
RequestDispatcher dispatcher = request.getRequestDispatcher("login-page.jsp");
dispatcher.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
for(int i = 2; i <= 10; i++)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("math-page.jsp");
request.setAttribute("questionNum", i);
dispatcher.forward(request, response);
}
String userChoice = request.getParameter("options");
}
}

Invoking a JSP Page from a Servlet

Can anyone tell me if there exists any method other than RequestDispatcher, to invoke a jsp page from my servlet? Because i have tried a lot without success.
My servlet works normally and recovred all the data from jsp. All that I need is to be redirected to another page when the user enters the username and password correctly.
my code :
first my servlet " login"
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String user = request.getParameter("username");
String pass = request.getParameter("password");
System.out.println(" le user est "+user+ " le mot de passe est " + pass);
String query = "SELECT * FROM users WHERE username = '"+user+"' and password='"+pass+"'";
dbconn = new DBAccess();
Connection conn = dbconn.connect();
stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(query);
if(res.next()){
ServletContext sc = this.getServletContext();
RequestDispatcher rd =sc.getRequestDispatcher( "inscreption.jsp");
rd.forward(request, response);
System.out.println(" il existe");
}else {
ServletContext sc = this.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("index.jsp");
// RequestDispatcher rd =request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
System.out.println("not found");
}
} catch (SQLException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
System.out.close();
}
}}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
/* #Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
my jsp that i would to be redirected for
<html>
<head>
<!--local jquery-->
<script src="jQuerys/jquery-1.9.1.min.js"></script>
<script src="jQuerys/jquery.mobile-1.3.1.min.js"></script>
<link rel ="stylesheet" type="text/css" href="css/jqueryMobile-1.3.1.css"/>
<!--/local jquery-->
</head>
<body>
<div data-role="page" id="inscription">
<div data-role="header" data-theme="b">
<center>CERIST</center>
</div>
<form id="insc" method="post" action="login">
<div data-role="content">
<div data-role="fieldcontain">
<label for="identifiant">Identifiant </label>
<input type="text" id="identifiant"/>
</div>
<div data-role="fieldcontain">
<label for="password1">Mot de passe </label>
<input type="password" id="password1"/>
</div>
<div data-role="fieldcontain">
<label for="password2">Confirmation</label>
<input type="password" id="password2"/>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Vous ĂȘtes :</legend>
<input type="radio" name="profil" id="radio-choice-1" value="Candidat" />
<label for="radio-choice-1">Utilisateur</label>
<input type="radio" name="profil" id="radio-choice-2" value="Entreprise" />
<label for="radio-choice-2">Administrateur</label>
</fieldset>
</div>
<br/>
S'inscrire
</form>
</div>
</div>
</body>
</html>
index.jsp :
<form action="Myservlet" method="post"><br>
User name`<`input type="text" name="username"`>`<br>
Password `<`input type="password" name="password"><br>
`<`input type="submit" value="Submit" `>`
</form>
Myservlet.java:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("Oppos!!!");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
RequestDispatcher rd;
if (user.equals("username") && pass.equals("password")) {
rd = request.getRequestDispatcher("/inscreption.jsp");
rd.forward(request, response);
} else {
rd = request.getRequestDispatcher("/wrong.jsp");
rd.forward(request, response);
}
}
You can create more than two pages where you want to dispatch your request so here I created more than two jsp page names: right.jsp and wrong.jsp. If the username and password is correct then it frowards to right.jsp page if it's wrong, it frowards the request to wrong.jsp page.

httpservlet parameter are null [duplicate]

This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}

Passing value to servlet from image

From JSP I have
..
<form action="TestMartController" method="post">
<input type="hidden" value="math">
<input type="image" src="<%=request.getContextPath()%>/css/categories/math.jpg">
</form>
..
In my servlet I have
...
private static final String MATH = "WEB-INF/jsp/math.jsp";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = null;
String action=request.getParameter("action");
if(action.equals("math")){
forward = MATH;
flag = 1;
}
RequestDispatcher rd = request.getRequestDispatcher(forward);
rd.forward(request, response);
}
...
When I clicked the image I got null pointer exception. I want to know why it does not pass the value where it should. Since hidden will always get the values to pass.
your input type="hidden" field is missing a name="action" attribute. Thus, the action parameter is null.

Categories

Resources