struts2学习笔记1-初学Struts2

首先struts2有六个必须的包
struts2必须的包
commons-logging-1.0.4.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar
commons-fileupload-1.2.1.jar(上传文件的,不上传文件可以不要)

struts2和struts1不同的是,采用的是filter,而不是servlet
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>


struts2的参数收集不像struts1那样依靠ActionForm,也不用extends Action
不依赖struts2的任何类

package com.langhua.action;

import com.opensymphony.xwork2.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;
	}
	
	public String execute() throws Exception{
		if("langhua".equals(this.getUsername().trim()) && "123456".equals(this.getPassword().trim())){
			return "success";
		}else{
			this.addFieldError("username","username or password is error");
			return "Error";
		}
	}

	@Override
	public void validate() {
		if(null == this.getUsername() || "".equals(this.getUsername().trim())){
			this.addFieldError("username", "username not null");			
		}
		if(null == this.getPassword() || "".equals(this.getPassword().trim())){
			this.addFieldError("password", "password not null");
		}
	}
	
}


struts2的配置文件在Eclipse里面要放到src目录下,这样部署到容器里面的时候,就会放到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>
	<!-- struts默认的struts-default -->
	<package name="struts2" extends="struts-default">
		<!-- 对应login.*的请求,就到class="com.langhua.action.LoginAction"处理 -->
		<action name="login" class="com.langhua.action.LoginAction">
			<!-- name就是execute()里面return的返回值,再转到相应的页面 input是默认的错误处理 this.addFieldError-->
			<result name="success">/langhua/result.jsp</result>
<result name="input">/login2.jsp</result>
			<result name="Error">/login2.jsp</result>
		</action>
	</package>
</struts>


jsp页面
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:form action="login">
    	<s:textfield name="username" label="username"></s:textfield>
    	<s:password name="password" label="password"></s:password>
    	<s:submit label="submit"></s:submit>
    </s:form>

你可能感兴趣的:(apache,freemarker,jsp,xml,struts)