how to pass datalist values from jsp to servlet - java

I have written a jsp file and servlet .In jsp I have used data list inside a form .And I want to pass that user input to the servlet.I have posted the code below.
jsp code
<form action="NewServlet1" method="Post" >
<center>
<input type="text" name="website" list="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist><br><br><br>
</center></form>
<div style="width: 400px; height: 400px">
<canvas id="myChart" width="1000" height="1000" ></canvas>
</div>
<center> <div>
<button id="button1" name="button1" onclick="submit()" class="btn btn-primary">submit</button>
</div></center>
<script>
function Test(today, time) {
var ctx = new Chart(document.getElementById("myChart")
, {
type: 'line',
data: {
labels: today,
datasets: [{
data: time,
label: "Web Service 1",
borderColor: "red",
fill: false
}
]
},
options:
{
scales: {xAxes: [{display: true, scaleLabel: {display: true, labelString: 'date and time'}}], yAxes: [{display: true, ticks: {beginAtZero: true, steps: 100, stepValue: 50, max: 6000}}]},
hover: {intersect: false },
title: {display: true, text: 'response time of selected website'},
tooltips: { mode: 'nearest'}
}
});
}
function submit()
{
$.post("NewServlet1",
{
},
function (data)
{
Test(data.today, data.time);
});
}
servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
But this is not working.Can someone help me to solve this?

First of all you need to submit the form to the servlet which path is mapped to NewServlet1
<form action="NewServlet1" method="Get" >
<center>
<input type="text" name="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist>
</center>
<%
String website= request.getParameter("website"); // it is not needed
request.setAttribute("website",website); // it is not needed
%>
<input type="submit"/> <!--need to add submit button to submit it to the servlet-->
</form>
Now your servlet code is fine which is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
}
Note : Need to write some value in website text box
Or if you want to get attribute which previously stored in request object then use RequestDispatcher.

Related

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

Save data by kendo ui and java servlet

Can anybody tell me how to save data by kendo ui and java servlet. That means i have design html fields like Student ID, Student name and want to save it using kendo ui framework and java servlet and return json formatted data after execute my insert query from java servlet.Please consider i am very new to java.
Here is my html
<div id="PaymentMasterDetailsDiv" >
<ul>
<li>
<label for="User" class="required lbl widthSize15_per">User:</label>
<input type="text" id="txtUser" name="User" class="" maxlength="50" value="123" placeholder="Pleaes Select Payment Id" required validationmessage="Please enter Payment Id" />
</li>
<li>
<label for="Password" class="required lbl widthSize15_per">Password:</label>
<input type="text" id="txtPassword" name="Password" class="" maxlength="50" value="123" placeholder="Pleaes Select Payment Id" required validationmessage="Please enter Payment Id" />
</li>
</ul>
<button id="btnSave" class="k-button" type="button" >Save</button>
</div>
And here is my .js to call my .java
SaveCommonInformation: function () {
var objBranchInfo = 0;
var serviceUrl = "/api/LoginController";
jQuery.ajax({
url: serviceUrl,
// data: jsonParam,
type: "POST",
processData: true,
contentType: "application/json",
dataType: "json",
success: onSuccess,
error: onFailed
});
function onSuccess(jsonData) {
if (jsonData == "Success") {
alert("Success");
}
else if (jsonData == "Common Already Exist") {
alert();
}
else {
alert("Exist");
}
}
function onFailed(error) {
alert("Error");
}
}
and this is my .java
#WebServlet("/LoginController")
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginController() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
but i can't understand how actually connect to database and insert to database something and also return "Success" or "Common Already Exist" in json formate

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

Show Servlet Response in some <div>

What I'm trying to do
I'm building a small webapp with Netbeans, which can search for a ZIP-Code. The layout is made with bootstrap.css. Now I made following form in my (index.jsp):
<form id="form_submit_search"
class="navbar-form navbar-right"
role="form"
action="zipSearchHandler"
method="get">
<div class="form-group">
<input name="tv_zip"
type="text"
placeholder="ZIP Code..."
class="form-control">
</div>
<button id="submit_search"
type="submit"
class="btn btn-success">Search</button>
</form>
When the Button is klicked following method in the servlet is getting called:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String zipCode = request.getParameter("tv_zip");
System.out.println(zipCode + " habe den zip bekommen");
response.setContentType("text/html;charset=UTF-8");
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
list.add(zipCode);
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
This give's me back a simple json-array, which is opened in a new site, but I'd like to show that response in some <div> in my index.jsp. How can I do that?
You could use something like this
$.ajax(
{
type: "POST",
url: "/TestServlet",
data: { tv_zip: '90210' }, // zipcode
dataType: "json",
success: function(response) {
// replace the contents of div with id=some_div with the response.
// You will want to format / tweak this.
$('#some_div').html(response);
},
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
}
);

Categories

Resources