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);
}
}
Related
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");
I am creating an online bank. On login, it created a session for that user. The user than has options to click on different transaction types.So when the user clicks on open an account button, it will go to openAccount.jsp page. I also have a form with a users first name, last name, and email in the openAccount.jsp. When the user clicks on the open account button and is redirected to the openAccount.jsp, I want the form to be prefilled from the database based. I am not sure how? Here is my code so far:
home-page.jsp
<div class="col-md-4">
<form name = "OpenAccount" action="open-account.jsp" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
open-account.jsp
<!DOCTYPE html>
<html>
<head>
<title>Open Account</title>
</head>
<body>
<h3>Please fill in the details</h3>
<form name="predifinedFields">
First Name: <input type="text" name="firstname" value= <%= request.getAttribute("firstname") %> > <br/><br/>
Last Name: <input type="text" name="lastname" value= <%= request.getAttribute("lastname") %>> <br/><br/>
Email: <input type="text" name="email" value= <%= request.getAttribute("email") %>> <br/><br/>
</form>
<form name="openAccount" action="OpenAccount" method="POST">
Select the type of account:
<select name="accounttype">
<option>Checking</option>
<option>Saving</option>
</select> <br/><br/>
Initial Deposit: $<input type="text" name="deposit"> <br/><br/>
Please check the box if everything above is complete:
Agree <input type="radio" name="agree" value="Agree">
Disagree <input type="radio" name="agree" value="Disagree">
<br/><br/>
<input type="submit" value="submit" name="Submit">
</form>
</body>
</html>
OpenAccount.java
public class OpenAccount extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = "";
HttpSession session = request.getSession(false);
if(session != null)
{
username = (String) session.getAttribute("username");
Users users = new Users();
users = DBConnection.getUsers(username);
request.setAttribute("firstname", users.getFirstName());
request.setAttribute("lastname", users.getLastName());
request.setAttribute("email", users.getEmail());
//request.setAttribute("username", users.getUsername());
}
// String firstName = (String) request.getParameter("firstname");
// String lastname = (String) request.getParameter("lastname");
String email = (String) request.getParameter("email");
String accountType = (String) request.getParameter("accounttype");
String accept = (String) request.getParameter("agree");
String deposit = (String) request.getParameter("deposit");
if(accept.equals("Agree"))
{
if(accountType.equals("Checking"))
{
DBConnection.newCheckingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
else if(accountType.equals("Saving"))
{
DBConnection.newSavingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
}
else
{
System.out.println("Please modify the changes");
RequestDispatcher dispatcher = request.getRequestDispatcher("open-account.jsp");
dispatcher.forward(request, response);
}
}
}
Database.java
public static Users getUsers(String username)
{
Users user = new Users();
try
{
DBConnection.connectToDB();
String query = "SELECT * FROM userlogin where username=?";
stmt = DBConnection.conn.prepareStatement(query);
stmt.setString(1,username);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception e)
{
System.out.println(e);
}
return user;
}
In your case (basic servlet), you should follow this logic :
->browser
->servlet which loads and prepares required data from database into request attributes as you have done and finally forwards to open-account.jsp
->open-account.jsp use request attributes to render dynamically fields with your data retrieved from your database.
For other use cases, try to keep this simple logic :
->browser
->servlet processing ....
->jsp rendering ....
Your form in home-page.jsp should post to the servlet (controller) :
<div class="col-md-4">
<form name = "OpenAccount" action="/OpenAccount" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
You should rename OpenAccount to OpenAccountServlet (keeping conventions is better) and configure correctly the servlet of OpenAccountServlet in your web.xml (or with annotations).
If you use web.xml file for the servlet configuration, the url posted in the previous jsp (action="/OpenAccount") should match with the value in <url-pattern>/OpenAccount</url-pattern>
The forward should do like that :
getServletContext().getRequestDispatcher("yourRequiredPath/open-account.jsp ").forward(request, response);
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.
I want to pass two values to a servlet from a jsp page. 1- a result set value, 2- a get parameter value.
It should look something like this in jsp page:
SCcalculator.getValue(rs.getString("value1"),request.getParameter("value1"));
on the servlet side how can i receive and manipulate this data in the SCcalculator package? any suggestions please?
In your servlet class use :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String s = request.getParameter("value1");
String s1 = request.getParameter("value");
}
in JSP don't do like that, instead do :
<form action="name" method="post"> //here action=name is name of your servlet class name
<input type="text" name="value">
<input type="text" name="value1">
<input type="submit" value="Send">
</form>
Conside this example
<html>
<head>
<title>Demo application</title></head>
<body>
<form id = "form1" method = "GET" action = "../Sample Application">
link1 : <input type = "text" id = "nRequests" name = "nRequests" />
<input type = "submit" name = "submit" id = "submit"/>
</form></body></html>
Now how you servlet will accept the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
nRequests = request.getParameter("nRequests");
In this way you can get the value from a HTML page to your servlets.
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
Hey I am quite new to servlet environment. Here I am trying to post a form to my servlet with something like this:
<form action="OnlineExam?q=saveQuestion" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Question</legend>
<textarea class="questionArea" id="question" name="question">Enter Question.</textarea>
<br class="clearFormatting"/>
Attach File<input type="file" name="file" />
<input class="optionsInput" value="Option A" name="A" onfocus = "clearValues('A')" onblur = "setValues('A')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option B" name="B" onfocus = "clearValues('B')" onblur = "setValues('B')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option C" name="C" onfocus = "clearValues('C')" onblur = "setValues('C')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option D" name="D" onfocus = "clearValues('D')" onblur = "setValues('D')"/>
<br/>
<input type="submit" value="Save" />
<input type="reset" value="Cancel" />
<button style="display: none" onclick="return deleteQuestion()" >Delete</button>
</fieldset>
</form>
And the servlet is something like this:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
saveQuestion(request);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void saveQuestion(HttpServletRequest request){
Enumeration enum = request.getParameterNames();
while (enum.hasMoreElements()) {
String pName = (String) enum.nextElement();
String[] pValues = request.getParameterValues(pName);
System.out.print("<b>"+pName + "</b>: ");
for (int i=0;i<pValues.length;i++) {
System.out.print(pValues[i]);
}
out.print("<br>");
}
}
But it is printing only the q parameter not the other form fields.
I also tried to get them with the request.getParameter("question") but this was also not working. So where i am going wrong. actually i am from PHP background and recently started coding in java so please help.
Thanks in advance
When you use enctype="multipart/form-data" you can not access request parameter as you normally do[that is request.getParameter("question")]. You have to use MultipartRequest object.
And also you submit form in POST and then in servlet you redirect it to doGet. Why so? Why don't directly use GET as a method in form submit.
Demo to use MultipartRequest:
String ph="images\\";
MultipartRequest req=new MultipartRequest(request, ph);
String question=req.getParameter("question");
System.out.println("Question: "+question);
why is your form action looking like a GET request with the ?q=saveQuestion, while the form type is POST? maybe the GET parameter is ignored on this call.