Struts2学习笔记<1> -入门及基本配置

使用的IDE为myeclipse6.0,第一个简单的示例就不涉及DB了.

总体上讲分以下几步:
  • 1.myeclipse中新建WEB工程
  • 2.导入struts2的JAR包
  • 3.编写action及jsp页面
  • 4.新建struts.xml文件,并在里面注册第三步写好的action


以下是详细步骤:

1.myeclipse中新建WEB工程--这个就不说了,地球人都知道^^

2.导入struts2的JAR包,包可到http://struts.apache.org/上下,目前最新版为2.0.11.第一个简单的示例,只用导以下五个包即可,
  • commons-logging-1.0.4.jar
  • freemarker-2.3.8.jar
  • ognl-2.6.11.jar
  • struts2-core-2.0.11.jar
  • xwork-2.0.4.jar


3.编写action及jsp页面

LoginAction.java代码如下:

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;
	}

	@Override
	public String execute() throws Exception {
		if("xxj".equals(this.username.trim()) && "fang".equals(this.password.trim())){
			return SUCCESS;
		} else {
			this.addFieldError("username", "username / password error");
			return ERROR;
		}
	}

	@Override
	public void validate() {
		//这里暂不写验证
				
	}
}


login.jsp代码如下:

<%@ page language="java" pageEncoding="GB18030"%>

<html>
	<head>
		<title>My JSP 'login.jsp' starting page</title>

	</head>
	<body>
		<form action="login.action" method="post">
			pusername:
			<input type="text" name="username">
			<br>
			password:
			<input type="password" name="password">
			<br>
			<input type="submit" value="submit">
		</form>
	</body>
</html>


result.jsp代码如下:
<%@ page language="java" pageEncoding="GB18030"%>

<html>
	<head>

		<title>result</title>

	</head>

	<body>
		pusername:${requestScope.username }
		<br>
		password:${requestScope.password }
		<br>
	</body>
</html>


4.新建struts.xml文件,并在里面注册第三步写好的action
PS:此文件必须建在\WEB-INF\classes\目录下,在Eclipse中,可以建在src目录下,eclipse会自动将其copy到\WEB-INF\classes\目录下


<?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="default" extends="struts-default">
    <!--这里就注册了刚才写好的LoginAction,以便让jsp中调用login.action-->
    <action name="login" class="com.test.action.LoginAction">
	<!--成功则跳到result.jsp,输入不正确则跳到login.jsp页面让用户继续输入正确的值-->
        <result name="success">/result.jsp</result>
        <result name="input">/login.jsp</result>
    </action>
	
   </package>
</struts>


修改web.xml文件。加入如下代码:
<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>
OK,布署到tomcat中就可以运行了

你可能感兴趣的:(java,eclipse,jsp,MyEclipse,struts)