struts2 配置xml、异步、上传文件、过滤器

出了面试基本用不到,屡一下免得忘了。

struts2是一个Controller层框架,和springMVC的作用相同。

环境

IDEA+maven

配置

1、添加jar包struts2-core

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

2、新建配置文件strus.xml
在这里插入图片描述

demo

1、创建struts2的action类,等价于springMVC的handler处理器类

public class Sysuser {
    private String uname;
    private int uage;
    private String msg;

    public String test(){
        msg="测试信息";
        return "hello";		//对应result标签的name
    }
    public String test2(){
        msg="test2";
        return "gohello";		//对应result标签的name
    }
 

struts2的默认编码是utf-8,无需再设置编码过滤。

2、配置strus.xml

<struts>
    <!--开启动态方法调用,针对于包禁止严格方法调用-->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
	<!--name 自定  namespace 二级路径  extends 继承其他 package             关闭严格方法调用 -->
    <package name="syspackage" namespace="/sys" extends="json-default" strict-method-invocation="false">
    	<!--三级路径  使用 "_方法名"风格的url指定action    method 调用方法 此处调用*指定的action方法-->
        <action name="user_*" class="Sysuser" method="{1}">
        	<!--1、当action类return的值为"hello"   返回到此页面-->
            <result name="hello">/WEB-INF/view/hello.jsp</result>
             <!--2、当action类return的值为"ttt2"   转发到此action-->
            <result name="gohello" type="chain">
                <param name="namespace">/sys</param>
                <param name="actionName">user_test</param>
             </result>
        </action>
    </package>

</struts>

result常用的5中type:
dispatcher,服务端转发的jsp页(默认)
redirect:客户端重定向到jsp
chain:服务单转发的新的action处理器
redirectAction:客户端重定向到新的action
json:异步

3、创建hello.jsp页面
可以使用el表达式取出action类种的全局变量

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>返回的页面</title>
</head>
<body>
    xxxxx
    <hr/>
    <p>uname=${uname},uage=${uage},msg:${msg}</p>
</body>
</html>

4、测试
访问的同时传值

http://localhost:8080/sys/user_test?uname=tom&uage=12

在这里插入图片描述
换成test2结果相同,同样是跳转到此页面

http://localhost:8080/sys/user_test2?uname=tom&uage=12

异步

原生异步

ServletActionContext获取response对象,其他和Java原生异步一样。

    public void test3() throws IOException {
        HttpServletResponse hsr= ServletActionContext.getResponse();
        PrintWriter writer = hsr.getWriter();

        Sysuser user=new Sysuser();
        user.setUname("aimy");
        user.setUage(19);
        user.setMsg("异步请求");
        writer.print(JSON.toJSON(user));
        writer.flush();
        writer.close();
    }

获取servlet核心对象也是通过ServletActionContext

struts2异步
public class Sysuser {
    private User user		//异步返回的对象需要是成员变量;
    private String msg;

    public String test4(){
        user=new Sysuser();
        user.setUname("aimy");
        user.setUage(19);
        return "testajax";
    }
 

添加struts2-json-plugin.jar
struts.xml中package需要extends自 json-default;
result标签的type=json,param标签的name=root,param标签的值为action中的成员变量名称。

<struts>
    <!--开启动态方法调用,针对于包禁止严格方法调用-->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
	<!--name 自定  namespace 二级路径  extends 继承其他 package             关闭严格方法调用 -->
    <package name="syspackage" namespace="/sys" extends="json-default" strict-method-invocation="false">
    	<!--三级路径  使用 "_方法名"风格的url指定action    method 调用方法 此处调用*指定的action方法-->
        <action name="user_*" class="Sysuser" method="{1}">
        <!-- 3、当action类return的值为"ttt4" 异步返回全局变量user(自动转json字符串)  -->
     	 	  <result name="testajax" type="json">
      	      	  <param name="root">user</param>
      		  </result>
        </action>
    </package>

</struts>

4、测试
访问

http://localhost:8080/sys/user_test4

在这里插入图片描述

接收前端的数据

user的数据也可以来自前端

public class Sysuser {
    private User user		//异步返回的对象需要是成员变量;
    private String msg;

    public String test4(){
        user=new Sysuser();
        return "testajax";
    }
 }

给成员变量的对象赋值,使用 user.uname这样的方式

http://localhost:8080/sys/user_test4?user.uname=bom&user.uage=22

在这里插入图片描述

文件上传

写个页面

<form action="user_uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="jl">
        <button>上传</button>
    </form>

对应的action方法

File 对应input表单元素的name;
ContentType为表单元素名+ContentType,是文件的mime-type类型;
FileName为表单元素名+FileName,是真文件名;

public class Sysuser {
    private File jl;        //文件数据   表单元素名
    private String jlContentType;   //文件mime-type类型  固定格式
    private String jlFileName;   //文件名   固定格式

    public String uploadFile(){
        System.out.println(jlContentType);
        System.out.println(jlFileName);
        //获取保存路径
        String path=ServletActionContext.getServletContext().getRealPath("/upload");
        File uploadFile=new File(path);
        if(!uploadFile.exists()){
            uploadFile.mkdirs();
        }
		//将文件剪切到指定位置
        File target=new File(uploadFile+jlFileName);
        jl.renameTo(target);    
        return "show";
    }
  }

配置xml
暂时先就把文件名传回去

    <result name="show" type="json">
        <param name="root">jlFileName</param>
    </result>

上传
上传后传回了文件名
在这里插入图片描述
文件被上传到了项目目录内
在这里插入图片描述

拦截器

写一个拦截器类

public class LoginInterceptor extends MethodFilterInterceptor {
    @Override
    protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
        System.out.println("前置操作");
        actionInvocation.invoke();
        System.out.println("后置操作");
        return null;
    }
}

在xml中配置此过滤器
要同时加入默认过滤器


    <package name="syspackage" namespace="/sys" extends="json-default" strict-method-invocation="false">
        <interceptors>
        	<!--								class  路径  如果在包内要加上包名-->
            <interceptor name="LoginInterceptor " class="Interceptor"></interceptor>
        </interceptors>

        <action name="user_*" class="Sysuser" method="{1}">
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <interceptor-ref name="loginInterceptor"></interceptor-ref>
            
            <!--限制文件上传大小 限制上传文件的后缀名 -->
            <param name="fileUpload.maximumSize">2048</param>
            <param name="fileUpload.allowedExtensions">jpg,bmp,png</param>
           ...

整合

为了便于维护,可以在每个包内建struts2-config.xml,再引入到struts2.xml中

struts2.xml

<struts>
    <!--开启动态方法调用,针对于包禁止严格方法调用-->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

    <!--各模块有自己的xml,统一包含到总得struts.xml -->
    <include file="com\sysuer\struts-config.xml"></include>
    <!--可以引入多个-->

</struts>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值