ssh 框架 jquery ajax 向action中传入bean对象,并解析

Debugzhang 2013-10-26

1.请先看jsp页面

<%@ 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+"/";
//System.out.print("path:"+path+"basePath:"+basePath);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>添加信息</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">
	-->
	
	<script type="text/javascript" src="<%=path%>/js/jquery/jquery-1.2.6.js"></script>  
	<script type="text/javascript" language="javascript">
		$(document).ready(function(){ 
    		$("#login").click(function(){  
        		login();  
        	});  
		}); 
		
		function Mybean(){
			this.title="你大爷威武";
			this.content="你大爷威武!!!";
			this.id="11";
		}
		 
		function login(){
		    //alert(11)
		    var mybean = new Mybean();
		    var url = "ajax_login2.action";  
		    var params = {
			    "user.username":$("#name").attr("value"),
			    "user.password":$("#password").attr("value"),
			    "haha":"你大爷的",
			    "result":JSON.stringify(mybean)
		    };  
		   
		    //alert("params:"+params);
		    
		    //alert(22);
		    
		    /*  
		    $.getJSON(url,params,function callback(data){  
		        // convert to json object 
		        
		        alert("data:"+data);
		         
		        var user = eval("("+data+")");//  
		        
		        alert("user:"+user);  
		          
		        $("#result").each(function(){  
		            $(this).html('welcome ,' + user.name);  
		            });  
		    });
		    */
		    $.ajax({
		    	type:"post",
		    	url:url,
		    	async:false,
		    	data:params,
		    	
		    	
		    	success:function(data){
		    		 alert(data);
		    		 
		    		 var user = eval("("+data+")");// 
		    		 alert(user)
		    		 //alert("命令为:"+user.command);
		    		 //alert("令为:"+user.list[0].id);
		    		 
		    		 //alert("用户名:"+user.users.username);
		    		 //alert("密码:"+user.users.password);
		    		 
		    		 alert("返回的bean:"+user.noticeBean.id+":"+user.noticeBean.title+":"+user.noticeBean.content);
		    		 
		    		 $.each(user.list,function(num,value){   
					    $("#result").append("<div>welcome您,"+user.users.username+"</div>").append("<div>第"+(num+1)+"个用户:</div>")   
					       .append("<div><font color='red'>用户ID:"+value.id+"</font></div>")   
					          .append("<div><font color='red'>公告标题:"+value.title+"</font></div>")   
					          .append("<div><font color='red'>公告内容:"+value.content+"</font></div>");   
					});
		    		$("#login").attr("disabled",true);
		    	
		    	},
		    	/*
		    	success: function(data){
		    		//alert("123");  
		    		//alert(data);  
                    //alert("您已预约成功!"); 
                    alert(data);
                    
                    
                    var user = eval("("+data+")");//  
		        
		            //alert("user:"+user);  
		          
		            $("#result").each(function(){  
		                $(this).html('welcome ,' + user[0].username);  
		            }); 
                    $("#login").attr("disabled", true);  
                },
                */
                error: function(){  
                    alert("您的预约信息保存失败,请重新预约!");  
                }  
		    });  
	    }  
	</script>
  </head>
  
  <body>
  	<!-- 
    This is my JSP page.你大爷的 <br>
    <s:form action="save" method="post" namespace="/taoge">
    
    <s:textfield name="user.username"  label="用户名"></s:textfield>  
    <s:password name="user.password"  label="密码"></s:password>  
    
    <s:submit  vlaue="提交"></s:submit>
    </s:form>
  	 -->
    
    <s:actionmessage/>  
	<form  method="post" id="form"><s:text  
	    name="用户名"/>:<input type="textbox" name="user.username" id="name"  
	    value='${param["user.username"]}' /><br>  
	<s:text name="密码" />:<input type="password" id="password"  
	    name="user.password" /><br>  
	<input type="button" id="login" value='<s:text name="登陆"/>' />
	
	</form>  
	
	<div id="result">  
	      
	</div>  
    
    
  </body>
</html>

 2:看action代码

package com.taoge.action;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.taoge.model.Account;
import com.taoge.model.Notice;
import com.taoge.model.NoticeDAO;
import com.taoge.service.stuManager;


@Entity
public class stuAction extends ActionSupport  {

	/**
	 * 
	 */
	@Id
	@GeneratedValue
	private static final long serialVersionUID = 1L;
	
	@ManyToOne
	private stuManager stuManager;
	
	private NoticeDAO noticeDAO;
	
	public void setNoticeDAO(NoticeDAO noticeDAO) {
		this.noticeDAO = noticeDAO;
	}

	private List list;
	
	
	private String str="haha"; 
	private String result; 
	private Notice noticeBean; 
	
	private String haha; 
	private String command; 

	private String username;
	
	private String password; 
	
	private Account user = null; 
	
	private Account users; 
	

	



	public String add(Object obj){
		
		stuManager.add(obj);
		return SUCCESS;
	}
	
	
	public String login2(){
		
		System.out.println(user.getUsername()+":"+user.getPassword()+"哈哈:"+this.getHaha());
		
		String rslt=this.getResult();
		
		noticeBean = (Notice)JSONObject.toBean(JSONObject.fromObject(rslt), Notice.class);
//		Account account=new Account();
//		
//		account.setUsername(user.getUsername());
//		account.setPassword(user.getPassword());
		
		this.setUsers(user);
		
        list = noticeDAO.findAll();
        this.setCommand("success123");
//		return "login2";
		return SUCCESS;
	}
	
	
	/*
	 * 流的形式返回
	 */
//	public String login(){
//		
//		System.out.println(user.getUsername()+":"+user.getPassword());
//		
//		Map<String, String> map = new HashMap<String, String>();  
//		
//        map.put("name", user.getUsername()); 
//        
//        map.put("password",user.getPassword());  
//        
//        list = stuManager.getList();
//        
//        
////        JSONObject obj = JSONObject.fromObject(map); 
////        result = obj.toString(); 
//        
//        JSONArray jsonarray = JSONArray.fromObject(list);
////        
////        result = jsonarray.toString(); 
//        
//        ActionContext  context = ActionContext.getContext();
////		HttpServletRequest  request=(HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);
//        
//		HttpServletResponse rspon = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
//		
//        System.out.println("result:"+result); 
//        
//        rspon.setCharacterEncoding("utf-8");  
//        rspon.setCharacterEncoding("utf-8");  
//        rspon.setContentType("text/html");
//        
//         PrintWriter out = null;  
//        try {  
//            out = rspon.getWriter();  
//        } catch (IOException e) {  
//              
//            e.printStackTrace();  
//        }    
//        
//        
//        out.print(jsonarray);  
//        
//        out.flush();  
//        out.close();  
//          
//		return SUCCESS;
//	}
	
	public String save(){
		
//		System.out.println("haha"+username);
		
	    System.out.println(user.getUsername()+":"+user.getPassword());
		
		list = stuManager.getList();
		return SUCCESS;
	}

	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 String getHaha() {
		return haha;
	}

	public void setHaha(String haha) {
		this.haha = haha;
	}

	
	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	public Account getUsers() {
		return users;
	}

	public void setUsers(Account users) {
		this.users = users;
	}

	public Account getUser() {
		return user;
	}

	public void setUser(Account user) {
		this.user = user;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public void setStuManager(stuManager stuManager) {
		this.stuManager = stuManager;
	}

	public List getList() {
		return list;
	}

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


	public Notice getNoticeBean() {
		return noticeBean;
	}


	public void setNoticeBean(Notice noticeBean) {
		this.noticeBean = noticeBean;
	}

		
	
	

}

 3.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">
  <display-name></display-name>	
  
  <context-param>
  	<param-name></param-name>
  	<param-value></param-value>
  </context-param>
  
  <context-param>
        <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
  </context-param>
  
  <!-- 管理session -->
  <filter>
  	<filter-name>lazyLoadingFilter</filter-name>
  	<filter-class>
  		org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  	</filter-class>
  	<init-param>  
            <!--  
                指定org.springframework.orm.hibernate3.LocalSessionFactoryBean  
                在spring配置文件中的名称,默认值为sessionFactory.  
                如果LocalSessionFactoryBean在spring中的名称不是sessionFactory,  
                该参数一定要指定,否则会出现找不到sessionFactory的例外  
            -->  
            <param-name>sessionFactory</param-name>  
            <param-value>sessionFactory</param-value>  
    </init-param>
  </filter>
 
  
  <!-- Spring Listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
	       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	
  
  <!-- Log4j Config -->
	<context-param>   
	    <param-name>log4jConfigLocation</param-name>   
	    <param-value>/WEB-INF/classes/log4j.properties</param-value>   
	</context-param> 
  
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  
  
  
  <filter-mapping>
  	<filter-name>lazyLoadingFilter</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  
  
  <filter>
	  <filter-name>CharacterEncodingFilter</filter-name>
	  <filter-class>
	   		com.taoge.filter.FilterEncoding
	  </filter-class>
	  <init-param>
	   <param-name>encoding</param-name>
	   <param-value>UTF-8</param-value>
	  </init-param>
	  <init-param>
	   <param-name>forceEncoding</param-name>
	   <param-value>true</param-value>
	  </init-param>
 </filter>
 <filter-mapping>
	  <filter-name>CharacterEncodingFilter</filter-name>
	  <url-pattern>/*</url-pattern>
 </filter-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  </web-app>

 4.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.Factory" value="spring"></constant>
	<package name="com.taoge.action" extends="struts-default" namespace="/taoge">
		<action name="findall"  class="testBean">
			<result>/success.jsp</result>
		</action>
		
		<action name="save"  class="testBean" method="save">
			<result name="SUCCESS">/success.jsp</result>
			<result name="save">/error.jsp</result>
		</action>
	</package>
	
	<package name="ajax_action" extends="json-default" namespace="/">
		
		<action name="ajax_*" class="testBean" method="{1}">
			<result type="json" ></result>
		</action>
	
	
	</package>

</struts>

相关推荐