I am using jquery Datatables and I am getting this error: DataTables warning: table id=example - Ajax error. This is MVC app. Data is from MSQL database. have no error on chrome's console. Maybe it is a syntax problem?
Here is my .jsp file:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
<script>
function confirmDelete(id) {
if (confirm("Are you sure to delete this cost?")) {
window.location.href = "/cost/delete/" + id;
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="../../resources/js/datatable.js"></script>
</head>
<body>
<table id="example" class="display" style="width:80%">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
<th>MPK</th>
<th>Account</th>
<th>Client</th>
<th>Amount</th>
<th>Description</th>
<th>Payment</th>
<th>Invoice Number</th>
<th>Department</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:forEach var="costs" items="${allcosts}">
<tr>
<td>${costs.id}</td>
<td>${costs.salesDate.toString()}</td>
<td>${costs.mpk.code}</td>
<td>${costs.account.code}</td>
<td>${costs.client.name}</td>
<td>${costs.amount.toString()}</td>
<td>${costs.description.toString()}</td>
<td>${costs.payment.type}</td>
<td>${costs.invoiceNumber.toString()}</td>
<td>${costs.department.name}</td>
<td>Delete</td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
<spring:url value="/report/?type=xls" var="xlsURL"/>
Download Excel
</body>
</html>
Here is my .js file:
$(document).ready(function () {
$('#example').DataTable({
"processing": true,
"serverSide": true,
"pageLength": 5,
"ajax": {
"url": "/cost/all",
"columns": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
{"data": "Delete"},
{"data": "Edit"}
]
} });
});
How can I solve this problem? I am stuck.
Use the following initialization code instead:
$(document).ready(function () {
$('#example').DataTable({
pageLength: 5
});
});
Related
I am using spring mvc with hibernate database connction,now how to pass values in jsp page into java page without call controller ,i am getting Error how to pass values jsp to java??
Jsp page
In this page i am using java code but unable to pass values in another java page
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%#page import="com.sample.utility.AutoIncrement" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>check page</title>
</head>
<body>
<div id="login_form">
<form:form action="check" method="post">
<table>
<tr>
<%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
<td class="f1_label">Shop code :</td>
<td>
<input type="text" name="shopcode" value="<%=val%>" />
</td>
</tr>
<tr>
<td class="f1_label">name :</td><td><input type="text" name="name" value="" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Submit" style="font-size:18px; " />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Java Page :
This below code is java here unable to return values in jsp page
public static String auto(String value)
{
String reVal="";
System.out.println("Inc val : "+value);
Session session = sessionFactory.openSession();
try
{
session.beginTransaction().begin();
String SQL_QUERY = "{CALL pro_autoincrement('"+value+"') }";
query = session.createSQLQuery(SQL_QUERY);
reVal=query.toString();
System.out.println("Inc val : "+reVal);
session.getTransaction().commit();
}
catch(Exception ex)
{
if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE
|| session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {
session.getTransaction().rollback();
}
}
finally
{
session.close();
}
return reVal;
}
Error:
SEVERE: Servlet.service() for servlet [jsp] in context with path [/annotation-based] threw exception [An exception occurred processing JSP page /welcome.jsp at line 18
15: <table>
16:
17: <tr>
18: <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
19: <td class="f1_label">Shop code :</td>
20: <td>
21: <input type="text" name="shopcode" value="<%=val%>" />
Stacktrace:] with root cause
java.lang.NullPointerException
at com.sample.utility.AutoIncrement.auto(AutoIncrement.java:26)
at org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java:81)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
Insted of this.
reVal=query.toString();
you can do like this
reVal=(String)session.createQuery(queryString).UniqueResult();
Above Method Return Object.So we need to type Cast into String Format.
I have a form that has two buttons, a submit button and an update button.
Here is the JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- Bootstrap core CSS !-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Custom scripts/styles for this page !-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/script/script.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/style.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
</head>
<body>
<!-- General Information Form -->
<form:form id="form" method="POST" action="${pageContext.request.contextPath}/create" modelAttribute="task">
<div id="general">
<table style="width: 224px;">
<tr>
<td colspan="2"><form:select id="systemType" path="systemType" items="${systemTypes}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2"><form:select id="userName" path="user.fullName" items="${userFullNames}" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=line><b>Line: </b></label></td>
<td><form:select path="location.line" items="${lines}" id="line"/></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td style="width: 50%;"><label for=position><b>Position: </b></label></td>
<td><form:select path="location.position" items="${positions}" id="position" /></td>
</tr>
<tr>
<td id="buffer"></td>
</tr>
<tr>
<td colspan="2">
<input id="submitButton" type="submit" name="submit" value=Submit />
<input style="display:none;" id="updateButton" type="submit" name="update" value="Update" />
<input id="cancel" style="float: right;" type="Reset" value="Cancel" />
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
Here is my controller:
#Controller
#RequestMapping("/")
public class HomeController {
private TaskService taskService;
#Autowired
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String initForm(Model model, HttpServletRequest request) {
Task task = new Task();
model.addAttribute("task", task);
return "home";
}
#RequestMapping(value="/create", params="submit", method = RequestMethod.POST)
public String submitForm(#ModelAttribute("task")Task task,BindingResult result, Model model) {
taskService.create(task);
return "redirect:/";
}
#RequestMapping(value="/create", params="update", method = RequestMethod.POST)
public String updateForm(#ModelAttribute("task")Task task, BindingResult result, Model model) {
System.out.println("Updating: " + task.toString());
taskService.update(task);
return "redirect:/";
}
The idea being that hitting the submit button will make a new item, and the update button will edit an existing one. The two .POST methods have different parameters specified to distinguish them.
The submit button is working as expected. However when the update button is pressed a Task object is delivered to the updateForm controller method - but all of its fields are null.
I am not sure why the form is binding the fields to the Task correctly on the submit method, but seemingly creating a new Task and not binding it at all in the update method.
I am inclined to just combine these methods into a single controller method and use some Java logic to determine whether to submit/update based on the parameter - but am curious as to what I'm missing and why this doesn't work.
Ok, I feel very stupid. This was not a SpringMVC issue at all. The problem was caused by a Jquery method that was disabling a part of the form. This gave the appearance that the form was not binding, but actually it was just binding to null values.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Populating JSP</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.0/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css" />
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.css" />
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>salary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(document).ready(function() {
$('#example').dataTable( {
serverSide: true,
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(2)', nRow).html('<a href="http://www.google.com' + aData[2] + '">' +
aData[2] + '</a>');
return nRow;
},
ajax : {
url: 'hello/data1',
dataType:'json',
type: 'POST'
}
}
);
});
</script>
</body>
</html>
I have 2 coulmns, ID and Salary. I am linking the salary to google.com, for that I am using fnRowCallback function. But that doesn't seem to work. Where do you think I am going wrong. The jsp is shown above.
Use custom column definition columnDefs to alter column rendering.
$('#example').dataTable( {
serverSide: true,
"aoColumnDefs" : [
{
"mData": "name",
"sClass": "dataTable-user-list-name",
"fnRender": function (oObj) {
return '<a href="/#/' + oObj.aData['detailsUrl'] + '">oObj.aData['name']<a>'
}],
ajax : {
url: 'hello/data1',
dataType:'json',
type: 'POST'
}
}
here i am trying to submit a form request through jquery but i don't know why i am unable to do so it just executes the code and nothing is visible on my console.when i try to submit form normally through form action it is successful.any help is thank full.
Jquery & jsp form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.List,beans.Country,mainclasses.CountryListing" errorPage=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Post a property</title>
<jsp:useBean id="CNY" class="beans.Country" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="js/combochange.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact_details_submit").click(function() {
var companyname = $("#company_name").val();
var officeaddress = $("#office_address").val();
var countryname = $("#country_name option:selected").val();
var statename = $("#state_name option:selected").val();
var cityname = $("#city_name option:selected").val();
var mobile_num = $("#mobilenum").val();
alert(companyname+" : "+officeaddress);
$.get("conatctDetailsInsert.jsp",
{
company_name : companyname,
office_address:officeaddress,
country_name:countryname,
state_name:statename,
city_name:cityname,
mobilenum:mobile_num} ,function(data){
alert(data);
});//end get
});
});
</script>
</head>
<body>
<form action="">
<table cellpadding="0" cellspacing="0" border="1" width="500">
<tbody id="contact_details">
<tr>
<td>i am a
<select>
<option>Agent/broker</option>
<option>Builder/Pvt.Ltd company</option>
</select>
</td>
</tr>
<tr>
<td><h3>Contact Details</h3></td></tr>
<tr>
<td>
Company Name:<input type="text" value="" id="company_name" name="company_name"/>
</td></tr>
<tr>
<td>Office Address:<input type="text" value="" id="office_address" name="office_address"/><br>
Country:
<select id="country_name" name="country_name">
<option>-Select-</option>
<%
mainclasses.CountryListing CNY_CL = new mainclasses.CountryListing();
List<Country> CNY_List=CNY_CL.getCountry();
for(int i=0; i < CNY_List.size(); i++ ){
CNY=(beans.Country)CNY_List.get(i);
%>
<option value="<%=CNY.getIdCountry() %>"><%=CNY.getCountryName() %></option>
<%} %>
</select><br>
State:<select id="state_name" name="state_name"><option></option></select><br>
City:<select id="city_name" name="city_name"><option></option></select><br>
</td>
</tr>
<tr>
<td>
Contact Number:
<input type="tel" id="mobilenum" value="" name="mobilenum"/>
</td>
</tr>
<tr>
<td>
<input type="submit" id="contact_details_submit" name="contact_details_submit"/>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Request handling jsp:
<%#page import="beans.ConatctDetailsService"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%boolean x=false;
String company_name =request.getParameter("company_name");
String office_address =request.getParameter("office_address");
String country_name =request.getParameter("country_name");
String state_name =request.getParameter("state_name");
String city_name =request.getParameter("city_name");
String mobilenum =request.getParameter("mobilenum");
beans.ConatctDetailsService CTD = new beans.ConatctDetailsService();
CTD.setCompanyName(company_name);
CTD.setCompanyName(office_address);
CTD.setIdCountry(country_name);
CTD.setIdState(state_name);
CTD.setCity(city_name);
CTD.setMobNum(mobilenum);
x=CTD.insert();
System.out.println(x);
CTD.geterror();
if(x){
out.println("done");
}
else{
out.println("no");
}
%>
Try adding an id to the form tag e.g.
<form id='myForm'>
And change to a on form submit.
$(document).ready(function(){
$("#myForm").on('submit', function(e) {
e.preventDefault();
try putting AJAX request to check what's happening:
$.ajax({
type:'GET',
url: 'conatctDetailsInsert.jsp',
data: {company_name : companyname,
office_address:officeaddress,
country_name:countryname,
state_name:statename,
city_name:cityname,
mobilenum:mobile_num},
success: function(data) {
console.log(data);
}, error: function(jqXHR, textStatus, errorThrown) {
console.log(err);
}
});
I would do it this way, much cleaner.
$("form").submit(function(e) {
var formData = $(this).serialize();
$.get("conatctDetailsInsert.jsp",formData, function(data){
alert(data);
});//end get
return false;
});
Hi i am new in jsp and Spring. I have a table of employee information. I want to add a edit link in each row and an edit link will be click it will send the primary key of the row to the controller. When i click the edit link it display the error "The request sent by the client was syntactically incorrect ()."
This page display the table
employeeList.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 align="center">Employee List</h1>
<table align="center" border="1">
<tr><th>Pk</th><th>Employee Name</th><th>Employee email</th><th>Address</th><th>Manager Id</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="employeeList" items="${list}">
<tr>
<td><c:out value="${employeeList.id}"/></td>
<td><c:out value="${employeeList.name}"/> </td>
<td><c:out value="${employeeList.email}"/> </td>
<td><c:out value="${employeeList.address}"/></td>
<td><c:out value="${employeeList.managerId}"/></td>
<td><a href="editEmployee.htm?id=${id}" >Edit</a></td>
<td><a href="deleteEmployee.htm?id=${id}" >Delete</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
my controller code is
#RequestMapping(value="/editEmployee.htm")
public String editEmployee(#RequestParam("id") int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
editEmployee.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
Edit Employee<br>
</body>
</html>
How i can solve this problem.
Change your jsp to something like this
<c:url var="editUrl" value="/editEmployee.htm" />
<a href="${editUrl}?id=${employeeList.id}">
Edit
</a>
<c:url var="deleteUrl" value="/deleteEmployee.htm" />
<a href="${deleteUrl}?id=${employeeList.id}">
Delete
</a
#RequestMapping(value="/editEmployee.htm") - wrong
#RequestMapping(value="/editEmployee/{id}")
public String editEmployee(#PathVariable int id,ModelMap model){
try {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
return "editEmployee";
} catch (Exception ex) {
return "index";
}
}
and also a href="editEmployee.htm?id=${id}
this should be something like a href="editEmployee/${id}