现在的位置: 首页 > 综合 > 正文

struts2.0登录例子

2013年12月03日 ⁄ 综合 ⁄ 共 2339字 ⁄ 字号 评论关闭

Login页面:这里要说明的是,如果你不使用标签库的话,<form>节点的action属性要写成login.action,如果使用它的标签库的话,只要写login,默认添加了.action,这个后缀是可以配置的

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>登录页面</title>
</head>
<body>
<!-- 不使用标签库 -->
<form action="login.action" method="post">
用户名: <input type="text" name="username"/><br/>
密码: <input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
<h3>-----------------------------------------------------------</h3>
<!-- 使用标签库 -->
<s:form action="login">
 <s:textfield label="用户名:" name="username"></s:textfield>
 <s:password label="密码:" name="password"></s:password>
 <s:submit label="登录"></s:submit>
</s:form>

</body>
</html>

配置信息:struts.xml文件要放在源文件的根目录下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 <package name="struts2.demo" extends="struts-default">
        <action name="login" class="serviceTest.LoginAction">
            <result>/hello.jsp</result>           
        </action>
    </package>
</struts>

Action类:这里继承ActionSupport,struts2.0中的Action可以不继承任何类,当你点击登录,通过配置信息查找匹配的路径,就被提交到这里来了。

package serviceTest;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

 private static final long serialVersionUID = -3503612815883130118L;
 
 private String username ;
 private String password ;
 
 @Override
 public String execute() throws Exception{
  if(getUsername().equals("admin") && getPassword().equals("admin"))
   return SUCCESS;
  else
   return ERROR;
 }
 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
 

}
web.xml文件要添加struts2.0核心的过滤器,所有请求首先都要被提交到这个过滤器

 <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

原文:http://xiezhk2006.blog.163.com/blog/static/123177885200981111205037/

抱歉!评论已关闭.