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
Related
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.
i cant get the value of a freeMarker variable when i put my code in a external javascript file
here is my page when the javascript code inside, this works i can get the value of my freemarker variable in this way:
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign title="value 1">
<#assign subtitle="value 2">
<script>
function doAjaxPost()
{
var name= $('#name').val();
var lastName= $('#lastName').val();
var json = {"name" : name, "lastName" : lastName};
console.log(json);
var variableFreeMarker = "${freeMarkValue}";
console.log('this value is: ' + variableFreeMarker);
$.ajax(
{
type: "POST",
url: "myUrl",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
but if i put my javascript code in a external file in this case myPageScript.js and then call that script in my page i cant get the value of my freeMarker variable this is how i'm calling my script
<script src="../resources/js/scripts/myPageScript.js"></script>
and this is my page that dont work
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
<br>
</#layout.masterPageLay>
this output in my chrome console "${freeMarkValue}" instead of the value of the variable
here are my controllers i'm processing the form using jquery ajax
#RequestMapping(value = "myForm", method = RequestMethod.GET)
public String myForm(Model model) {
model.addAttribute("freeMarkValue", "controll");
return "myForm";
}
#RequestMapping(value = "myForm", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User objetmapped = mapper.readValue(json, User .class);
User person = new User iox();
person.setName(objetmapped .getName());
person.setLastName(objetmapped .getLastName());
);
model.addAttribute("freeMarkValue", "second controller value");
return toJson(objetmapped );
}
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
You can move your variable into a script block in the html page.
<#import "../masterPage.html" as layout>
<#layout.masterPageLay bread1="my bread1" bread2="my bread2">
<#assign titulo="value 1">
<#assign subtitulo="value 2">
<script src="../resources/js/scripts/myPageScript.js"></script>
<script>
// This variable can be accessed from myPageScript.js
var variableFreeMarker = "${freeMarkValue}";
</script>
<form name="myform">
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
Show modify name in view: <input type="text" id="modifyname" name="modifyname">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
Or add it as a value of a hidden input etc..
<input type="hidden" id="myVal" value="${freeMarkValue}">
Your JS (in a seperate script) would then need to read the value for example using jQuery.
var aValue = $("#myVal").val();
I use the first method for common stuff such as adding a date format string that is specific to the user on to every page. They will have global scope so be careful with naming.
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
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); }
}
);
I started to change my software from Primefaces to HTML5 client - server solution.
Problem: Same origin policy failed when using POST, but it is working when using GET.
WEB SERVICE
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(Users entity) {
super.create(entity);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<Users> findAll() {
return super.findAll();
}
FILTER
public class CrossOriginResourceSharingFilter implements ContainerResponseFilter {
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
return response;
}
}
WEB.XML
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>entity.CrossOriginResourceSharingFilter</param-value>
</init-param>
CLIENT
<form id="register-form">
<div class="register-form-block">
<input type="text" value='Your first name' name="firstName" id="firstName"/>
</div>
<div class="register-form-block">
<input type="text" value='Your surname' name="lastName" id="lastName" onclick="this.value = ('')" />
</div>
<div class="register-form-block">
<input type="text" value='Username' name="username" id="username" onclick="this.value = ('')"/>
</div>
<div class="register-form-block">
<input type="password" value='Password' name="password" id="password" onclick="this.value = ('')"/>
</div>
<div class="register-form-block">
<input type="password" value='Password again' name="passwordagain" onclick="this.value = ('')"/>
</div>
<button type="submit" class="btn btn-primary" id="btnAddUser" onclick="foo()">Register</button>
</form>
<script>
function foo(){
alert('Button pressed');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'http://127.0.0.1:8080/testsoft/webresources/entity.users/',
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR) {
alert('User created successfully');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('addUser error: ' + textStatus +' ERROR:'+ errorThrown);
}
});
};
function formToJSON() {
alert($('#username').val());
return JSON.stringify({
"username": $('#username').val(),
"firstName": $('#firstName').val(),
"lastName": $('#lastName').val(),
"password": $('#password').val(),
});
}
</script>
ERROR
Failed to load resource: the server responded with a status of 500 (Internal Server Error) (22:49:54:618 | error, network)
at http://localhost:8080/testsoft/webresources/entity.users/
XMLHttpRequest cannot load http://localhost:8080/testsoft/webresources/entity.users/. Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (22:49:54:618 | error, javascript)
ANOTHER SOLUTION NOT WORKING, NO ERRORMESSAGE AT ALL
function foo(){
alert('Button pressed');
console.log('#####################addUser################################');
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://127.0.0.1:8080/testsoft/webresources/entity.users/",
dataType: "json",
data: {"username":"UllaUser","password":"testpwd","firstName":"Unto","lastName":"lastnameson","nickName":null,"isAdmin":false,"isCustomer":false,"isGuest":false,"isActive":true,"isInvemailsent":false,"isInvCardSent":null,"inSaveDateSent":false,"isThankCardSent":false,"weddingAsUser":false,"hasGuestUsers":false,"userRole":null,"email":null,"createDate":null,"turnout":null,"lastUpdated":1360240740000,"secretQuestion":null,"secretAnswer":null,"weddingWeddingId":null,"languageLanguageId":null,"invitationInvitationId":null,"emailEmailId":null,"addressAddressId":null},
success: function(data){
// we have the response
alert("Server said:\n '" + data.username + "'");
},
error: function(data) {
alert('addUser error: ' + data.username);
}
});
};
this could be because some browsers (like chrome) sandbox localhost. Try plugging in your ip instead of localhost, and see if that does anything.