Struts 2内嵌了Dojo工具包,实现对Ajax的支持。下面是一个用户名和密码都是Admin的Login应用。
1、在struts.xml中加入一个Action mapping
xml 代码
- <action name="showAjaxLoginForm">
- <result>/pages/ajaxlogin.jspresult>
- action>
-
- <action name="ajaxLogin" class="net.roseindia.Login">
- <result name="input">/pages/ajaxlogin.jspresult>
- <result name="error">/pages/ajaxlogin.jspresult>
- <result>/pages/ajaxloginsuccess.jspresult>
- >
2、用Ajax编写一个Login页面ajaxlogin.jsp
这个页面使用了 标签, 这个标签能通过Ajax tags载入页面内容。jsp页面还使用了标签,这个标签可以利用Ajax来更形页面元素和提交一个form。当出现错误是,和标签执行并显示错误信息。
xml 代码
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <html>
- <head>
- <s:head theme="ajax" debug="true"/>
- head>
- <body>
- <s:div id="loginDiv" theme="ajax">
- <div style="width: 300px;border-style: solid">
- <s:form action="ajaxLogin" validate="true">
- <tr>
- <td colspan="2">
- Login
- td>
- tr>
- <tr>
- <td colspan="2">
- <s:actionerror />
- <s:fielderror />
- td>
- tr>
- <s:textfield name="username" label="Login name"/>
- <s:password name="password" label="Password"/>
- <s:submit theme="ajax" targets="loginDiv" notifyTopics="/ajaxLogin"/>
- s:form>
- div>
- s:div>
- body>
- html>
3、编写一个验证用户名和密码的Action类Login.java
如果验证成功返回SUCCESS,失败就返回ERROR
java 代码
- package net.roseindia;
-
- import com.opensymphony.xwork2.ActionSupport;
- import java.util.Date;
-
-
-
-
- public class Login extends ActionSupport {
-
- public String execute() throws Exception {
- System.out.println("Validating login ... ...");
- System.out.println("User = " + getUsername());
- if (!getUsername().equals("Admin") || !getPassword().equals("Admin")) {
- System.out.println("Validating error ! User = " + getUsername());
- addActionError("Invalid user name or password! Please try again!");
- return ERROR;
- } else {
- System.out.println("Validating success !");
- return SUCCESS;
- }
- }
-
-
-
-
-
-
- private String username = null;
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String value) {
- username = value;
- }
-
-
-
-
-
-
- private String password = null;
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String value) {
- password = value;
- }
-
- }
4、编写一个登录成功页面ajaxloginsuccess.jsp
xml 代码
- <html>
- <head>
- <title>Login Successtitle>
- head>
- <body>
- <p align="center"><font color="#000080" size="5">Login Successful !font>p>
- <h1> Welcome to <%=request.getParameter("username")%> h1>
- body>
- html>
5、访问下面连接 http://localhost:8080/s2ajax/showAjaxLoginForm.action
posted on 2007-12-05 00:01
怡众科技 阅读(982)
评论(0) 编辑 收藏 所属分类:
转载区