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.
Related
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);
}
}
I try to submit two forms with one button, but value of first form(input) is null.
test.jsp
<body>
<script>
function submitAllForms(){
console.log($('input[name=valueDateFromFilter]').val());
console.log($('input[name=valueDateToFilter]').val());
document.formDateFromFilter.submit();
document.formDateToFilter.submit();
};
</script>
<form method="post" action="./Servlet" name="formDateFromFilter">
<input class="span2" size="16" type="text" name="valueDateFromFilter">
</form>
<form method="post" action="./Servlet" name="formDateToFilter">
<input class="span2" size="16" type="text" name="valueDateToFilter">
</form>
<a class="btn" href="#" onclick="submitAllForms();"><i class="icon-message"></i></a>
</body>
doPost method in Servlet.jsp
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String a = request.getParameter("valueDateFromFilter");
String b = request.getParameter("valueDateToFilter");
System.out.println(a);
System.out.println(b);
}
In browser console i see values of both strings, but in the server log console value of first string (variable a) is null
This is poor design and probably won't work. The better way to do it would be to build a JSP/servlet that receives both sets of data and calls the other servlets with the appropriate fields programatically on the server side
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.
In my jsp:
<form name="frmTest" action="test" method="post">
<input type="submit" value="sub" name="sub" />
<img id="cImg" name="cImg" src="${param.src}">
</form>
In my servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
String imgUrl = req.getParameter("cImg");
I want to retrieve the src data of my image in canvas. It will be in base 64 data URI format. The above will give me null value. How should I go about doing it, any helps will be appreciated.
No you cannot, You can get data with only name attribute.
What you can do is take a hidden variable ,add value to it and get in servlet.
Like
<form name="frmTest" action="test" method="post">
<input type="submit" value="sub" name="sub" />
<img id="cImg" name="cImg" src="${param.src}">
<input type="hidden" name="hiddenSrc" value="${param.src}" />
</form>
in servlet
String hiddenimgUrl = req.getParameter("hiddenSrc");
i want to know which is the best servlet pattern to follow for creating a controller servlet.
So far i am writing a controllerservlet like this for handling the requests
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String action = req.getParameter("action");
if (action.equals("LOGIN")){
}else if(action.equals("Deposit")) {
}
else if(action.equals("Withdraw")) {
} else if(action.equals("view")) {
}
}
is it ok to proceed like this or does anyone have a better approach for this?
this is my sample html:
<form action="Controller" method="post">
<center><br><br>
<h2><u><i><b>LOGIN SCREEN</b></i></u></h2><br><br><br>
<h4>Enter User Name :<input type=text name="userid" size=6 style="height:20;color=red"><br><br>
User Password     :<input type=password name ="pwd" size=20><br><br>
<h3>ARE YOU A NEW USER? THEN REGISTER NOW.</H3>
<input type="hidden" name="action" value="LOGIN">
<input type ="submit" name="login" value="login" >
<input type="button" value="register" onclick="reg()">
</center>
</form>
Maybe REST (like RESTeasy) is of your interest if you can adjust the form's action:
public class Controller {
#POST
#Path("/login")
public String doLogin() {...}
#POST
#Path("/view")
public String showView() {...}
...
If you don't want to use one of the many already available frameworks to do that for you, you can start off with the command pattern, combining it with the factory and null value object pattern. Thats just for starters.