How to connect data from Oracle database to Kendo Grid using Java? - java

I could able to create a grid using local data. I want to know how to get data from Oracle database to display as a Kendo Grid?
How to modify "read" function in datasource to get data?
Servlet
public class TeacherListPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
ArrayList<MessageObjects> listArr;
OracleConnection oraconn= new OracleConnection();
listArr= oraconn.teacherDetails();
System.out.println("In teacher servlet \n" );
if(!listArr.isEmpty()){
Gson gson= new Gson();
String json=gson.toJson(listArr);
System.out.println("In list");
System.out.println(json);
request.setAttribute("list",json);
request.getRequestDispatcher("Grid.jsp").forward(request, response);
//response.sendRedirect("Grid.jsp");
}
else
{
System.out.println("list is empty");
}
}
}
listArr= oraconn.teacherDetails(); will call OracleConnection.java
OracleConnection
public ArrayList teacherDetails()
{
ArrayList<MessageObjects> list= new ArrayList<MessageObjects>();
ArrayList<String> list1= new ArrayList<>();
MessageObjects obj= new MessageObjects();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","STUDENT_DB","Aishwarya11");
Statement statement=con.createStatement();
ResultSet rs= statement.executeQuery("select * from TEACHERS_DETAILS");
while(rs.next()) {
obj.setTid(rs.getString(1));
obj.setName(rs.getString(2));
obj.setGender(rs.getString(3));
obj.setDob(rs.getString(4)) ;
obj.setYoe(rs.getString(5)) ;
obj.setMajsub(rs.getString(6));
list.add(obj);
Gson gson= new Gson();
String json=gson.toJson(obj);
System.out.println("In DAO");
System.out.println(json);
list1.add(json);
System.out.println("List1");
}
}
catch (SQLException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return list1;
}
Forwarding data from servlet to jsp(Grid.jsp)
Grid.jsp
<div id="grid"></div>
<script>
$(document).ready(function() {
var dataSource= new kendo.data.DataSource({
transport:{
read:{/* I want to know how to read data here , how to code ?*/,
dataType : "json",
type: "POST",
}
},
schema:{
data: "xdata.rows",
model:{
id:"tid",
fields:{
// tid:{editable:false},
tid:{type:"String"},
name:{type:"String"},
gender:{type:"String"},
dob:{type:"String"},
yoe:{type:"String"},
majsub:{type:"String"}
}
}
},
pageSize:20,
batch:true
});
$("#grid").kendoGrid({
dataSource:dataSource,
height:350,
scrollable: true,
columns:[{field: "tid",title:"Teacher Id",width: "130px"},
{field: "name",title:"Name",width: "130px"},
{field: "gender",title:"Gender",width: "130px" },
{field: "dob",title:"Date of Birth",width: "130px"},
{field: "yoe",title:"Year of Experience",width: "130px"},
{field: "majsub",title:"Major sub",width: "130px" },
{command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "popup"
});
});
I am just trying to read data to grid, so i didn't provide Update,Destroy,Create.
I successfully retrieve data from Database and changed it to JSON.
["{\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Physics\"}","{\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}"]
I got this in Grid.jsp, when i tried to view it using
${list}

Data you are passing is not in correct json format.
Compare the changedData and yourData in the method.
Data is required in array form for Grid, that's why I am converting it into array form. If you have data in array then pass that directly.
that should be like :
var data5 = [{ "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }, { "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }, { "Id": 121, "referenceId": 18222, "status": "test", "message": 'kk', "ss": "ss" }];
You will need kendo js and css file for kendo grid.
Use these :
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.common-material.min.css">
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.226/styles/kendo.material.min.css">
<script src="//kendo.cdn.telerik.com/2016.1.226/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.226/js/kendo.all.min.js"></script>
<div id="grid" data-role="grid" class="k-grid k-widget k-editable" style="height: 550px;">
<script>
$(document).ready(function () {
var yourData = ["\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Physics\"}", "{\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}"]
var changedData = "[{\"tid\":\"001\",\"name\":\"Varalakshmi\",\"gender\":\"Female\",\"dob\":\"01/08/1989\",\"yoe\":\"2\",\"majsub\":\"Maths\"}, {\"tid\":\"002\",\"name\":\"Lakshman\",\"gender\":\"Male\",\"dob\":\"05/08/1979\",\"yoe\":\"8\",\"majsub\":\"Maths\"}]";
var feedData = $.parseJSON(changedData);
$("#grid").kendoGrid({
dataSource: feedData,
navigatable: true,
pageable: true,
height: 550,
// toolbar: ["create", "save", "cancel"],
columns: [
{ field: "tid", title: "Unit Price" },
{ field: "name", title: "Units In Stock" },
{ field: "gender", title: "gender" },
{ field: "dob", title: "dob" },
{ field: "yoe", title: "yoe" },
{ field: "majsub", title: "majsub" },
],
editable: true
});
});
</script>
</div>

Related

how to escape part of json loaded as object

I'm not fluent in API testing hence my question. I have a body to POST (mock) that will consist of:
{
"request":
{
"urlPath": "path/to/",
"method": "POST",
"bodyPatterns":[{
"equalToJson" : "{\n\"query\": [\n{\n\"name\": \"name1\",\n\"value\": \"123\"\n },\n{\n\"name\": \"name2\",\n\"value\": \"345\"\n},\n{\n\"name\": \"name3\",\n\"value\": \"someName\"\n}\n],\n\"anotherItem\": [],\n\"side\": 77,\n\"pageSize\": 44\n}", "jsonCompareMode": "LENIENT"
}]
},
"response":
{
"status": 200,
"headers":
{
"Content-Type" : "application/json"
},
"body": "{"items\": [\n{\n\"item\": 1,\n
\"item2\": 2,\n
etc
"\n}\n]\n}"
}
}
I want to use some pojo classes to separately create Request and Response:
public Request initRequest() {
BodyPattern bodyPat = new BodyPattern();
Query query = new Query();
Query query2 = new Query();
Query query3 = new Query();
EqualToJson equalToJ = new EqualToJson();
query.setName("name1");
query.setValue("123");
query2.setName("name2");
query2.setValue("345");
query3.setName("name2");
query3.setValue("someName");
List<Query> queryList = new ArrayList<>();
queryList.add(query);
queryList.add(query2);
queryList.add(query3);
equalToJ.setQuery(queryList);
List<Filter> filtersList = new ArrayList<>();
equalToJ.setFilter(filtersList);
equalToJ.setSide(77);
equalToJ.setPageSize(44);
List<EqualToJson> eqList = new ArrayList<>();
eqList.add(equalToJ);
req.setUrlPath(URL + "/Test001");
req.setMethod("POST");
bodyPat.setEqualToJson(eqList);
bodyPat.setJsonCompareMode("LENIENT");
List<BodyPattern> bodyPatList = new ArrayList<>();
bodyPatList.add(bodyPat);
req.setBodyPatterns(bodyPatList);
return req;
}
To see it in more user-friendly view, here you go:
{
"request": {
"urlPath": "/path/to",
"method": "POST",
"bodyPatterns": [
{
"equalToJson": {
"query": [
{
"name": "name1",
"value": "123"
},
{
"name": "name2",
"value": "345"
},
{
"name": "name3",
"value": "someName"
}
],
"filter": [
],
"side": 77,
"pageSize": 44
},
"jsonCompareMode": "LENIENT"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"side": 77,
"pageSize": 44,
"items": [
{
"name1": "123",
"name2": "345",
"name3": "someName"
etc...
}
]
}
}
}
Similarly, I do with Response.
My question is, how can I make to have just a part of this json (BodyPatters) as escaped signs? Mock is created this way that it only accepts escaped characters in this part of json.
I can of course hardcode this payload, but I want to have control over those fields' values and steer them, as parameters.
I really have no idea how to handle this.
You can use objectmapper of jackson to convert Object to String. For example:
void name2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Query query = new Query("name1", "123");
EqualToJson equalToJson = new EqualToJson();
equalToJson.setQuery(Arrays.asList(query));
BodyPattern bodyPattern = new BodyPattern();
bodyPattern.setEqualToJson(mapper.writeValueAsString(equalToJson));
String bodyPatternText = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(bodyPattern);
System.out.println(bodyPatternText);
}
#Data
#AllArgsConstructor
static class Query{
private String name;
private String value;
}
#Data
static class EqualToJson {
private List<Query> query;
}
#Data
static class BodyPattern {
private String equalToJson;
}
This is a result:
{
"equalToJson" : "{\"query\":[{\"name\":\"name1\",\"value\":\"123\"}]}"
}

Not displaying JSON data in Jquery datatable

I am trying to display sample data from my Java controller into the table, however, it is not rendering the data nor displaying any error messages. For the time being, I am trying to display simple mock data in JSON format...However, the table is not displaying any data nor any error messages..
I am using JSP, AngualrJS and jquery for front end, Java for backend..
This is my JSP Page table:
<table class="table table-striped table-bordered dt-responsive nowrap" id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
</table
This is my JSP page:
$.ajax({
url:"/home/review/",
success:function(data) {
var table = $('#myTable').DataTable( {
"data": data,
dom: "Bfrtip",
"iDisplayLength": 15,
"lengthChange": false,
"ordering": true,
"info": false,
'columnDefs': [
{
'targets': 1,
'orderable': false,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
{ "data": "id", "defaultContent": "" },
{ "data": "status", "defaultContent": ""}
],
});
}
});
This is my angularJS Controller:
angular.module('myApp').controller('HomeController', ['DTOptionsBuilder', 'DTColumnBuilder','HomeService', '$scope', function(DTOptionsBuilder, DTColumnBuilder, HomeService, $scope) {
var test_URL = '/home/review/';
var self = $scope;
var vm = this;
vm.dtOptions = HomeService.fetchList();
console.log(vm.dtOptions);
}]);
My angularJS service:
angular.module('myApp').factory(HomeService', ['$http', '$q', function($http, $q){
var URL= '/home/review/';
var factory = {
fetchList: fetchList
};
return factory;
function fetchList() {
var deferred = $q.defer();
$http.get(URL)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching List');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
This is my Java backend controller:
#RequestMapping(value = "/review/", method = RequestMethod.GET)
public String geList() throws JSONException {
logger.info("List All Controller");
System.out.println("Fetching All list...");
JSONArray resultarray = new JSONArray();
String resultString = "";
JSONObject result = new JSONObject();
result.put("id","1234");
result.put("status", "New");
resultarray.put(result);
resultString = resultarray.toString(4);
System.out.println(resultString);
return resultString;
}
Try JSON.parse() for your data, while passing to the DataTable.

datatables Load data exception

I've got the JSON data behind the scenes, that's it
[{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
Background and foreground code are as follows
#Autowired
private MediaImpl media;
#ResponseBody
#RequestMapping(value = "/media",method = RequestMethod.GET)
public List<Media> MediaAll(){
System.out.println("------------------------------------------------------");
return media.findAll();
}
JS code is as follows
<script>
$(document).ready(function () {
$('#table_id_example').DataTable({
"iDisplayLength": 10,
"bLengthChange": false,
"ajax": {
"url": "/media",
"dataType": "json",
"success": function (json) {
console.log(json)
}
},
"columns": [
{
"data": 'aid'
},
{
"data": 'name'
},
{
"data": 'rtsp'
},
{
"data": 'statuz'
},
{
"data": 'updateTime'
}
]
});
});
html code is as follows
The console code
VM178:10 (2) [{…}, {…}]0: {aid: 100000, name: "JYCM201609010250", rtsp: "947|100000|3750", statuz: "1", updateTime: "2017-05-31"}1: {aid: 100001, name: "gui", rtsp: "947|100000|3750", statuz: "0", updateTime: "2017-05-31"}length: 2__proto__: Array(0)
There is no error in the front-end console, and no errors in the back end.But the data is not available
There are a couple of problems here. The first is that datatables expects data in a data element of the json response, such as:
{
data: [{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
}
You should be able to use ajaxSrc: "" on your DataTable settings.
The second problem is with your ajax settings. DataTables states you can not supply the success callback in the ajax settings as it uses this internally.
Documentation on both of these issues:
https://datatables.net/reference/option/ajax
Assuming you are using DataTables 1.10.x

How to display jqxGrid in spring

I have to implement the jqxGrid using spring.I don't know how to do it on spring.Below is my controller class
AccountController.java:
#Controller
#RequestMapping(value="/account")
public class AccountsController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/list", method = RequestMethod.GET, headers =
"Accept=application/json")
public #ResponseBody ModelAndView listOfAccounts() {
ModelAndView modelAndView = new ModelAndView();
List<Accounts> accounts = accountService.getAccounts();
modelAndView.addObject("accounts", accounts);
return modelAndView;
}
}
I think the json data retrieved from Accounts.java class is in the format :
[{"id":"1","PeriodName":2000-2001,"PeriodStartDate":"2000-01-01","PeriodEndDate":"2001-12-31"},{"id":"2","PeriodName":2001-2002,"PeriodStartDate":"2001-01-01","PeriodEndDate":"2002-12-31"}]
Below is jquery get request for the json response and code for getting the jqxGrid:
$.get('account/list',function(responseJson) {
var data = responseJson;
var source =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'PeriodName' },
{ name: 'PeriodStartDate' },
{ name: 'PeriodEndDate' }
],
id: 'id',
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
//columnsresize: true,
width: 800,
source: dataAdapter,
pageable: true,
//pagerButtonsCount: 10,
autoheight: true,
// editable: false,
pagerrenderer: pagerrenderer,
columns: [
{ text: 'Period Name', datafield: 'PeriodName', width: 200 },
{ text: 'Start Date', datafield: 'PeriodStartDate', width: 200 },
{ text: 'End Date', datafield: 'PeriodEndDate', width: 200 }
]
});
});
But i didn't get the grid on here.I don't know where is the problem in the above code.I have imported all js files for jqxGrid.Please help me to solve this
*I looked on your problem here is the same code (little modified). comment that pagerenderer code .You have not defined the pagerenderer function anywhere. It will work. here is the working code http://jsfiddle.net/qwm3z/ .
responseJson = <c:out value="${accounts}" />;
var data = responseJson;
var source =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'PeriodName' },
{ name: 'PeriodStartDate' },
{ name: 'PeriodEndDate' }
],
id: 'id',
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
//columnsresize: true,
width: 800,
source: dataAdapter,
pageable: true,
//pagerButtonsCount: 10,
autoheight: true,
// editable: false,
// pagerrenderer: pagerrenderer,
columns: [
{ text: 'Period Name', datafield: 'PeriodName', width: 200 },
{ text: 'Start Date', datafield: 'PeriodStartDate', width: 200 },
{ text: 'End Date', datafield: 'PeriodEndDate', width: 200 }
]
});
and why are you making grid in each response? you can make one time and update it for every get request.*

