嗨我在PostgreSQL中有我的数据库,即使用extjs for servlet。我想在网格中添加新记录到我的数据库,但我不知道如何从servlet连接它。有人可以帮帮我吗? p.s:我应该使用doPost方法,但我不知道我怎么能这样做。这是我的代码:
Ext.define('Book.Person', {
extend : 'Ext.data.Model',
fields : ['ID', 'Username']
});
var store = Ext.create('Ext.data.Store', {
model : 'Book.Person',
autoLoad : true,
autoSync : true,
proxy : {
type : 'ajax',
url : 'Sheldon.xml',
reader : {
type : 'xml',
record : 'Item',
totalProperty : 'total'
}
},
data : [{
title : '',
manufacturer : '',
author : ''
}]
});
var inputForm = Ext.create('Ext.form.Panel', {
activeRecord : null,
iconCls : 'icon-user',
frame : true,
title : 'User -- All fields are required',
defaultType : 'textfield',
bodyPadding : 2,
fieldDefaults : {
anchor : '100%',
labelAlign : 'right'
},
items : [{
fieldLabel : 'ID',
name : 'ID',
allowBlank : false
}, {
fieldLabel : 'Username',
name : 'Username',
allowBlank : false
}
],
dockedItems : [{
xtype : 'toolbar',
dock : 'bottom',
ui : 'footer',
items : ['->', {
iconCls : 'icon-user-add',
text : 'Create',
scope : this,
handler : function() {
createFunction();
}
}, {
iconCls : 'icon-reset',
text : 'Reset',
scope : this,
handler : function() {
inputForm.getForm().reset();
}
}]
}]
});
var windowToShow = Ext.create('Ext.window.Window', {
title : 'New Book',
height : 200,
width : 400,
layout : 'fit',
items : inputForm
});
var createFunction = function() {
var form = inputForm.getForm();
if (form.isValid()) {
var tt = form.findField('ID').getValue();
var mf = form.findField('Username').getValue();
// inputForm.fireEvent('create', inputForm, form.getValues());
var newBook = new Book.Person({
ID : tt,
Username : mf
});
/*
* windowToShow.show(); rec, edit = this.editing; edit.cancelEdit();
*/
/*
* this.store.insert(0, newBook); edit.startEditByPosition({ row : 0,
* column : 1});
*/
store.add(newBook);
store.load();
form.reset();
}
windowToShow.hide();
};
var resetFunction = function() {
inputForm.getForm().reset();
};
Ext.define('Book.Form', {
extend : 'Ext.form.Panel',
alias : 'widget.Bookform',
requires : ['Ext.form.field.Text'],
initComponent : function() {
// Ext.apply(this, this.bookform);
this.callParent();
},
setActiveRecord : function(record) {
this.activeRecord = record;
if (record) {
this.down('#save').enable();
this.getForm().loadRecord(record);
} else {
this.down('#save').disable();
this.getForm().reset();
}
}
/*
* onSave: function(){ var active = this.activeRecord, form =
* this.getForm();
*
* if (!active) { return; } if (form.isValid()) {
* form.updateRecord(active); this.onReset(); } },
*/
});
Ext.define('Book.Grid', {
extend : 'Ext.grid.Panel',
alias : 'widget.Bookgrid',
requires : ['Ext.grid.plugin.CellEditing', 'Ext.form.field.Text',
'Ext.toolbar.TextItem'],
initComponent : function() {
this.editing = Ext.create('Ext.grid.plugin.CellEditing');
Ext.apply(this, {
iconCls : 'icon-grid',
frame : true,
plugins : [this.editing],
dockedItems : [{
xtype : 'toolbar',
items : [{
iconCls : 'icon-add',
text : 'Add',
scope : this,
handler : this.onAddClick
}, {
iconCls : 'icon-delete',
text : 'Delete',
disabled : true,
itemId : 'delete',
scope : this,
handler : this.onDeleteClick
}]
}, {
weight : 2,
xtype : 'toolbar',
dock : 'bottom',
items : {
xtype : 'tbtext',
text : '<b>@Sebahat&Volkan</b>'
}
}, {
weight : 1,
xtype : 'toolbar',
dock : 'bottom',
ui : 'footer',
items : ['->', {
iconCls : 'icon-save',
text : 'Sync',
scope : this,
handler : this.onSync
}]
}],
columns : [{
text : '',
width : 40,
sortable : true,
resizable : false,
draggable : false,
hideable : false,
menuDisabled : true,
dataIndex : 'id',
renderer : function(value) {
return Ext.isNumber(value)
? value
: ' ';
}
}, {
header : 'ID',
width : 100,
sortable : true,
dataIndex : 'ID',
field : {
type : 'textfield'
}
}, {
header : 'Username',
width : 100,
sortable : true,
dataIndex : 'Username',
field : {
type : 'textfield'
}
}]
});
this.callParent();
this.getSelectionModel().on('selectionchange',
this.onSelectChange, this);
},
onSelectChange : function(selModel, selections) {
this.down('#delete').setDisabled(selections.length === 0);
},
onSync : function() {
this.store.sync();
},
onDeleteClick : function() {
var selection = this.getView().getSelectionModel()
.getSelection()[0];
if (selection) {
this.store.remove(selection);
}
},
onAddClick : function() {
windowToShow.show();
rec, edit = this.editing;
edit.cancelEdit();
this.store.insert(4, rec);
edit.startEditByPosition({
row : store.getTotalCount()+1,
column : 1
});
}
});
var rec = new Book.Person({
ID : '',
Username : ''
});
Ext.require(['Ext.data.*', 'Ext.tip.QuickTipManager', 'Ext.window.MessageBox']);
Ext.onReady(function() {
Ext.tip.QuickTipManager.init();
Ext.create('Ext.button.Button', {
margin : '0 0 20 20',
text : 'Reset sample database back to initial state',
tooltip : 'The sample database is stored in the session, including any changes you make. Click this button to reset the sample database to the initial state',
handler : function() {
Ext.getBody().mask('Resetting...');
Ext.Ajax.request({
url : 'app.php/example/reset',
callback : function(options, success, response) {
Ext.getBody().unmask();
var didReset = true, o;
if (success) {
try {
o = Ext.decode(response.responseText);
didReset = o.success === true;
} catch (e) {
didReset = false;
}
} else {
didReset = false;
}
if (didReset) {
store.load();
main.down('#form').setActiveRecord(null);
Ext.example.msg('Reset', 'Reset successful');
} else {
Ext.MessageBox.alert('Error',
'Unable to reset example database');
}
}
});
}
});
var main = Ext.create('Ext.container.Container', {
padding : '0 0 0 20',
width : 500,
height : Ext.themeName === 'neptune' ? 700 : 650,
renderTo : document.body,
layout : {
type : 'vbox',
align : 'stretch'
},
items : [{
// itemId: 'form',
xtype : 'Bookform',
manageHeight : false,
margin : '0 0 10 0',
listeners : {
create : function(form, data) {
store.insert(0, data);
}
}
}, {
// itemId: 'grid',
xtype : 'Bookgrid',
title : 'User List',
flex : 1,
store : store
/*
* listeners : { selectionchange :
* function(selModel, selected) {
* main.child('#form') .setActiveRecord(selected[0] ||
* null); } }
*/
}]
});
});
&#13;
package net.davon;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Test_DB
*/
@WebServlet("/Sheldon.xml")
public class OrnekTest extends HttpServlet {
private static final long serialVersionUID = 1L;
private PrintWriter pw;
private Connection conn;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
String connectionString = "jdbc:postgresql://localhost:5432/Davon_User"; // +
// "databaseName=Davon_User;user=postgres;password=volkan";
String queryString = "select * from dvn_user";
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(connectionString, "postgres",
"volkan");
if (conn == null) {
System.out.println("CANNOT CONNECT DATABASE!");
System.exit(0);
}
statement = conn.createStatement();
resultSet = statement.executeQuery(queryString);
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\"?>\n").append("<Items>\n");
while (resultSet.next()) {
xml.append("\t<Item>\n");
String user_id = resultSet.getString("id");
String username = resultSet.getString("user_name");
xml.append("\t\t<ID>" + user_id + "</ID>\n");
xml.append("\t\t<Username>" + username + "</Username>\n");
xml.append("\t</Item>\n");
}
xml.append("</Items>\n");
response.getWriter().println(xml.toString());
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
}
}
&#13;
答案 0 :(得分:0)
您应该阅读一些内容。
首先,你的extjs商店代理需要一个作家the extjs docs have a useful guide to get you started
然后,您需要在java Servlet类中创建端点,以处理存储在保存时将发出的http请求。
然后,这个新端点将调用您正在使用的方法/服务写入数据库,并将所需的适当信息传递给调用。
然后您的servlet方法将使用适当的http代码重新生成,以便客户端可以适当地指示成功/失败。