getParameters keeps returning null - java

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) {
// ^^^^^^^^^^^^^^^^^^^
// ...
});
}

Related

User interface does not come out when passing the value to servlet using link <a href>

I'm implementing MVC using JAVA. I want to display the details from db. I'm passing the value using link which direct to the servlet page. The details from the db come out on the screen but the problem is the user interface does not appear. I have already include all of my CSS style files in jsp pages. But when I run the page itself without connecting to servlet, the UI appear nicely.(but without it data from db)
How can I solve this? Help me.
Here are the codes;
1.jsp file(where the input value):
'
Search Patient :
<div class="col-sm-9">
<input type="text" id="empid" name="empid" placeholder="ID" class="col-xs-10 col-sm-5" />
</div>
</div>
<div class="space-4"></div>
<div class="clearfix form-actions">
<div class="col-md-offset-3 col-md-9">
Search
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>'
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("13124124");
String forward="";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("view")){
System.out.println("sdfvdsdsg");
forward = "/cms/viewempdetail.jsp";
int empid = Integer.parseInt(request.getParameter("empid"));
Employee employee = empdao.EmployeebyId(empid);
System.out.println(employee.getEmpName());
request.setAttribute("employee", employee);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
}
}
'

Send a message from html to Servlet java using ajax

I have a stupid proplem for send the input from a html page to a servlet using ajax.
Practically I create the message java how I learned, but the servlet doesn't read the input value. I insert my code
<div class="col_9">
<h1>Ricerca Dataset</h1>
<div class="form">
<div class="col_9">
<div class="col_12">
<div class="col_5">Cerca:</div>
<div class="col_6">
<input id=query type="text" name="name" />
</div>
</div>
</div>
<div class="col_3">
<button id="cerca" class="large">Cerca</button>
</div>
</div>
</div>
function cercaNormaleFn() {
$("#cerca").click(function(e) {
$("#center").load("ShowResult.jsp", function() {
var oTable = $('#example').dataTable({
"processing" : true,
"ajax" : {
url : context + "/CercaServlet",
dataSrc : "demo",
type : "Post",
data : "query=" + $("#query").val(),
}
});
alert(query)
});
});
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
System.out.println(request.getAttribute("data"));
}
You may need to add the attribute to your dataTable function:
"serverSide": true
as dataTables.net Server-side processing explains:
With server-side processing enabled, all paging, searching, ordering etc actions that DataTables performs are handed off to a server
A demo from dataTables.net post demo

Submit more forms with one button in jsp

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

JSP + JavaScript + Servlet Unexpected Results

I have a form on a jsp which calls a javascript function which latter calls a servlet. However the code mention below works once in while and when the code does reach the servlet the parameters return null. Also its really bizarre but it jumps between The doGet and doPost method even though i specify "POST". Can someone assist me with the correction.
JAVASCRIPT:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$().ready(function() {
$('.my_button').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "POST",
data: dataf,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
</script>
JSP FORM:
<form id="newsletter" method="POST">
<div class="wrapper">
<div class="bg">
Email:<input type="text" id="email">
</div>
<div class="bg">
Password:<input type="password" id="password">
</div>
<button class="my_button" name="login" >login</button>
</div>
</form>
SERVLET "loginServlet":
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String email = request.getParameter("email");
String password = request.getParameter("password");
String loginResult = login(email,password);
System.out.println("EMAIL:" +email);
System.out.println("PASSWORD:" +password);
System.out.println("IM INSIDE GET!!!!");
response.getWriter().write(loginResult);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String email = request.getParameter("email");
String password = request.getParameter("password");
String loginResult = login(email,password);
System.out.println("IM INSIDE POST!!!!");
response.getWriter().write(loginResult);
}
If any other information is required please let me know. Thank you for the help in advance.
I Found the solution through this site, thank you for the help everyone!
http://coderlearner.com/Java_Servlet_doGet_Ajax_JSON#LoginJSON.java
Three points here,
In the html, your button will end up submitting your form to the current url (Refer https://stackoverflow.com/a/9824845/1304559)
Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).
In the html, <form>, add onsubmit="return false". Just to be entirely safe that it does not post back to the current url.
One question - what does processRequest do in your servlet code?

Unable to Access Request Parameter in SpringMVC Controller while redirecting to URL

I am having a form which submits new articles to my controller.
JSP Page:
<form class="form-signin" method="post"
action="/articleViewer">
<div class="control-group" style="margin-top: -5px;">
<label class="control-label text-info" for="commentContent"><strong>Post
Comment</strong></label>
<div class="controls">
<textarea class="FormElement" name="area2" id="commentContent"
style="width: 100%;"></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-left: 90%;">Post</button>
</form>
Controller Method:
#RequestMapping(value="/articleViewer", method = RequestMethod.POST)
public String saveArticleComment (HttpServletRequest request, HttpServletResponse response,Principal principal, ModelMap map) throws ServletException, IOException{
//processing request
System.out.println("Link : "+Path.Jsp.ARTICLE_VIEWER_PAGE);
return Path.Jsp.ARTICLE_VIEWER_PAGE; //this ARTICLE_VIEWER_PAGE = /articleViewer
}
Now from the above controller method I wanna redirect to another method where I want to pass
currently saved article id as http://<myurl>/article?articleId="xyz".
Here is my get method code for handling the redirect.
#RequestMapping(value="/articleViewer", method= RequestMethod.GET)
public String articleViewer(HttpServletRequest request, Principal principal,
ModelMap map, HttpServletResponse response)
throws DatabaseException {
//I wanna access article id here.
return Path.Jsp.ARTICLE_VIEWER_PAGE;
}
I wanna know how could I access that passed request parameter in above method?
If you submit the action url without parameter, or use hidden field for this purpose then you should return that parameter back as a result. So, you don't get it lost, or redirect to the page where the parameter is not needed anymore. To pass parameter in the url use
<form class="form-signin" method="post" action="/articleViewer?varArticleID=94">
I Resolved it by using Redirect attribute in return ...
return "redirect:/articleViewer?varArticleID="+getVarArticleID();
So if you need the page like as after submitting change the action value of form like
<form class="form-signin" method="post"
action="/articleViewer?varArticleID={yourArticleid}">
Also after submit you need
return Path.Jsp.ARTICLE_VIEWER_PAGE+"?varArticleID="+request.getParameter("varArticleID");

Categories

Resources