当前位置: 代码迷 >> JavaScript >> extjs+struts(JSON)对报表的增删查改
  详细解决方案

extjs+struts(JSON)对报表的增删查改

热度:260   发布时间:2012-10-09 10:21:45.0
extjs+struts(JSON)对表格的增删查改

html代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
<link rel="stylesheet" href="ext/resources/css/ext-all.css" />
<script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="ext/ext-all.js"></script>
<script type="text/javascript" src="ext/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="js/edit.js"></script>
</head>
<body>

</body>
</html>

?edit.js代码:

	function editRecord() {
	}
	
	function deleteRecord() {
		var grid = Ext.getCmp("table");
		var sm = grid.getSelectionModel();
		var sel = sm.getSelections();
		if(sm.hasSelection()){
			Ext.MessageBox.show({
				title:"删除用户记录",
				buttons:Ext.MessageBox.YESNOCANCEL,
				msg:"您确定要删除"+sel.length+"个用户吗?",
				fn:function(btn){
					if(btn=="yes"){
			
						var ids = "[";
						for(var i=0;i<sel.length;i++){
							var record = sel[i];
							ids+=record.get("id")+",";
						}
						ids = ids.substring(0,ids.length-1)+"]";
						alert(ids);
						var conn = new Ext.data.Connection();
						conn.request({
							url:"http://localhost:8686/myjob1/delete",
							params:{
								action:"delete",
								ids:ids
							},
							success:function(resp,opt){
								for(var i=0;i<sel.length;i++){
									var record = sel[i];
									grid.getStore().remove(record);
								}
							},
							failure:function(resp,opt){
								Ext.MessageBox.alert("错误","不能删除用户信息!");
							}
						});
					}
				}
			});
		}
		//grid.getStore().reload(null);
	}
	
	function addRecord() {
		var ds_model = Ext.data.Record.create([
			"id",
			"name",
			"password",
			"sex",
			"age"
		]);
		var grid = Ext.getCmp("table");
		var page = grid.getBottomToolbar();
		//pageCount = getRowSize()/getPageSize() + ((getRowSize()%getPageSize())==0?0:1);
		var store = grid.getStore();
		var row = store.getTotalCount();
		var pageSize = store.getCount();
		var pageCount = Math.ceil(row/pageSize);
		alert(row+"--"+pageSize+"--"+pageCount);
		page.changePage(pageCount);
		var conn = new Ext.data.Connection();
		conn.request({
			url:"http://localhost:8686/myjob1/add",
			method:"post",
			params:{
				name:"NewUser"
			},
			success:function(resp,opt){
				var insert_id = Ext.util.JSON.decode(resp.responseText).id;
				grid.getStore().insert(0,new ds_model({
					id:insert_id,
					name:"NewUser",
					password:"",
					sex:"true",
					age:0
				}));
				grid.startEditing(0,0);
			},
			failure:function(resp,opt){
				alert(resp+">>>>>>>>"+opt);
				Ext.MessageBox.alert("","不能插入新用户!");
			}
		});
		//grid.getStore().reload(null);
	}
	
	function rendererSex(val) {
		if (val == true) 
			return "<h4 style='color:green'>男</h4>";
		else 
			return "<h4 style='color:red'>女</h4>";
			
	}
	function selectAll(){
		var sm = Ext.getCmp("table").getSelectionModel();
		sm.selectAll();
	}
	function disSelect(){
		//Ext.MessageBox.alert("","你点击了编辑");
		var grid = Ext.getCmp("table");
		var sm = Ext.getCmp("table").getSelectionModel();
		for(var i=grid.getView().getRows().length-1;i>=0;i--){
	       if(sm.isSelected(i)){
	    	   sm.deselectRow(i);
	       }else{
	    	   sm.selectRows([i],true);   // rsm.selectRow(i,true); 也可以
	       }
		}
	}
	function saveRecord(){
		alert("save");
		var grid = Ext.getCmp("table");
		
	}
Ext.onReady(function(){
	var idEditor = new Ext.form.TextField();
	var nameEditor = new Ext.form.TextField();
	var passwordEditor = new Ext.form.TextField();
	var sexEditor = new Ext.form.TextField();
	var ageEditor = new Ext.form.TextField();
	var sm = new Ext.grid.CheckboxSelectionModel();
	var cm = new Ext.grid.ColumnModel([
		new Ext.grid.RowNumberer(),
		sm,
		{header:"id", dataIndex:"id", width: 120,sortable: true,editor:idEditor},
		{header:"用户名", dataIndex:"name", width: 120,sortable: true,editor:nameEditor},
		{header:"口令", dataIndex:"password", width: 120,sortable: true,editor:passwordEditor},
		{header:"性别", dataIndex:"sex", width: 80,editor:sexEditor},
		{header:"年龄", dataIndex:"age", width: 120,sortable: true,editor:ageEditor}
	]);
	
	var store = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url:"http://localhost:8686/myjob1/list"}),
		reader: new Ext.data.JsonReader({totalProperty:'total', root:'list'}, [
		{name: 'id'},
		{name: 'name'},
		{name: 'password'},
		{name: 'sex'},
		{name: 'age'}
		])
	});
	store.load({params:{start:0, limit:20}});
	
	var grid = new Ext.grid.EditorGridPanel({
		renderTo:Ext.getBody(),
		title:"user info",
		height:650,
		id:"table",
		store:store,
		autoSizeColumns: true,
		cm:cm,
		sm:sm,
		tbar: new Ext.Toolbar({
						items:[
								{id:'selectAll',text:'全选', handler:selectAll},
								{id:'disSelect',text:'反选', handler:disSelect},
								{id:'delete',text:'删除', handler:deleteRecord},
								{id:'add',text:"添加",handler:addRecord},
								{id:'edit',text:"保存",handler:saveRecord}
							]
				}),
		bbar: new Ext.PagingToolbar({
			pageSize: 20,
			store: store,
			displayInfo: true,
			displayMsg: '显示第{0}条到第{1}记录,一共{2}条',
			emptyMsg: '没有记录'
		}),
		listeners:{
			afteredit:function(e){
				alert(e.record.get("id"));
				var conn = new Ext.data.Connection();
				conn.request({
					url:"update",
					params:{
						id:e.record.get("id"),
						field:e.field,
						value:e.value
					},
					success:function(resp,opt){
						e.record.commit();
					},
					failure:function(resp,opt){
						e.record.reject();
					}
				});
					
			}
		}
	});
	
});

?struts.xml代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<constant name="struts.objectFactory" value="spring" />
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<package name="user" namespace="/" extends="json-default">
		<action name="login" class="userAction" method="login">
			<result name="login">
				/login.jsp
			</result>
			<result name="success" type="redirect">
				/welcome.jsp
			</result>
		</action>
		<action name="loginJSON" class="userAction" method="loginJSON">
			<result type="json"/>
		</action>
		<action name="list" class="userAction" method="list">
			<result type="json"/>
		</action>
		<action name="delete" class="userAction" method="delete">
			<result type="json"/>
		</action>
		<action name="add" class="userAction" method="add">
			<result type="json"/>
		</action>
		<action name="update" class="userAction" method="update">
			<result type="json"/>
		</action>
	</package>
</struts>    

?UserAction.java代码

package action;

import java.util.Arrays;
import java.util.List;

import org.apache.struts2.json.annotations.JSON;

import service.UserService;
import util.Pager;
import mode.User;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{
	private User user;
	private UserService service;
	private List<User> list;
	private int limit;
	private int start;
	private int total;
	private boolean success = true;
	private String ids;
	
	private String id;
	private String name;
	private String password;
	private boolean sex;
	private int age;
	
	private String field;
	private String value;
	
	
	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isSex() {
		return sex;
	}

	public void setSex(boolean sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	@JSON(serialize=false)
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
	@JSON(serialize=false)
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}
	@JSON(serialize=false)
	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}
	public List<User> getList() {
		return list;
	}

	public void setList(List<User> list) {
		this.list = list;
	}
	@JSON(serialize=false)
	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}
	@JSON(serialize=false)
	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	public String login(){
		if(service.login(user.getName(), user.getPassword())){
			return SUCCESS;
		}
		return LOGIN;
	}
	public String loginJSON(){
		if(service.login(name, password)){
			success = true;
		}else {
			success = false;
		}
		return SUCCESS;
	}
	/*
	 * 1	1	5
	 * 2	6	10
	 * size*pagenow-pagesize+1=start
	 * pagenow = start+pagesize-1/size
	 */
	public String list(){
		System.out.println(start+" ------------------------    "+limit);
		/*0 20
		 * 
		 */
		int now = (start+1+limit-1)/limit;
		System.out.println(now);
		Pager pager = new Pager(limit, -1,now);
		list = service.list(pager);
		total = pager.getRowSize();
		return SUCCESS;
	}
	public String delete(){
		System.out.println(ids);
		String[] idArr = ids.substring(1,ids.length()-1).split(",");
		System.out.println(Arrays.toString(idArr)+"  "+idArr.length);
		service.deleteUserByIdArray(idArr);
		
		success=true;
		return SUCCESS;
	}
	public String add(){
		if(user==null){
			user = new User();
			user.setName(name);
			user.setAge(age);
			user.setPassword(password);
			user.setSex(sex);
			id = service.regsiter(user);
			success=true;
			System.out.println("add user-----");
		}
		
		return SUCCESS;
	}
	public String update(){
		if(id.startsWith("ext")){
			User user = new User();
			if(field.equals("name")){
				user.setName(value);
			}else if(field.equals("password")) {
				user.setPassword(value);
			}else if(field.equals("sex")){
				user.setSex(Boolean.parseBoolean(value));
			}else if(field.equals("age")){
				user.setAge(Integer.parseInt(value));
			}else{
				
			}
			service.regsiter(user);
		}else{
			System.out.println("id:"+id+";field:"+field+";value:"+value);
			User user = service.getUserById(id);
			if(field.equals("name")){
				user.setName(value);
			}else if(field.equals("password")) {
				user.setPassword(value);
			}else if(field.equals("sex")){
				user.setSex(Boolean.parseBoolean(value));
			}else if(field.equals("age")){
				user.setAge(Integer.parseInt(value));
			}else{
				
			}
			service.updateUserById(user);
		}
		success=true;
		return SUCCESS;
	}
}
?
  相关解决方案