(一)教你学会Struts2使用及封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21004057/article/details/79252536

 大家好,今天给大家带来的是Struts2的使用。文章共四篇,最后一篇完整集成SSH框架。每篇文章都用心在写,然后呈现给大家。方便大家共同学习。如若有误,敬请指出!今天学习的效果图如下:通过登录界面登录成功后跳转到主界面,登录失败则跳到原界面重新输入。后续文章将包括AOP增强,各类配置文件的完善。


一:Struts的下载及导入:

Struts的官网下载地址: 点击进入官网



下载后解压得到其中的8个jar包。如下图,servlet-api.jar除外,此jar是tomcat的jar包。将此9个包导入复制到webcontent/web-INF/lib目录下。它会自动将包加入到src目下的web app Libraries。


二:SSH项目结构及分包

SSH项目分包结构如下如:

三:Struts原理介绍

 Struts框架通过URL请求中的action后缀来判断是哪种action,比如 login.action或者 loginout.action,loginin.action。 检查URL中是否存在带有action后缀,然后对其进行截取,比如login.action将会截取login作为具体行为。截取之后便会将该请求中的参数对进行实体对象封装。比如获取帐号密码,会匿名封装一个对象,同时提供execute方法,用来处理请求成功或者失败。

四:Struts简单实例

在action包下新建一个登录类LoginAction。默认实现

LoginAction类三种写法:
  • 不继承任何类也不实现任何接口
  • 继承ActionSupport类(推荐此方法),提供了许多默认方法,比如国际化信息方法,数据校验,默认处理用户请求,方便扩展
  • 实现Action接口,通过implements

1.编写LoginAction


package com.struts.test.web.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.opensymphony.xwork2.ActionContext;
import com.struts.test.Config;
import com.struts.test.pojos.User;

public class LoginAction extends ActionSupport{
	private String username;//用户名
	private String userpassword;//用户密码

	public String getUsername() {
		return username;
	}

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

	public String getUserpassword() {
		return userpassword;
	}

	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}

	public String execute(){
		if("790710371".equals(username)&&"123".equals(userpassword)){
			//获取当前的时间戳
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date());
		ActionContext context  = ActionContext.getContext();
		context.getSession().put(Config.KEY_LOGIN_TIME,date);//保存当前登录的时间戳
		context.getSession().put(Config.KEY_CURRENT_USER,new User(username,userpassword));//保存当前用户
			return "success";//登录成功跳转到主界面
		}
		return "input";
	}
}

2.添加web.xml中的struts2的核心过滤器

 web.xml在创建项目时候勾选自动生成。添加<filter>过滤器和过滤器映射<filter-mapping>标签,具体请参照下面代码。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>strutstest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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>
</web-app>

3.编写struts2的配置文件struts.xml

 创建该文件时,并不会主动生成dtd声明,我们可以直接复制下面的声明或者直接从其他项目工程中。在下面的代码中有一个<struts>标签,内含<package>包标签。一般extends直接写默认的struts-default,namespace如果不写的话,访问URL的时候直接项目名/xxx.action?action=xxx。如果填写namespace的话,访问URL的时候为项目名/命名空间?action=xxx。

<package>:包含package名称,extends继承,填写默认;命名空间,根据实际情况命名。建议不为空。
<action>:包含action名称,class类名,即该action所对应的类名。比如action为login,即LoginAction。此处需要类全名(包+类名)。
按住ctrl把鼠标移动到class上面,鼠标箭头变成手型,并且可以点进去即代表配置正确。
<result>:请求结果的处理,通常为jsp界面或者action。


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC  
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
"http://struts.apache.org/dtds/struts-2.3.dtd">  
<struts>
	<package name="loginout" extends="struts-default" namespace="/admin">
		<action name="login" class="com.struts.test.web.action.LoginAction">
		<result name="success">/admin/main.jsp</result>
		<result name= "input">/admin/login.jsp</result>
		</action>	
	</package>
</struts>
result标签的完整写法如下:

跳转到jsp:

通过dispatcher的方式转发,默认的就是dispatcher,所以不写type的时候默认是dispatcher转发。

<result name="success" type="dispatcher">/admin/main.jsp</result>
或者重定向
<result name="success" type="redirect">/admin/main.jsp</result>

跳转到action:

同包下的action跳转:

chain方式(action链式)
<result type="chain" name="success">other_action_name</result>
或者重定向
<result type="redirect"name="success">other_action_name</result>

不同包的action跳转:

<result type="rediretAction">
	<param name="actionName">loginout</param><!--要跳转的action的名称-->
	<param name="namespace">port</param><!--要跳转的action的命名空间-->
</result>

4.URL访问

   上面说了访问分为action访问和jsp访问,URL的两种方式。本文的URL采用
http://localhost:8002/strutstest/admin/login.action?action=login&username=790710371&userpassword=123
访问规则:域名(或者ip:端口)+项目名+命名空间/xxx.action?action=xxx&参数键1=参数值&参数键2=参数值2&...

五:Struts封装使用

   在实际项目中,我们通常需要对整体进行项目的封装,以便减少繁缛重复地代码,降低不必要的代价。所以我们需要编写Action基类类BaseAction。通常基类中都是把每个业务类中共有的方法抽象出来。本文采用反射调用执行任意action从而实现在一个Action文件内实现多个action调用。比如LoginAction实现注销等与登录有关的功能,我们只需要添加loginout等方法就可以了。而不需要重新建立LoginOut类继承ActionSupport。这样就简单多了。

package com.struts.test.web.action;

import java.lang.reflect.Method;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport{
	private String action;//从URL中得到的action,比如login.action?action=login

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}
	public String execute(){
		try {
			return invokeMethod(getAction());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return INPUT;
	}
	private String  invokeMethod(String  action) throws Exception{
		Class[] c=null;
		Method  method = this.getClass().getMethod(action, c);
		Object[] o = null;
		String s = (String)method.invoke(this, o);
		return s;
	}
}

改良后的LoginAction:

 项目中我们只需要继承基类BaseAction即可,大大减少工作量。
package com.struts.test.web.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.opensymphony.xwork2.ActionContext;
import com.struts.test.Config;
import com.struts.test.pojos.User;

public class LoginAction extends BaseAction{
	private String username;//用户名
	private String userpassword;//用户密码

	public String getUsername() {
		return username;
	}

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

	public String getUserpassword() {
		return userpassword;
	}

	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}
	public String login(){
		if("790710371".equals(username)&&"123".equals(userpassword)){
		//获取当前的时间戳
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date());
		ActionContext context  = ActionContext.getContext();
		context.getSession().put(Config.KEY_LOGIN_TIME,date);//保存当前登录的时间戳
		context.getSession().put(Config.KEY_CURRENT_USER,new User(username,userpassword));//保存当前用户
			return "success";
		}
		return "input";
	}
}
右键login.jsp选择run as server运行,结果如下图:



升级后的action比之前的更完美直观,不再有execute出现啦!
本文到此就结束了,谢谢大家阅读!有什么问题欢迎给我留言!



猜你喜欢

转载自blog.csdn.net/qq_21004057/article/details/79252536