前提条件:搭建好SSH框架;
本功能依赖jar包:struts2-json-plugin-2.3.24(例);
步骤:1、导入依赖jar包;2、编写action;3、配置spring;4、配置struts.xml;5、编写ajax脚本;
说明:本例关键词:ajax、jquery、javascript、SSH、java;
IDE环境:intellij idea;
1、导入jar包
把下载好的struts2-json-plugin-2.3.24复制到lib文件夹下,并要在Module Setting中添加引用,不然报错。
2、编写action
package com.soyann.sys.login;
import com.opensymphony.xwork2.ActionContext;
import com.soyann.common.util.BaseAction;
import com.soyann.common.util.Constants;
import com.soyann.common.util.MD5;
import com.soyann.sys.user.pojo.SysUser;
import com.soyann.sys.user.service.SysUserService;
import java.util.List;
/**
* @Title: filename
* @Package: com.soyann.sys.login
* @Description: ajax调用struts action实例
* @Copyright: Copyright 2015 ShenZhen SOYANN Corporation
* @Company:
* @author: neil
* @date: 2015/6/22
* @version: V1.0
*/
public class JsonLoginAction extends BaseAction {
private static final long serialVersionUID = 8513301164650419245L;
private SysUserService sysUserService;(注意这里不能生成getter,否则spring注入的时候报错)
private String username;
private String passwd;
private String result;
private SysUser sysUser;
public SysUser getSysUser() {
return sysUser;
}
public void setSysUser(SysUser sysUser) {
this.sysUser = sysUser;
}
public void setSysUserService(SysUserService sysUserService) {
this.sysUserService = sysUserService;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
try {
List<SysUser> userList = sysUserService.getUserByLoginid(username);
if (userList.isEmpty()) {
super.addActionError(super.getText("login.message.failed"));
result = "false";
} else {
sysUser = userList.get(0);
if (new MD5().getMD5ofStr(passwd).equals(sysUser.getPassword())) {
ActionContext.getContext().getSession().put(Constants.USERNAME_KEY, username);
ActionContext.getContext().getSession().put(Constants.SYSUSER_KEY, sysUser);
result ="true";
} else {
//super.addActionError(super.getText("login.message.failed"));
result ="false";
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return SUCCESS;
}
public String getResult() {
return result;
}
}
这里注意execute()执行后返回为null、success都无所谓,在前台我们只取定义的result值,这里将会以json返回到前台。
3、配置spring
<!-- json登录Action -->
<bean id="jsonLoginAction" class="com.soyann.sys.login.JsonLoginAction" scope="prototype">
<property name="sysUserService" ref="sysUserService"/>
</bean>
4、配置struts.xml
<strong> </strong><package name="ajax" extends="json-default">
<action name="jsonLogin" class="jsonLoginAction">
<result type="json"></result>
</action>
</package>
这里要注意包要继承json-default,返回类型type=json; 这样后台数据才能以json形式返回到前台读取。
5、编写ajax脚本
<%--
Created by IntelliJ IDEA.
User: neil
Date: 2015/6/22
Time: 17:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax调用struts</title>
<script type="text/javascript" src="assets/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
</head>
<body>
<script type="text/javascript">
jQuery(document).ready(function($){
$("form#login").validate({
errorClass: "error",
errorElement: "div",
errorPlacement: function(error, element) {
element.after(error);
},
rules: {
username: { required: true, minlength: 2},
passwd: { required: true, minlength: 2}
},
messages: {
username: { required: "必填", minlength: $.validator.format("不得少于{0}字符.")},
passwd: { required: "必填", minlength: $.validator.format("不得少于{0}字符.")}
},
submitHandler: function(form)
{
$.ajax({
url: "jsonLogin.action",
method: 'POST',
dataType: 'text',
data: {
do_login: true,
username: $(form).find('#username').val(),
passwd: $(form).find('#passwd').val()
},
success: function (json) {
var obj = $.parseJSON(json); //使用这个方法解析json
var state_value = obj.result; //result是和action中定义的result变量的get方法对应的
/*alert(state_value);*/
if(state_value=="true"){
alert("true");
}else{
alert("false");
}
},
error: function (json) {
alert("json=" + json);
return false;
}
});
}
});
});
</script>
<form method="post" role="form" id="login" action="">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" autocomplete="off" />
</div>
<div class="form-group">
<label for="passwd">Password</label>
<input type="password" name="passwd" id="passwd" autocomplete="off" />
</div>
<div class="form-group">
<button type="submit">
Log In
</button>
</div>
</form>
</body>
</html>
注意这里有个验证功能,需要导入相应的js包才能运行。