getParameter returns null from Method get - java

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

Related

How to submit form without reload page

I have form action with textarea and submit button
<form method="post" action="/analyze">
<div class="form-group">
<label for="text">Input text:</label>
<textarea class="w-100" name="text" id="text" cols="30" rows="10"></textarea>
</div>
<div class="form-group d-flex justify-content-center">
<input type="submit" class="btn__submit btn btn-dark my-auto" value="Обработать">
</div>
</form>
<div class="row">
<div class="col">
<p th:text="#{nertext}"></p>
</div>
</div>
When I click submit button, i want to get processed text from server in Spring Boot and paste in tag p in div col.
Java Controller
#RequestMapping(value = "/analyze", method = RequestMethod.POST)
public String analyzeText(#RequestParam String text, Model model) {
System.out.print(classifier.classifyToString(text, "tsv", false));
String asd = classifier.classifyToString(text, "tsv", false);
model.addAttribute("nertext", asd);
return "/analyze";
}
How can i do submit without reload page
Use the Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and the onsubmit event listener (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit) to submit the form with JavaScript without reloading the page:
let form = document.getElementById("the-form");
form.onsubmit = function (e) {
e.preventDefault();
fetch(form.action, {
method: "post",
body: new FormData(form)
}).then(response => {
// do something with the response...
});
}
The e.preventDefault() makes sure that the page is not reloaded when you click the submit button. This assumes your form has the id the-form, like this:
<form id="the-form" method="post" action="/analyze"> ... </form>

Passing value via URL to controller from JSP in Spring MVC

Created an application. Page A displays a droplist containing list of values. If user clicks on particular account, will display a chart. We have similar button right to the acccount droplist. Those are separate JSP's. If user clicks on Page A, then selected account name should move to those 4 jsp page. I have tried via URL. But not getting. Please help.
JSP 1
<a id="priorityCallAnalysis" class="item"> <button type ="button" onclick="getPriorityCall()">Priority </button> </a>
<form:form action="somepage" method="post" commandName="somedata"
id="taskDetails" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Choose Account*</label>
<form:select path="accountName" class="form-control"
id="accountName" onchange="getDashboard()">
<form:option value="" label="--select--"></form:option>
<c:forEach items="${accountList}" var="accountName">
<form:option value="${accountName}" label="${accountName}"></form:option>
</c:forEach>
</form:select>
</div>
</div>
</div>
</form:form>
function getPriorityCall()
{
var accountName = $("#accountName").val();
alert(accountName);
window.location="priorityCall.html?accountName="+accountName+"";
}
Controller
#RequestMapping(value="/priorityCall")
public ModelAndView priorityCall(Map<String, Object> model,#RequestParam ("accountName") String accName)
{
System.out.println("entry");
SampleBean template = new SampleBean ();
model.put("template ", template );
List<String> accountList = Service.getAccountList();
model.put("accountList", accountList);
model.put("accName", accName);
return new ModelAndView("analByPrior","","");
}
JSP : analByPrior
<form:form action="#" method="post" commandName="somedata"
id="taskDetails" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Choose Account*</label>
<form:select path="accountName" class="form-control"
id="accountName" onchange="getAssignmentGroups()">
<form:option value="" label="--select--"></form:option>
<c:forEach items="${accountList}" var="accName">
<form:option value="${accName}" selected="true"> ${accName}</form:option>
</c:forEach>
</form:select>
</div>
</div>
</div>
</form:form>
UPDATE
While clicking on Priority Button, this controller is getting called, instead of PriorityCall.. I dont know y..
#RequestMapping("/priorityCallAnalysis")
public String someAction(#ModelAttribute("accountName") TicketInfo data, Map<String, Object> map,
HttpServletRequest request) {
TicketInfo somedata = new TicketInfo();
map.put("somedata",somedata);
System.out.println(somedata);
System.out.println("acc=" + request.getParameter("accountName"));
/* do some process and send back the data */
map.put("somedata", data);
map.put("accountName", request.getParameter("accountName"));
return "analysisByPriority";
}
First in the .jsp file you can use a global variable to store context path and use this variable as prefix in all the relative paths.
<script>var context = "${pageContext.request.contextPath}"</script>
Now within your js function use the context path and call the controller.
function getPriorityCall(){
var accountName = $("#accountName").val();
alert("contextPath: "+context); // will print your {appName}
window.location=context+"/priorityCall?accountName="+accountName;
}
So your URI looks like below in your request call.
http://localhost:8080/{appName}/priorityCall?accountName={acountName}
PS:
benefit of use this ${pageContext.request.contextPath} is if you change your appName later you dont need to change it in views. It will automatically get the latest contextPath.
If you are using Firefow browser install the firebug add-on and Use it for to verify your requests. So you can validate your URI with params.(If its chrome use Inspect Element to validate URI)

Problems with bootstrap form and POST Method

i was making a simple page with a formulary using bootstrap and Eclipse (With JBoss).
Html code(Just < body > part):
<div class="jumbotron">
<div class="container">
<form method="POST" class="form-inline" action="validarIngresoAdmin.htm">
<h4>Ingrese sus datos:</h4>
<input type="text" class="form-control input-sm" placeholder="Email" name="txtEmail">
<input type="password" class="form-control input-sm" placeholder="Password" name="txtPsw">
<button type="submit" class="btn btn-danger">Iniciar sesi&#243n</button>
</form>
</div>
but when i try to get the attributes txtEmail and txtPsw they return null.
Eclipse code:
private void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter pw = response.getWriter();
String email = (String)request.getAttribute("txtEmail");
String pass = (String)request.getAttribute("txtPsw");
}
¿Why 'email' and 'pass' attributes return null?
P.S: Sorry about my english.
Thanks.
To retrieve http variables, you should be using getParameter rather than getAttribute.

