跳过struts2环境搭建部分,或者可以看我的博客(http://www.cnblogs.com/zhangky/p/8436472.html),里面有写,很详细。
需要导入的jar包(struts官网有,自己下)
一、java类
private String username;
private String pwd;
private Map<String, Object> result; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd;
} public Map<String, Object> getResult() {
return result;
} public void setResult(Map<String, Object> result) {
this.result = result;
} public String login() {
result = new HashMap<String , Object>();
if(username.equals("z") && pwd.equals("123")) {
result.put("success", true);
result.put("username", username);
return "success";
}else {
result.put("success", false);
return "success";
} }
二、html页面
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div id="tips"></div>
<input type="text" id="username"/>
<input type="password" id="pwd"/>
<button onclick="login()">登录</button>
</body>
<script src="jquery.min.js"></script>
<script>
function login(){
const username = document.getElementById("username").value;
const pwd = document.getElementById("pwd").value;
$.ajax({
type:"POST",
url:"login",
data:{
"username":username,
"pwd":pwd
},
dataType:"json",
success:function(data){
let tips = document.getElementById("tips");
if(data.success == true){
window.location.href = "welcome.html?username=" + data.username
}else{
tips.innerHTML = "用户名或者密码错误";
}
},
error:function(error){ }
})
}
</script>
</html>
三、struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<package name="default" namespace="/" extends="json-default,struts-default">
<action name="login" class="day20.LoginAction" method="login" >
<!--result默认name是success可不写,由于返回的是json格式数据,因此type必须是json -->
<result type="json">
<!--param 的 name固定写,result就是java类要返回的数据变量 -->
<param name="root">result</param>
</result>
</action>
</package>
</struts>