Submit more forms with one button in jsp - java

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

Related

getParameter returns null from Method get

I'm tryring to get an id from url but getParameter return null
this is how I'm sending the id in the url (tool.jsp):
Execute
this the doGet method where I want the id value
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
ToolDAO dao=new ToolDAO();
String id= req.getParameter("id");
Tool t=dao.getToolById(Integer.parseInt(id));
String first = req.getParameter("first");
byte[] bytes = first.getBytes(StandardCharsets.ISO_8859_1);
first= new String(bytes, StandardCharsets.UTF_8);
if(first!=null)
{
String [] input=first.split(" ");
System.out.println("input"+input[0]);
EXEJAVA exe=new EXEJAVA();
FileRead f=new FileRead();
f.writeinputfile(input);
ArrayList l=exe.executetool(t.getTool_path_exe());
req.setAttribute("l",l);
req.setAttribute("first", first);
req.getRequestDispatcher("executetool.jsp").forward(req, res);
}
and this is the form (executetool.jsp)
<form accept-charset="UTF-8" name="form" action="executetool" method="get">
<div class="centre">
<div class="row">
<div class="inline-div">
<label for="ta1">Text in Latin script</label>
<textarea cols="60" rows="15" id="first" name="first" class="inline-
txtarea">${first}</textarea>
</div>
<div class="inline-div">
<input type="button" value="Clear" onclick="javascript:eraseText();">
</div>
<div class="inline-div">
<label for="ta2" >Text in Arabic script</label>
<textarea cols="60" rows="15" id="second" name="second" class="inline-
txtarea"><c:forEach items="${l}" var="s">${s} </c:forEach>
</textarea>
</div>
</div>
</div>
</form>
Since it's method get the url keeps changing everytime the page is refreshed and so the "id=something" part gets replaced by the value of the two text areas that I have in the form what sould I do to always keep that part in the url?
Place a hidden field instead
<input type='hidden' name='id' value='${l.tool_id}'>
Then use input type submit for the button, not a generic <a> tag as that won't submit the form unless you have a javascript code somewhere that will submit the form for you.
You can also place the id in the action attribute of the form.
<form accept-charset="UTF-8" name="form" action="executetool?id=${l.tool_id}" method="get">

getParameters keeps returning null

So, I'm having trouble retrieving information from my the client-side jsp. The javascript executes, and the alert prints, however query becomes null in the java servlet, and null is then written to the logger. I can't seem to figure out why the query is now null.
HTML:
<div id="query">
<div id="querybar">
<form onsubmit="query();return false;" method="get">
<input type="text" id="querytext" placeholder="Run a query" name="querytext">
</form>
<div id="queryimg-container">
<img src="styles/magnifyingglass.png" id="queryimg" alt="" />
</div>
</div>
</div>
JS:
function query() {
$.get('QueryHelper', function(data) {
alert("Somesortofalert");
});
}
Java Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("querytext");
response.setContentType("text/plain");
#SuppressWarnings("resource")
PrintWriter writer = response.getWriter();
sLogger.info(query);
}
Can anyone see anything wrong? I'm super stumped here.
It'll be null because no parameter by that name is being sent with the Ajax request.
Despite being started by an onsubmit event, $.get() doesn't have any automatic knowledge of the <form>. It's up to you to gather or specify any parameters to be included with the request using the data parameter.
$.get('QueryHelper', { querytext: 'foo bar' }, function (res) {
// ...
});
Provided you have a reference to the <form> or its inputs, you can use .serialize() to prepare the fields' names and values as data.
<form onsubmit="query(this); return false;" method="get">
<!-- ^^^^ -->
function query(form) {
// ^^^^
$.get('QueryHelper', $(form).serialize(), function (res) {
// ^^^^^^^^^^^^^^^^^^^
// ...
});
}

Retrieve src data from jsp through form submit

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");

How to identify form action URI from processAction() method in Portlet class?

I created a form like;
<portlet:actionURL var="myFriendlyURI">
<portlet:param name="action" value="addUser"></portlet:param>
</portlet:actionURL>
<form id="userForm" name="userForm" action="${myFriendlyURI}" method="post">
Name :- <input type="text" name="userName">
<input type="submit">
</form>
In processAction(ActionRequest request, ActionResponse response) method, how can I identify the request URI based on myFriendlyURI?
request.getAttribute("javax.servlet.forward.request_uri").toString()) is giving only "/web/portal/Adduser-PageName".
I just want to check the request just like we are doing in Servlet class ;
if(request.getRequestURI().endsWith("user/add")) { // <form action="user/add" ..... >
System.out.println("Ends with : user/add ");
// do actions here
}
Use this
HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(actionRequest);
HttpServletRequest originalReq = PortalUtil.getOriginalServletRequest(actionRequest);
PortalUtil.getCurrentCompleteURL();
Reference to the link has many examples

Unable to read form field in servlet [duplicate]

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.

Categories

Resources