简体   繁体   中英

how to add a record to a database java servlet from extjs

Hi I have my database in PostgreSQL, im using extjs for servlet. I want to add new records in grid to my database but i dont know how to connect that from servlet. Is anyone can help me? ps: I should use doPost method but i dont know how can i do that with this. Here is my codes:

 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 : '&nbsp;'; } }, { 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); } } */ }] }); }); 

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

There are a few things you should read up on.

First your extjs store proxy needs a writer the extjs docs have a useful guide to get you started

Then you would need to create the endpoint in your java Servlet class to handle the http requests that the store would emit on save.

This new endpoint would then call the method/service you are using to write to the database, passing the appropriate information required into the call.

Then your servlet method would resond with an appropriate http code so that the client can indicate success/failure as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM