日期:2014-05-16  浏览次数:20373 次

天易28----struts2.1和ajax json的简单使用

一:效果预览

说明:这里没有做任何样式的布局,只是简单的实现功能而已

1)用户名和密码都为空:

2)用户名和密码不正确:

3)用户名和密码输入正确:


二:代码演示:

1)项目目录演示:



2)action代码(为了方便这里用户名和密码是固定写死的,没有访问数据库,可根据需要连接数据库进行用户名校验):
package com.test.action;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.AjaxBean;

public class AjaxLoginAction extends ActionSupport{

	private String method;
	private String info;
	private AjaxBean ab;
	public String execute() {
		String url = "fail";
		try{
			if("login".equals(this.getMethod())){
				url=this.login();
			}
		}catch(Exception err){
			err.printStackTrace();
		}
		return url;
	}

	/**
	 * json登陆测试
	 * @return String
	 */
	private String login(){
		//System.out.println("name and pass11111===================>>>>>>>"+ab.getUsername()+" "+ab.getPassword());
		if((ab.getUsername()==null || ab.getUsername().equals("")) || (ab.getPassword()==null || ab.getPassword().equals(""))){
			this.setInfo("用户名或密码为空,请填写用户名或密码!");
		}
		else if(!ab.getUsername().equals("wzh") || !ab.getPassword().equals("123")){
			this.setInfo("用户名或密码输入有误,请输入正确的用户名和密码!");
		}else{
			this.setInfo("登陆成功!");
		}
		return "loginsuccess";
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	
	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public AjaxBean getAb() {
		return ab;
	}

	public void setAb(AjaxBean ab) {
		this.ab = ab;
	}
	
	
}
3)实体类bean代码(为了方便将username和password两个参数放到原有的实体类里,这里只用username和password两个即可):
package com.test.bean;

import java.io.Serializable;

public class AjaxBean implements Serializable {

	private String id;
	private String sfdm;
	private String sflbbh;
	private String ywmc;
	private String xz;
	private String rksj;
	private String gxsj;
	private String zt;
	private String fplb_id;
	private String zdyflag;
	private String msfbz;
	private String bm;
	private String jmbz;
	private String sfbz;
	
	private String username;
	private String password;
	//组装sql语句
	public String getWhere() {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer(" WHERE 1=1 ");
		if(sfdm!=null&&!"".equals(sfdm.trim())){
			sql.append(" AND SFDM = '"+sfdm+"'");
		}if(ywmc!=null&&!"".equals(ywmc.trim())){
			sql.append(" AND YWMC LIKE '%"+ywmc+"%'");
		}
		
		return sql.toString();
		
	}
	
	
	
	public String getUsername() {
		return username