Liferay: How to make enctype="multipart/form-data" and method="post" work together?

I'm developing a web app using liferay portal server 6.2
JSP code -
<form id="mainForm" action="<portlet:actionURL/>" method="post" enctype="multipart/form-data" >
<input type="hidden" id="varImport" name="varImport"/>
<div class="tab-pane" id="uploadFile">
<p>Please upload a file</p>
<div id="inputFileDiv">
<input type="file" name="uploadFile" />
</div>
</div>
<input type="submit" class="btn btn-info" onClick="import()" value="IMPORT" />
</form>
<script>
function import() {
console.log("importing");
document.getElementById("varImport").value = "IMPORTFILE";
document.getElementById("mainForm").submit();
}
</script>
Servlet code -
#Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
System.out.println("myPortlet.processAction() >> " + request.getParameter("varImport"));
//... rest of the code.
}
If I remove enctype from jsp form, I get the value of varImport in my servlet.
But if i keep it, it returns null.
What am i missing?
import com.liferay.portal.util.PortalUtil;
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("myPortlet.processAction() >> " + uploadRequest.getParameter("varImport"));

How to save event data into an xml file from dhtmlxscheduler

I need to save event data to an xml file.I need to do this using a java code.i am using html5.
So from the javascript i need to call this java code and need to save event text,date and other details to an xml file.And whenever the data is needed it should be displayed back in the dhtmlx scheduler.How can i do this?
function init() {
scheduler.config.xml_date="%Y-%m-%d %H:%i";
scheduler.config.prevent_cache = true;
scheduler.init('scheduler_here',new Date(2010,0,20),"month");
scheduler.load("data/data.xml");
}
function show() {
alert(scheduler.toXML());
}
function save() {
var form = document.forms[0];
form.action = "./data/xml_writer.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
function download() {
var form = document.forms[0];
form.action = "./data/xml_download.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
xml_writer.php
<?php
file_put_contents("./data.xml",$_POST["data"]);
header("Location:./dummy.html");
?>
<?php
if(empty($_POST['data'])) {
echo "why";
exit;
}
xml_download
$filename = "data.xml";
header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $_POST['data'];
?>
html code
<form action="./php/xml_writer.php" method="post" target="hidden_frame" accept-charset="utf-8">
<input type="hidden" name="data" value="" id="data">
</form>
<iframe src='about:blank' frameborder="0" style="width:0px; height:0px;" id="hidden_frame" name="hidden_frame"></iframe>
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<input type="button" name="download" value="Download" onclick="download()" style="right:500px;" />
<input type="button" name="show" value="Show" onclick="show()" style="right:400px;" />
<input type="button" name="save" value="Save" onclick="save()" style="right:300px;" />
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
This much code i have.But code for saving to an xml file is in php.I need java code instead of php.

Categories

Resources