Struts文档

因为先接触MVC框架为是SpringMVC,自己整理一下Struts框架的大概用法,作为了解

1、Struts使用

struts2是一个基于MVC设计模式的Web应用框架,Struts2作为控制器(Controller)来简历模型与视图的数据交互(和Spring MVC的作用是一样的)

1、添加jar包

    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.3.28.1</version>
    </dependency>

2、修改web.xml文件

 <!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 通过该过滤器引入struts框架 -->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <!--  /*会拦截所有的资源,然后进入struts2进行相关的处理 -->
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

3、开发action类

自定义的action类,继承ActionSupport类,类中根据url调用的方法,必须是public的,返回值必须是String,方法不能有参数,如下:

//方法是public的,是String类型返回值,方法没有参数
	public String login(){
//ServletActionContext.getRequest(); 获取请求对象
		return "success";}

4、配置struts.xml

​ 在src下擦混关键struts.xml文件,程序回自动加载该文件(实际加载发布目录下的xml文件):

​ …\webapp\web应用\WEB-INF\classes

4.1、Struts的配置必须引入相关的约束

<?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">

4.2、Struts的基本配置格式


	<!-- package 属性:
name 包名,不能重复
		extends  继承的包,大部分情况下,继承自struts-default 
		abstract 是否是抽象的,ture表示是,如果设置为true,配置中不能有action
		namespace 命名空间,默认是"/",设置命名空间主要用来解决不同包中,action的name相同的的情况的处理,namespace的值作为路径的一部分存在
			如http://localhost:8080/F01_Struts2_2/abc/login
			
		action 属性:
			name  action的名称,作为url的一部分存在
			class  访问action对应的类,必须写上包名 :包名+类名
			method 访问action执行的方法
			
		result属性:			name  result的名称,与method对应方法的返回值String内容对应
			result的文本内容,如"/index.jsp" 表示要跳转到的资源
	-->
	<struts>
	<package name="login"  namespace="/abc" extends="struts-default">
		<action name="login" class="com.rr.action.LoginAction" method="login">
			<result name="success">/index.jsp</result><!-- 转发的方式是内部转发 -->
			<result name="error" type="redirect">/error.jsp</result><!-- 重定向 -->
		</action>
	</package>

</struts>

5、其他Struts配置

5.1、常量

​ 注:在内的头部进行添加

<!-- constant 设置常量 name对应的值可以参考default.properties文件-->
	<!-- 设置post提交方式的中文乱码处理 -->
	<constant name="struts.i18n.encoding" value="UTF-8"></constant>
	<!-- 设置访问action的后缀 -->
	<!-- <constant name="struts.action.extension" value="do"></constant> -->
	<!-- 表示后缀可以是action/do,或者没有后缀 -->
	<constant name="struts.action.extension" value="action,do,"></constant>

	<!-- 修改struts配置后,自动加载 -->
	<constant name="struts.configuration.xml.reload" value="true"></constant>
<!-- 设置是否是开发模式,true是,默认false ,针对其他类型的配置文件,也不用重启服务器-->
	<constant name="struts.devMode" value="true"></constant>

5.2、result的type属性

​ 注:在struts-default.xml文件中可以查询到type支持的值

<result name="success">/index.jsp</result><!-- 转发的方式是内部转发 -->
<result name="error" type="redirect">/error.jsp</result><!-- 重定向 -->

5.3、指定其他的struts.xml文件

    <!--包含其他的struts配置文件-->
    <include file="com/qfedu/first/struts.xml"></include>

2、action中接受参数

2.1、通过ServletActionContext获取请求对象

	public String param1(){
        //拿到请求对象
        HttpServletRequest request = ServletActionContext.getRequest();
        request.getParameter("name");
        request.getParameter("password");
    }

2.2、action中直接定义相关属性

​ 注:name属性值,必须和action类中的属性名必须保持一致,类中必须写get和set方法

Action类中:
private String name;
	private String pwd;

	public void setName(String name) {
		this.name = name;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
    /**
     * 定义属性方式接受,方法中可直接输出
     */
    public String param2(){
        System.out.println(name +"----"+password);
        return SUCCESS;
    }

2.3、定义一个实体获取参数

1、定义一个实体,在实体中添加属性和get、set方法
2、在Action类中把实体当作属性
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
3、修改前端页面的name值。(对象名称.属性)
        <input type="text" name="user.name" /><br/>
        <input type="password" name="user.password" /><br/>
        <input type="submit" />
4、Action类中可以通过实体的get方法直接输出参数
    /**
     * 定义一个对象来接受参数
     */
    public String param3(){
        System.out.println(user.getName());
        System.out.println(user.getPassword());
        return SUCCESS;
    }

2.4、使用ModelDriven

1、Action类实现ModelDriven接口并重写getModel方法。

​ 注:使用ModelDriven方法不用修改前端的name值为 对象名.属性名,只需要 name值实体的属性名 一致即可

 */
public class ParamAction2 extends ActionSupport implements ModelDriven<User> {

    private User user = null;
    @Override
    public User getModel() {
        if(user == null){
            user = new User();
        }
    return user;
    }
}
2、直接使用实体的get方法进行输出
    public String param4(){
        System.out.println(user.getName());
        System.out.println(user.getPassword());
        return SUCCESS;
    }

3、资源共享数据处理

3.1使用ServletActionContext获取域对象,并进行内部转发

    public String data1(){
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();
        ServletContext servletContext = ServletActionContext.getServletContext();

        request.setAttribute("req_data","张三");
        session.setAttribute("session_data","李四");
        servletContext.setAttribute("app_data","王五");
        return SUCCESS;
    }

​ 在页面中使用el表达式进行取值

${req_data}<br/>
${session_data}<br/>
${app_data}<br/>

3.2、通过ActionContext进行共享数据

	public String data2(){
        ActionContext context = ActionContext.getContext();
        //相当于获取请求对象中存数据的结构
        Map<String, Object> contextMap = context.getContextMap();
        //session对象中存数据的结构
        Map<String, Object> session = context.getSession();
        //ServletContext中存数据的结构
        Map<String, Object> application = context.getApplication();
        return SUCCESS;
    }

​ 之后三个对象中(map)中,put数据,jsp页面通过${key值}来获取数据

4、查看值栈中的数据

3.1在jsp页面中引入Struts提供的标签库

​ <%@taglib uri="/struts-tags" prefix=“s” %>

3.2在页面中使用debug标签
<s:debug/s:debug>

5、struts对json的处理

5.1导入jar包
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-json-plugin</artifactId>
<version>2.3.28.1</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.30</version>
</dependency>
5.2、配置struts.xml

注:package 中的 extends 属性为 json-default

​ result中因为不需要跳转页面,所以内容是控制,只需要设置一个type为json就行,不需要设置name

    <package name="json" extends="json-default">
        <action name="json1" class="com.qfedu.first.HelloStruts" method="hellow">
            <result type="json"></result>
        </action>
    </package>
5.3、JsonAction类中的方法
public class JsonAction extends ActionSupport {
    public void json1() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("name","zhangsan");
        map.put("age",20);

        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(map));

        writer.flush();//刷一下
        writer.close();//清缓存
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值