Message alert box in servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
try {
// System.out.println("in mail servlet");
if (action.equals("show")) {
List<EmailSetup> emailSetup_List = emailSetup_lf.findAll();
JSONObject returnJSON = new JSONObject();
JSONArray emailSetup_Array = ListToJSONArray(emailSetup_List);
returnJSON.put("success", true);
returnJSON.put("rows", emailSetup_Array);
// System.out.println(returnJSON.toJSONString());
sendJSONResponse(returnJSON, response);
} else if (action.equals("add")) {
if( emailSetup_lf.count() >= 1 ){
sendJSONResponseSimple("fail", response);
return;
}
// all data is sent to the servelet as strings
// when creating cast to proper DB type
String smtp_host = request.getParameter("SMTP_HOST");
String smtp_user = request.getParameter("SMTP_USER");
String smtp_pwd = request.getParameter("SMTP_PWD");
String smtp_port = request.getParameter("SMTP_PORT");
String smtp_from = request.getParameter("SMTP_FROM");
if ((!smtp_host.equals(""))
&& (!smtp_user.equals(""))
&& (!smtp_pwd.equals(""))
&& (!smtp_port.equals(""))
&& (!smtp_from.equals(""))) {
EmailSetup new_email_setup_record = new EmailSetup();
new_email_setup_record.setSmtpHost(smtp_host);
new_email_setup_record.setSmtpUser(smtp_user);
new_email_setup_record.setSmtpPwd(smtp_pwd);
new_email_setup_record.setSmtpPort(smtp_port);
new_email_setup_record.setSmtpFrom(smtp_from);
emailSetup_lf.create(new_email_setup_record);
// LOG
systemLog("Create (MailServerSevlet)", "Created Mail Server: " + new_email_setup_record.toString(), request);
}
} else if (action.equals("edit")) {
// all data is sent to the servelet as strings
// when creating cast to proper DB type
String e_id = request.getParameter("E_ID");
String smtp_host = request.getParameter("SMTP_HOST");
String smtp_user = request.getParameter("SMTP_USER");
String smtp_pwd = request.getParameter("SMTP_PWD");
String smtp_port = request.getParameter("SMTP_PORT");
String smtp_from = request.getParameter("SMTP_FROM");
if ((!smtp_host.equals(""))
&& (!smtp_user.equals(""))
&& (!smtp_pwd.equals(""))
&& (!smtp_port.equals(""))
&& (!smtp_from.equals(""))) {
EmailSetup email_setup_record = emailSetup_lf.find(new BigDecimal(e_id));
email_setup_record.setSmtpHost(smtp_host);
email_setup_record.setSmtpUser(smtp_user);
email_setup_record.setSmtpPwd(smtp_pwd);
email_setup_record.setSmtpPort(smtp_port);
email_setup_record.setSmtpFrom(smtp_from);
// CALL EDIT!
emailSetup_lf.edit(email_setup_record);
// LOG
systemLog("Update (MailServerSevlet)", "Updated Mail Server: " + email_setup_record.toString(), request);
} // systemLog
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</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 doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* 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);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short Description";
}// </editor-fold>
}
I have now tried using a JSON simple response, but it keeps calling the wrong error message
var db_drivers_Store = new Ext.data.JsonStore({
//url: '../DataBaseDriversServelet_show',
url: '../DataBaseDriversServelet?action=show',
root: 'rows',
idProperty: 'ID',
fields: [{
name: 'ID',
type: 'int'
},{
name: 'TYPE',
type: 'string'
},{
name: 'NAME',
type: 'string'
},{
name: 'ADDRESS',
type: 'string'
},{
name: 'PORT',
type: 'int'
}]
});
// ADD
var add_db_driver_Window = new Ext.Window({
title: 'Add DB Driver',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: true,
closable:false,
modal:true,
shim: false,
frame: true,
// forceLayout: true,
items: add_db_driver_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
if( add_db_driver_FormPanel.getForm().isValid()){
add_db_driver_FormPanel.getForm().submit({
success: function(){
add_db_driver_Window.hide();
db_drivers_Store.load();
add_db_driver_FormPanel.getForm().reset();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
add_db_driver_Window.hide();
add_db_driver_FormPanel.getForm().reset();
} // cancel handler
}]
});
// DBDRIVER - ADD POP UP UI (END)
// DBDRIVER - EDIT POP UP UI (START)
var edit_db_driver_FormPanel = new Ext.FormPanel({
url: '../DataBaseDriversServelet?action=edit',
// url:'../DataBaseDriversServelet_edit',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
id: 'edit_db_driver_FormPanel',
items: [
{
fieldLabel: 'Type',
id: 'TYPE_edit_db_driver_FormPanel',
allowBlank: false,
name: 'TYPE',
width:190
},{
fieldLabel: 'Name',
id: 'NAME_edit_db_driver_FormPanel',
allowBlank: false,
name: 'NAME',
width:190
},{
fieldLabel: 'Address',
id: 'ADDRESS_edit_db_driver_FormPanel',
allowBlank: false,
name: 'ADDRESS',
width:190
},new Ext.form.NumberField ({
fieldLabel: 'Port',
id: 'PORT_edit_db_driver_FormPanel',
allowBlank: false,
name: 'PORT',
width:190
})
]
});
var recordToEdit;
var edit_db_driver_Window = new Ext.Window({
title: 'Edit DB Driver',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: edit_db_driver_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
var db_driver_id = recordToEdit.get("ID");
if(edit_db_driver_FormPanel.getForm().isValid()){
edit_db_driver_FormPanel.getForm().submit({
// url:'../DataBaseDriversServelet_edit',
url: '../DataBaseDriversServelet?action=edit',
waitMsg:'Saving Data...',
params:{
ID: db_driver_id
},
success: function(){
edit_db_driver_Window.hide();
db_drivers_Store.load();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
edit_db_driver_Window.hide();
edit_db_driver_FormPanel.getForm().reset();
} // cancel handler
}]
});
// DBDRIVER - EDIT POP UP UI (END)
// DBDRIVER - POP UP UI (END)
var db_driver_btn_panel = [{
id: 'db_driver_add_btn',
text: 'Add',
iconCls: 'adddb',
handler: (function(){
add_db_driver_Window.show();
}) // add handler function
}, {
text: 'Edit',
iconCls: 'edit',
handler: (function(){
var edit_selModel = Ext.getCmp("db_drivers_UPanel").getSelectionModel();
var selRecord;
if(edit_selModel.getSelected()== undefined){
Ext.message.msg('Notice','Select Database Driver first');
}else{
selRecord = edit_selModel.getSelected();
recordToEdit = selRecord;
Ext.getCmp("TYPE_edit_db_driver_FormPanel").setValue(recordToEdit.get("TYPE"));
Ext.getCmp("NAME_edit_db_driver_FormPanel").setValue(recordToEdit.get("NAME"));
Ext.getCmp("ADDRESS_edit_db_driver_FormPanel").setValue(recordToEdit.get("ADDRESS"));
Ext.getCmp("PORT_edit_db_driver_FormPanel").setValue(recordToEdit.get("PORT"));
edit_db_driver_Window.show();
} // end if
}) // edit handler function
},{
text: 'Delete',
iconCls: 'delete',
handler: function() {
//get currently selected record
var rec = Ext.getCmp('db_drivers_UPanel').getSelectionModel().getSelected();
//rec will be undefined if nothing is selected so check for this.
if(rec){
//open delete confirmation box
Ext.MessageBox.confirm('Delete Confirmation', 'Delete Driver?', function(btn)
{//check if the user selected 'yes'
if (btn == 'yes'){
//create ajax request to send delete requesdt to the servlete
Ext.Ajax.request({
//specify servlet url
//url : '../DataBaseDriversServelet_delete' ,
url: '../DataBaseDriversServelet?action=delete',
params : {
//D_ID = driver id, send through as param to the servlet
'D_ID': rec.data.ID
},
//use post
method: 'POST',
//method will run if server returns success message
success: function ( result, request ) {
// Ext.MessageBox.alert('Success','Post Deleted');
Ext.message.msg('Driver - Removed.', 'Driver has successfully been removed!');
//Ext.message.msg('Success','Driver Deleted');
db_drivers_Store.load();
},
//method will run if server returns failure message
failure: function ( result, request) {
Ext.MessageBox.alert('Failure','Driver Deletion Failed');
}
});//ajax request
}//if btn
});//confirm box
}else
{
Ext.message.msg('Notice','Select driver first');
}
} // function
}];
var db_drivers_UPanel = new Ext.Panel({
id: 'databaseDriversUtil-form',
labelAlign: 'left',
bodyStyle:'padding:5px',
frame: true,
boder: true,
width: 450,
title:"Database Drivers",
items:[{
xtype: 'grid',
id: 'db_drivers_UPanel',
tbar: db_driver_btn_panel,
ds: db_drivers_Store, // ds = datastore
cm: db_drivers_ColModel, // cm = column model
autoScroll:true,
height:220
}]
});
return db_drivers_UPanel;
}
// Database Drivers UI (End)
// Database Setup UI (Start)
Ext.Dyno.databaseUtil.databaseSetupUtilPanel = function(){
var db_setup_Store = new Ext.data.JsonStore({
//url: '../DataBaseSetupServelet',
url: '../DataBaseSetupServelet?action=show',
root: 'rows',
idProperty: 'ID',
fields: [{
name: 'ID',
type: 'int'
},{
name: 'TYPE',
type: 'string'
},{
name: 'DRIVERNAME',
type: 'string'
},{
name: 'CONNECTSTART',
type: 'string'
},{
name: 'DEFAULTPORT',
type: 'int'
}]
});
// this displays the data in the gird
db_setup_Store.load();
var db_setup_ColModel = new Ext.grid.ColumnModel([
{
header: "ID",
width: 70,
sortable: true,
locked:false,
hidden: true,
dataIndex: 'ID'
},{
header: "Type",
width: 70,
sortable: true,
dataIndex: 'TYPE'
},{
header: "Driver Name",
width: 150,
sortable: true,
dataIndex: 'DRIVERNAME'
},{
header: "Connect Start",
width: 100,
sortable: true,
dataIndex: 'CONNECTSTART'
},{
header: "Default Port",
width: 80,
sortable: true ,
dataIndex: 'DEFAULTPORT'
}
]);
// DBTYPE - POP UP UI (START)
// DBTYPE - ADD POP UP UI (START)
var add_db_type_FormPanel = new Ext.FormPanel({
//url:'../DataBaseSetupServelet_add',
url: '../DataBaseSetupServelet?action=add',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
items: [
{
fieldLabel: 'Type',
name: 'TYPE',
allowBlank: false,
width:190
},{
fieldLabel: 'Driver Name',
name: 'DRIVERNAME',
allowBlank: false,
width:190
},{
fieldLabel: 'Connect Start',
name: 'CONNECTSTART',
allowBlank: false,
width:190
},new Ext.form.NumberField ({
fieldLabel: 'Default Port',
name: 'DEFAULTPORT',
allowBlank: false,
width:190
})
]
});
// ADD
var add_db_type_Window = new Ext.Window({
title: 'Add DB Type',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
//get currently selected record
var rec = Ext.getCmp('db_setup_UPanel').getSelectionModel().getSelected();
//rec will be undefined if nothing is selected so check for this.
if(rec){
//open delete confirmation box
Ext.MessageBox.confirm('Delete Confirmation', 'Delete Setup?', function(btn)
{//check if the user selected 'yes'
if (btn == 'yes'){
//create ajax request to send delete requesdt to the servlete
Ext.Ajax.request({
//specify servlet url
// url : '../DataBaseSetupServelet_delete' ,
url: '../DataBaseSetupServelet?action=delete',
params : {
//D_ID = driver id, send through as param to the servlet
'ID': rec.data.ID
},
//use post
method: 'POST',
//method will run if server returns success message
success: function ( result, request ) {
//Ext.MessageBox.alert('Success','Post Deleted');
//Ext.message.msg('Success','Setup Deleted');
Ext.message.msg('Setup - Removed.', 'Setup has successfully been removed!');
db_setup_Store.load();
},
//method will run if server returns failure message
failure: function ( result, request) {
Ext.MessageBox.alert('Failure','Setup Deletion Failed');
}
});//ajax request
}//if btn
});//confirm box
}else
{
Ext.message.msg('Notice','Select setup first');
}
} // function
}];
var db_setup_UPanel = new Ext.Panel({
id: 'databaseSetupUtil-form',
labelAlign: 'left',
bodyStyle:'padding:5px',
frame: true,
boder: true,
width: 450,
title:"Database Setup",
items:[{
xtype: 'grid',
id:'db_setup_UPanel',
tbar: db_setup_btn_panel,
ds: db_setup_Store, // ds = datastore
cm: db_setup_ColModel, // cm = column model
autoScroll:true,
height:220
}]
});
return db_setup_UPanel;
}
var cat_config_Store = new Ext.data.JsonStore({
url: '../configureCatogoriesServelet?action=show',
root: 'rows',
idProperty: 'C_ID',
fields: [{
name: 'C_ID',
type: 'int'
},{
name: 'C_NAME',
type: 'string'
},{
name: 'C_DESCRIPTION',
type: 'string'
}]
});
// this displays the data in the gird
cat_config_Store.load();
var categoryGridTable = new Ext.grid.GridPanel({
region:'center',
//columnWidth: 0.70,
layout: 'fit',
ds: cat_config_Store,
//cm: colModel,
columns:[
{
header: "ID",
width: 70,
sortable: true,
locked:false,
hidden: true,
dataIndex: 'C_ID'
}, {
header: "Name",
width: 100,
sortable: true,
dataIndex: 'C_NAME'
}, {
header: "Description",
width: 300,
sortable: true,
dataIndex: 'C_DESCRIPTION'
}
],
frame:true,
height:250,
// width:500,
border:false
});
var cat_config_FormPanel = new Ext.FormPanel({
url: '../configureCatogoriesServelet',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
items: [
{
fieldLabel: 'Name',
name: 'C_NAME',
allowBlank: false,
maxLength: 256, // for validation
width:190
},{
fieldLabel: 'Description',
name: 'C_DESCRIPTION',
allowBlank: false,
maxLength: 256, // for validation
width:190
}] // items
}); // cat_config_FormPanel
var cat_config_Window = new Ext.Window({
//title: 'Add Category',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: cat_config_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
var form = cat_config_FormPanel.getForm();
if(form.isValid()){
form.submit({
url: '../configureCatogoriesServelet',
waitMsg:'Saving Data...',
params:{
action:categoryAddEditAction,
ID:chosenCategoryIdToEdit
},
success: function(){
cat_config_Window.hide();
cat_config_Store.load();
form.reset();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
cat_config_Window.hide();
cat_config_FormPanel.getForm().reset();
} // cancel handler
}]
});
var cat_conf_btn_panel = [{
text: 'Add',
iconCls: 'adddb',
handler: (function(){
cat_config_FormPanel.getForm().reset();
categoryAddEditAction = 'add';
cat_config_Window.setTitle('Add Category');
cat_config_Window.show();
}) // add handler function
},{
text: 'Edit',
iconCls: 'edit',
handler: function(){
var selModel = categoryGridTable.getSelectionModel();
var selRecord;
//updatepassword=true;
if(selModel.getSelected()== undefined){
Ext.MessageBox.alert('Notice','Select Catogry first');
}else{
selRecord = selModel.getSelected();
chosenCategoryIdToEdit = selRecord.get("C_ID");
categoryAddEditAction = "edit";
cat_config_Window.setTitle('Edit Category Configuration');
cat_config_Window.show();
cat_config_Window.hide();
cat_config_FormPanel.getForm().findField("C_NAME").setValue(selRecord.get("C_NAME"));
cat_config_FormPanel.getForm().findField("C_DESCRIPTION").setValue(selRecord.get("C_DESCRIPTION"));
cat_config_FormPanel.getForm().loadRecord(selRecord);
cat_config_Window.show();
}
} // edit handler function
},{
text: 'Delete',
iconCls: 'delete',
handler: function() {
var selModel = categoryGridTable.getSelectionModel();
var selRecord;
if(selModel.getSelected()== undefined){
Ext.MessageBox.alert('Notice','Select category first');
}else{
selRecord = selModel.getSelected();
var recordToDelete = selRecord;
var add_app_Window = new Ext.Window({
//title: 'Add Application',
width: 700,
height:250,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: applicationForm,
buttons: [{
text: 'Submit',
handler: function(){
if( applicationForm.getForm().isValid()){
applicationForm.getForm().submit({
url: '../ApplicationServelet',
waitMsg:'Saving Data...',
params:{
action:schedulerAppAddEditAction,
ID:chosenSchedulerAppIdToEdit
},
success: function(){
add_app_Window.hide();
AppList_Store.load();
applicationForm.getForm().reset();
},
},
fail: function(){
Ext.MessageBox.alert('Email Server', 'Multiple Mail Server is not Allowed.');
},
failure: function(result, request){
var obj = Ext.util.JSON.decode(request.response.responseText);
Ext.MessageBox.alert('Add Application Failed.', obj.reason);
}
});
}else{
Ext.MessageBox.alert('Applications', 'Could not Submit. Make sure all fields are valid.');
}
This is the javascript part which contains all the error messages , which contains all the error messages, the message i want to call if the Fail message, which says that Multiple Mail Server is not allowed
That's not valid HTML or Javascript. You need to remove the script from inside the opening <body> tag and place it inside <script> tags of its own.
out.println ("<html><body><script>alert('Hello World!');</script></body></html>");
You should however avoid printing out HTML from a Servlet and consider redirecting to an error.jsp instead. This would also allow you to collate all the validation errors and display them to the user in one go.
Try this
out.println("<html><body onload=\"alert('Hello World')\"></body></html>");

Categories