这两天新学Struts2,顺带看了点prototype,做了个ajax登录的小例子,练习了一下基本的struts2的配置和一些简单的prototype方法的使用。
login.js内容:
1 //login.js
2 // javascript document
3 function loginfun(username, password) {
4 var logindiv1 = $("logindiv");//$()相当于document.getElementById()
5 //alert(logindiv1.id);
6 var forms = {username:$F(username), password:$F(password)};//$F()返回表单控件的值
7 logindiv1.innerHTML = "登录中";
8 var url = "logintest.action";//后面的struts.xml配置的
9 var pars = $H(forms);//将对象转换成一个可枚举的和联合数组类似的hash对象
10 var par = pars.toQueryString();//显示username=xj&password=4321;
11 var myajax = new Ajax.Request(url, {method:"post", parameters:par, onComplete:showResponse});//实现ajax请求
12 }
13 function showResponse(originalRequest) {
14 // 将返回的 xml 放到 textarea 内
15 $("logindiv").innerHTML = originalRequest.responseText;
16 }
17 //login.js end
login.html内容:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>prototype+struts</title>
5 <script type="text/javascript" src="../js/prototype.js"></script>
6 <script type="text/javascript" src="../js/login.js"></script>
7 </head>
8 <body>
9 <div id="logindiv">
10 用户名:
11 <input type="text" value="xj" id="user">
12 密码:
13 <input type="text" value="4321" id="password">
14 <br>
15 <button onclick="loginfun('user','password')">
16 Login
17 </button>
18 </div>
19 </body>
20 </html>
21
LoginAction.java内容:
//这里直接用servelet实现,在web.xml配置也一样
1 package struts.login;
2
3 import java.io.IOException;
4 import javax.servlet.http.HttpServletResponse;
5 import org.apache.struts2.ServletActionContext;
6 import com.opensymphony.xwork2.ActionSupport;
7
8 public class LoginAction extends ActionSupport {
9
10 private String username;
11 private String password;
12
13 public String getPassword() {
14 return password;
15 }
16
17 public void setPassword(String password) {
18 this.password = password;
19 }
20
21 public String getUsername() {
22 return username;
23 }
24
25 public void setUsername(String username) {
26 this.username = username;
27 }
28
29 public String execute() throws IOException {
30 HttpServletResponse response = ServletActionContext.getResponse();
31 response.setCharacterEncoding("utf-8");
32 if (getUsername().equals("xj") && getPassword().equals("4321")) {
33 response.getWriter().write(getUsername() + " 登陆成功!");
34 }else {
35 response.getWriter().write(getUsername() + " 登陆失败!");
36 }
37 return null;
38 }
39 }
struts.xml配内容:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5 <struts>
6 <package name="struts.login" extends="struts-default">
7 <action name="logintest" class="struts.login.LoginAction">
8 <result>login.html</result>
9 </action>
10 </package>
11 </struts>
显示结果: