读书人

【Struts 二】登陆示例

发布时间: 2012-09-04 14:19:30 作者: rapoo

【Struts 2】登陆示例

Struts一般必须的lib有:

commons-fileupload-1.2.2.jarcommons-io-2.0.1.jarcommons-lang3-3.1.jarfreemarker-2.3.19.jarjavassist-3.11.0.GA.jarognl-3.0.5.jarstruts2-core-2.3.4.jarxwork-core-2.3.4.jar


将以上包加入到项目中,然后配置web.xml,

  <filter>  <filter-name>struts2</filter-name>  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>  <filter-name>struts2</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>

Strust自己也有一个配置文件,在src目录中,新建xml文件struts.xml,

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><package name="yhn" extends="struts-default"></package></struts>


新建一个类,LoginAction,继承自ActionSupport,

public class LoginAction extends ActionSupport{private String username;private String password;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;}@Overridepublic String execute() throws Exception {return SUCCESS;}}


Action的作用相当于Servlet所以也需要配置,在struts.xml中加入:

<action name="LoginAction" class="org.yhn.test.action.LoginAction"><result name="success">/index.jsp</result><result name="error">/error.jsp</result></action>


在登陆页面中加入:

<form action="LoginAction" method="post">用户名:<input type="text" name="username"><br>密码:<input type="password" name="password"><br><input type="submit" value="登陆"></form>


在成功页面,也就是index.jsp中显示数据:

你输入的:<br>用户名:${requestScope.username}<br>密码:${requestScope.password}


运行后,登陆成功效果如下:

【Struts 二】登陆示例

读书人网 >编程

热点推荐