日期:2014-05-20  浏览次数:21158 次

Spring Framework 3.0.5+Spring Security 3.0.5+ mybatis 3.0.5+ Struts 2.2.3整合代码

简单的权限控制,密码使用sha加密

?

?

?

?

?

web.xml

?

?

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		<!-- default: /WEB-INF/applicationContext.xml -->
	</listener>
	<!-- -->
	
	
	<!-- spring security  -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            classpath*:applicationContext*.xml  
        </param-value>  
    </context-param> 
    
    <filter>  
        <filter-name>springSecurityFilterChain</filter-name>  
        <filter-class>  
            org.springframework.web.filter.DelegatingFilterProxy  
        </filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>springSecurityFilterChain</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <listener>  
        <listener-class>  
            org.springframework.web.context.ContextLoaderListener  
        </listener-class>  
    </listener>  
	
	
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf8</param-value>
		</init-param>
	</filter>
	
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 
	<filter>
		<filter-name>openSessionInView</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>openSessionInView</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	 -->
	<filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

?

applicationContext.xml

?

?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
   			http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   			http://www.springframework.org/schema/context 
   			http://www.springframework.org/schema/context/spring-context-2.5.xsd
   			http://www.springframework.org/schema/jee 
   			http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
   			http://www.springframework.org/schema/tx 
   			http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<bean
		class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:jdbc.properties</value>
		</property>
	</bean>
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url"
			value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<!--
		配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了
	-->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />
	<!-- myBatis文件 -->

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis.xml" />
		<property name="mapperLocations" value="classpath*:com/glen/model/*.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
<!-- 
	<bean id="accountDao" class="com.glen.dao.AccountDao">
		<property name="sessionFactory" ref="sqlSessionFactory" />
	</bean>

	<bean id="accountService" class="com.glen.service.AccountService">
		<property name="accountDao" ref="accountDao" />
	</bean>
 -->
	<context:annotation-config />
	<context:component-scan base-package="com.glen" />


</beans>

?

?

applicationContext-security.xml

?

?

?

?

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/security  
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<!--
		auto-config = true 则使用from-login. 如果不使用该属性 则默认为http-basic(没有session).
		access-denied-page:出错后跳转到的错误页面;
	-->
	<http auto-config="true" access-denied-page="/common/403.jsp">
		<!--
			intercept-url:拦截器,可以设定哪些路径需要哪些权限来访问. filters=none 不使用过滤,也可以理解为忽略
		-->
		<intercept-url pattern="/index.jsp" access="ROLE_USER,ROLE_ADMIN" />
		<intercept-url pattern="/login.jsp" filters="none" />
		<intercept-url pattern="/common/**" filters="none" />
		<intercept-url pattern="/script/**" filters="none" />
		<intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
		<intercept-url pattern="/user.jsp" access="ROLE_USER" />

		<!-- session-management是针对session的管理. 这里可以不配置. 如有需求可以配置. -->
		<!--
			id登陆唯一. 后登陆的账号会挤掉第一次登陆的账号 error-if-maximum-exceeded="true" 禁止2次登陆;
			session-fixation-protection="none" 防止伪造sessionid攻击.
			用户登录成功后会销毁用户当前的session. 创建新的session,并把用户信息复制到新session中.
		-->
		<session-management session-fixation-protection="none">
			<concurrency-control />
		</session-management>

		<!--
			login-page:默认指定的登录页面. authentication-failure-url:出错后跳转页面.
			default-target-url:成功登陆后跳转页面
		-->
		<form-login login-page="/login.jsp"
			authentication-failure-url="/login.jsp" default-target-url="/index.jsp" />
		<!-- logout-success-url:成功注销后跳转到的页面; -->
		<logout logout-success-url="/login.jsp" />
		<http-basic />

	</http>




	<!-- 权限管理操作 -->
	<authentication-manager>
		<authentication-provider>
			
			<!-- 使用固定的用户名和密码及权限来做验证.    -->
			<!--
				<user-service> <user name="admin" password="admin"
				authorities="ROLE_USER, ROLE_ADMIN" /> <user name="user"
				password="user" authorities="ROLE_USER" /> </user-service>
			-->

			
			<jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="select username,password,enabled
                                        from account
                                        where username=?"
				authorities-by-username-query="select username,authority
                                        from authorities
                                        where username=?" />
			<password-encoder hash="sha"/>

		</authentication-provider>
	</authentication-manager>
	<!--
		<beans:bean id="userDetailsServiceImpl"
		class="com.demo.test.service.impl.UserDetailsServiceImpl" />
	-->



</beans:beans>  

?

?

mybatis.xml?

?

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>




</configuration>

?

struts.xml

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.i18n.encoding" value="UTF-8" />

	<package name="User" extends="json-default">  
       		<action name="user" class="com.glen.action.AccountAction">  
           		<result type="json" />   
        	</action> 
    	</package> 
</struts>

?

account-mapper.xml

?

?

?

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="account">

 <!-- 
 <select id="getList" parameterType="com.glen.model.Account" resultType="list" resultMap="accountMap.accountResultMap">
   select * from account where username like '%' #{username} '%'
 </select>
  -->
 <select id="getAllAccount" resultType="list" resultMap="accountMap.accountResultMap">
   select * from account
 </select>
  
 
 <!-- accountResultMap是account-resultmap.xml中定义的resultmap -->
 <select id="get" parameterType="com.glen.model.Account" resultType="com.glen.model.Account" resultMap="accountMap.accountResultMap">
  <![CDATA[
   select * from account where id = #{id}
        ]]>
 </select>
 
 
 <!-- 自动生成id策略 -->
 <insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.glen.model.Account">
  insert into account(id, username, password)
  values(#{id,jdbcType=BIGINT}, #{username}, sha(#{password}))
<!--将最后插入的逐渐返回到java对象-->
  <selectKey resultType="int" keyProperty="id">
   SELECT LAST_INSERT_ID()
  </selectKey>
  
 </insert>
  
 <update id="edit" parameterType="com.glen.model.Account">
  update account set
  username = #{username},
  password = #{password}
  where id = #{id}
 </update>
 
 <delete id="remove" parameterType="com.glen.model.Account">
  delete from account where id = #{id}
 </delete>
  
</mapper> 

?

account-resultMap.xml

?

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="accountMap">

    <resultMap type="com.glen.model.Account" id="accountResultMap">

       <id property="id" column="id"/>

       <result property="username" column="username"/>

       <result property="password" column="password"/>
       
		<result property="enabled" column="enabled"/>

    </resultMap>

</mapper>

?Account.java

?

package com.glen.model;

import java.io.Serializable;

public class Account implements Serializable {

	private static final long serialVersionUID = -7970848646314840509L;

	private Integer id;
	private String username;
	private String password;
	private int enabled;
	public Account() {
		super();
	}


	public Integer getId() {
		return id;
	}


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



	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

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


	public int getEnabled() {
		return enabled;
	}


	public void setEnabled(int enabled) {
		this.enabled = enabled;
	}

	
	

}

?AccountDao.java

?

package com.glen.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import com.glen.model.Account;
@Repository
public class AccountDao {
	
	@Resource
	private SqlSessionFactory sessionFactory;

	public SqlSessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SqlSessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public int insert(Account account) {

		SqlSession session = sessionFactory.openSession();
		return session.insert("account.add", account);
	}
	public void remove(Account account) {

		SqlSession session = sessionFactory.openSession();
		 session.delete("account.remove", account);
	}
	public Account getAccountById(Account account) {

		SqlSession session = sessionFactory.openSession();
		Account accountFromDb = (Account) session.selectOne("account.get",
				account);
		return accountFromDb;
	}
	@SuppressWarnings("unchecked")
	public List<Account> getAllAccount(){
		SqlSession session = sessionFactory.openSession();
		List<Account> accountFromDb = (List<Account>) session.selectList("account.getAllAccount");
		return accountFromDb;
		
	}

}

?

AccountService.java

?

package com.glen.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.glen.dao.AccountDao;
import com.glen.model.Account;
@Repository
public class AccountService {
	@Resource
	private AccountDao  accountDao;

	
	
	public int insertAccount(Account account) {
	  
		return accountDao.insert(account);
		
	}
	 
	public int remove(String removeNumbers) {
		String arrs[] = removeNumbers.split("\\|");
		for (String string : arrs) {
			System.out.println(string);
			Account account = new Account();
			account.setId(Integer.parseInt(string));
			accountDao.remove(account);
		}
		 
		 return arrs.length;
		 
	}
	 
	
	public Account getAccountById(Account account) {
	  
		return accountDao.getAccountById(account);
	}
	public List<Account> getAllAccount() {
		  
		return accountDao.getAllAccount();
	}
	public AccountDao getAccountDao() {
		return accountDao;
	}

	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	
}

?

AccountAction.java

?

package com.glen.action;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;

import com.glen.model.Account;
import com.glen.service.AccountService;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@Component
public class AccountAction extends ActionSupport{
	
	@Resource
	private AccountService accountService;
	private List<Account> list;
	
	private HttpServletResponse response ;
	private String removeNumbers;
	private Account account;
	private String level;
	@Override
	public String execute() throws Exception  {
		// TODO Auto-generated method stub
		response = ServletActionContext.getResponse();
		
		list = accountService.getAllAccount();
	
		String jsonStr="";
		for (Account account2 : list) {
			
				JSONObject jo = JSONObject.fromObject(account2);
				jsonStr+=","+ jo.toString();  
			
		}
		jsonStr = jsonStr.substring(1,jsonStr.length());
		try {  
            // 返回成功标识  
            response.getWriter().println(jsonStr);  
            response.getWriter().flush();  
            System.out.println("haha");
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                response.getWriter().close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
  
        return null;  
		
	}
	
	
	
	public String addUser() throws Exception{
		
		response = ServletActionContext.getResponse();
		account.setEnabled(1);
		accountService.insertAccount(account);
		
		try {  
            // 返回成功标识  
            response.getWriter().println("{success:true,userID:"+account.getId()+"}");  
            response.getWriter().flush();  
            System.out.println("haha");
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                response.getWriter().close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
		
		return null;
		
	}
	
	
	public String removes(){
		System.out.println(removeNumbers);
		response = ServletActionContext.getResponse();
		
		int count = accountService.remove(removeNumbers);
	
		try {  
            // 返回成功标识  
            response.getWriter().println(count);  
            response.getWriter().flush();  
            System.out.println("haha");
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                response.getWriter().close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
		
		return null;
	}
	
	
	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public AccountService getAccountService() {
		return accountService;
	}
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	public List<Account> getList() {
		return list;
	}

	public void setList(List<Account> list) {
		this.list = list;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public String getRemoveNumbers() {
		return removeNumbers;
	}

	public void setRemoveNumbers(String removeNumbers) {
		this.removeNumbers = removeNumbers;
	}

	public String getLevel() {
		return level;
	}

	public void setLevel(String level) {
		this.level = level;
	}

}

?login.js

?

/**
 * @author joo
 */

Ext.require( [ 'Ext.form.*', 'Ext.window.*' ])

Ext.onReady(function() {

	var form = Ext.create('Ext.form.Panel', {
		border : false,
		url : 'j_spring_security_check',
		method : 'post',
		fieldDefaults : {
			labelWidth : 50
		},
		bodyPadding : '30 60 10 60',
		items : [ {
			id:'loginUsername',
			xtype : 'textfield',
			fieldLabel : '用户名',
			name : 'j_username',
			anchor : '100%',
			shadow : true
		}, {
			xtype : 'textfield',
			id:'loginPassword',
			fieldLabel : '密码',
			name : 'j_password',
			anchor : '100%',
			padding : '20 0 0 0'

		} ]

	})

	var win = Ext.create('Ext.window.Window', {
		title : 'Resize Me',
		width : 400,
		height : 200,
		layout : 'fit',
		x:500,
		y:200,
		plain : true,
		items : form,
		buttons : [ {
			text : '登陸',
			handler : function() {
				var username = Ext.getCmp('loginUsername').value;
				var password = Ext.getCmp('loginPassword').value;
				$('#bestLoginUsername').val(username);
				$('#bestLoginPassword').val(password);
				$('#submitForm').submit();
		}
		}, {
			text : '取消'
		} ]
	});

	win.show();
});

?login.jsp

?

?

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	 -->
	 <link rel="stylesheet" type="text/css" href="ext-4.0/resources/css/ext-all.css" />
    	<link rel="stylesheet" type="text/css" href="ext-4.0/examples/shared/example.css" />
    	<script type="text/javascript" src="ext-4.0/bootstrap.js"></script>
    	
  <script type="text/javascript" src="jquery-1.4.1.js"></script>
		<script type="text/javascript" src="login.js" charset="utf-8"></script>
		
  </head>
  
  <body>
  <div align="center" style="padding-top: 200px;padding-left:100px">
	<form id="submitForm" action="<%=path %>/j_spring_security_check" method="post">  
        USERNAME:<input type="text" name="j_username" id="bestLoginUsername" value="" /><br/>  
        PASSWORD:<input type="password" name="j_password" id="bestLoginPassword" value="" /><br/>   
    </form> 
    </div> 
  </body>
</html>
?

?

user.js

?

/**
 * @author joo
 */
Ext.require([
	'Ext.dd.*',
	'Ext.data.*',
	'Ext.grid.*',
	'Ext.ModelManager.*'

])

Ext.define('DataObject',{
	extend:'Ext.data.Model',
	fields:['id','username','password']
});
function strToJson(str){   
    var json = eval('(' + str + ')');   
    return json;   
}  
var auth ;

function getGrid(firstGridStore){
	var Levelstates = Ext.create('Ext.data.Store', {
        fields: ['level', 'value'],
        data: [{
            "level": "ROLE_USER",
            "value": "ROLE_USER"
        }, {
            "level": "ROLE_ADMIN",
            "value": "ROLE_ADMIN"
        } // ...
]
    });
	var columns = [
		       		{text:'用户名',flex:1,sortable:true,dataIndex:'username'},
		       		{text:'密码',winth:70,sortable:true,dataIndex:'password'}
		       	]
		       	
		       	firstGrid = Ext.create('Ext.grid.Panel',{
		       		
		       		multiSelect:true,
		       		viewConfig:{
		       			plugins:{
		       				ptype:'gridviewdragdrop',
		       				dragGroup:'firstGridDDGroup',
		       				dropGroup:'secondGridDDGroup'
		       			},
		       			listeners: {
		                       drop: function(node, data, dropRec, dropPosition) {
		       					
		                           var dropOn = dropRec ? ' ' + dropPosition + ' ' + dropRec.get('name') : ' on empty view';
		                           Ext.example.msg("Drag from right to left", 'Dropped ' + data.records[0].get('name') + dropOn);
		                           
		                       }
		                   }
		       			
		       		},
		       		store:firstGridStore,
		       		columns:columns,
		       		title:'用户列表',
		       		stripeRows:true,
		       		margins:'0 4 0 0'
		       	})
		       	
		       	
		       	var secondGridStore = Ext.create('Ext.data.Store',{
		       		model:DataObject
		       	})
		       	
		       	secondGrid = Ext.create('Ext.grid.Panel',{
		       		
		       		viewConfig:{
		       			plugins:{
		       				ptype:'gridviewdragdrop',
		       				dragGroup:'secondGridDDGroup',
		       				dropGroup:'firstGridDDGroup'
		       			},
		       			listeners: {
		                       drop: function(node, data, dropRec, dropPosition) {
		                           var dropOn = dropRec ? ' ' + dropPosition + ' ' + dropRec.get('name') : ' on empty view';
		                           Ext.example.msg("Drag from left to right", 'Dropped ' + data.records[0].get('name') + dropOn);
		                       }
		                   }
		       		},
		       		store:secondGridStore,
		       		stripeRows:true,
		       		columns:columns,
		       		title:'删除列表'
		       		
		       	})
		       	
		       	
		       	
		       	var displayPanel = Ext.create('Ext.Panel',{
		       		
		       		width:650,
		       		height:300,
		       		layout:{
		       			type:'hbox',
		       			align:'stretch',
		       			padding:5
		       		},
		       		defaults:{flex:1},
		       		items:[firstGrid,secondGrid],
		       		renderTo:'panel',
		       		dockedItems:{
		       			xtype:'toolbar',
		       			dock:'bottom',
		       			items:[{
		       				text:'添加',
		       				handler:function(){
		       					if(auth=='[ROLE_ADMIN]')
		       						win.show();
		       					if(auth=='[ROLE_USER]')
		       						Ext.Msg.alert('用户','您没有权限')
		       					
		       				}
		       			},'->',{
		       				text:'删除',
		       				handler:function(){
		       				
	       					if(auth=='[ROLE_USER]'){
	       						Ext.Msg.alert('用户','您没有权限')
	       						return;
	       					}
	       						
		       					var store = (secondGrid.getStore());
		       					if(store.getCount()<=0){
		       						Ext.Msg.alert('消息', '请拖动数据到删除列表..');  
		       						return
		       					}
		       					var val = "";
		       					for(var i=0;i<store.getCount();i++){
		       						val += "|"+(store.getAt(i).get('id'))
		       					}
		       					val=val.substring(1, val.length);
		       					Ext.Ajax.request({

		       					   url: 'user!removes.action',

		       					   success:function(response,opts){
		       							
		       						Ext.Msg.alert('消息', '删除成功:共删除了'+response.responseText+'条内容');
		       							secondGridStore.removeAll()
		       						},

		       					   failure:function(response,opts){
		       							
		       							Ext.Msg.alert('消息', '删除失败');
		       						},
		       						
		       					   params:{removeNumbers:val}

		       					});
		       					//;
		       				}
		       			}]
		       		}
		       		
		       	})
		       	
		       	
		       	
		       	var addUserForm = Ext.create('Ext.form.Panel',{
		       		border:false,
		       		fieldDefaults:{
		       			labelWidth:50
		       		},
		       		bodyPadding:'30 60 10 60',
		       		items:[{
		       				xtype:'textfield',
		       				fieldLabel:'姓名',
		       				name:'account.username',
		       				anchor:'100%', 
		       				shadow :true,
		       				id:'username',
		       			},{
		       				xtype:'textfield',
		       				fieldLabel:'密碼',
		       				name:'account.password',
		       				anchor:'100%' ,
		       				padding:'20 0 0 0',
		       				id:'password'
		       			}
		       			]

		       	})
		       	
		       	var win = Ext.create('Ext.window.Window', {
		               title: 'Resize Me',
		               width: 400,
		               height:300,
		               layout: 'fit',
		               plain: true,
		       		items:addUserForm,
		               buttons: [{
		                   text: '添加',
		       			handler:function(){
		       				var store = firstGrid.getStore();
		       				//var loginForm = Ext.getCmp('login-form').form;   
		       				addUserForm.form.doAction('submit', {    
		       	                    url:'user!addUser.action',    
		       	                    method:'POST',                          
		       	                    waitMsg:'正在添加...',    
		       	                    timeout:10000,//10秒超时,    
		       	                    //params:loginForm.getValues(),  
		       	                    success:function(form, action){    
		       	            			//alert(action.result.userID); 
		       	            			var user = Ext.ModelManager.create({
		    		          			username : Ext.getCmp('username').value,
		    		          			password  : Ext.getCmp('password').value,
		    		          			id  : action.result.userID,
		    		       				}, 'DataObject');
		    		       				store.insert(store.getCount(),user);
		       	                    },    
		       	                    failure:function(form, action){    
		       	                        alert('添加失败');    
		       	                    }    
		       	                });    
		       				
		       				
		       				
		       				
		       				win.hide();
		       			}
		               },{
		                   text: '取消',
		       			handler:function(){
		       				win.hide()
		       			}
		               }]
		           });
	
}

Ext.onReady(function(){

	//您的权限为
	auth = $('#authHidden').val();
	if(auth=='[ROLE_ADMIN]')
		Ext.Msg.alert('管理员','您的权限为管理员')
	if(auth=='[ROLE_USER]')
		Ext.Msg.alert('用户','您的权限为普通用户')
	Ext.Ajax.request({

		   url: 'user.action',

		   success:function(response,opts){
				var data =  ('['+response.responseText+']');
				var onepiece=strToJson(data);
				var firstGridStore = Ext.create('Ext.data.JsonStore',{
					model:DataObject,
					data:onepiece
				})
				getGrid(firstGridStore)
			},

		   failure:function(response,opts){
				
				Ext.Msg.alert('消息', '错误');
			},
			
		   params:{page:1}

		});

	
});

?index.jsp

?

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
    	
		<link rel="stylesheet" type="text/css" href="ext-4.0/resources/css/ext-all.css" />
    	<link rel="stylesheet" type="text/css" href="ext-4.0/examples/shared/example.css" />
    	<script type="text/javascript" src="ext-4.0/bootstrap.js"></script>
		<script type="text/javascript" src="ext-4.0/examples/shared/examples.js"></script>
		<script type="text/javascript" src="user.js" charset="utf-8"></script>

	<script type="text/javascript" src="jquery-1.4.1.js"></script>
	
	<SCRIPT type="text/javascript">
	
	
	
	</SCRIPT>
	
  <body>
  <INPUT type="hidden" id="authHidden" value ="<sec:authentication property="principal.authorities"/>"/>
		<div align="center" style="padding-top:120px;" id="panel"></div>
  </body>
</html>
1 楼 funnyone 2012-01-19