struts2 一个简洁的struts.xml

struts2 一个简洁的struts.xml

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<constant name="struts.ui.theme" value="simple"></constant>

	<package name="rx" extends="struts-default" namespace="/*">
		<action name="*_*" class="{1}Action" method="{2}">
			<result name="success">${successResultValue}</result>
			<result name="redirect" type="redirectAction" >${redirectResultValue}</result>
		</action>
	</package>
</struts>    

BaseAction.java

package com.yl.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;


public class BaseAction extends ActionSupport {

	/**
	 * 序列化ID
	 */
	private static final long serialVersionUID = 1L;

	protected String successResultValue;

	public String getSuccessResultValue() {
		return successResultValue;
	}

	public void setSuccessResultValue(String successResultValue) {
		this.successResultValue = successResultValue;
	}

	protected String redirectResultValue;

	public String getRedirectResultValue() {
		return redirectResultValue;
	}

	public void setRedirectResultValue(String redirectResultValue) {
		this.redirectResultValue = redirectResultValue;
	}

	protected String chainResultValue;

	public String getChainResultValue() {
		return chainResultValue;
	}

	public void setChainResultValue(String chainResultValue) {
		this.chainResultValue = chainResultValue;
	}

	/**
	 * 返回request对象
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 返回response对象
	 * 
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 返回session对象
	 * 
	 * @return
	 */
	protected HttpSession getSession() {
		return getRequest().getSession();
	}
}

一个样例action:

package com.yl.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.yl.biz.ImgBiz;
import com.yl.config.SysConfig;
import com.yl.cons.UploadResult;
import com.yl.entity.Img;
import com.yl.util.CipherUtil;

@Component("imgAction")
@Scope("prototype")
/**
 * 图片Action
 */
public class ImgAction extends BaseAction {

	/**
	 * 序列化ID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 路径
	 */
	private File upload;

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	/**
	 * 图片实体
	 */
	private Img img;

	public Img getImg() {
		return img;
	}

	public void setImg(Img img) {
		this.img = img;
	}

	/**
	 * 注入
	 */
	@SuppressWarnings("unused")
	@Resource(name = "imgBiz")
	private ImgBiz imgBiz;

	/**
	 * 图片上传
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String uploadFile() {
		@SuppressWarnings("unused")
		String paths = getRequest().getRealPath("/");
		// 推断路径是否为空
		if (this.upload == null || !this.upload.isFile()
				|| !this.upload.canRead()) {
			this.addActionError(UploadResult.NULLFILE.getTitle());
			return SUCCESS;
		}
		try {
			FileInputStream fis = new FileInputStream(this.upload);
			// 获得图片大小
			int fileSize = fis.available();
			// 推断图片大小
			if (fileSize > SysConfig.MAX_FILE_SIZE) {
				this.addActionError(UploadResult.TooLargeFile.getTitle());
			} else {
				// 保存路径
				String path = SysConfig.PUBLIC_PATH;
				// 获取图片名字
				String fileName = this.upload.getName();
				// 推断是否有点
				if (!fileName.contains(".")) {
					this.addActionError(UploadResult.NOTIMG.getTitle());
				}
				// 截取文件类型
				fileName = fileName.substring(fileName.lastIndexOf("."));
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss aa");
				// 从新给图片命名
				fileName = CipherUtil.md5Encoding(sdf.format(new Date()))
						+ fileName;
				// 保存图片路径+图片名字
				fileName = path + "\\" + fileName;
				// New一个新的地址.
				File file = new File(fileName);
				// 输出图片到新的地址
				FileOutputStream fos = new FileOutputStream(file);
				int c;
				byte b[] = new byte[4 * 1024];
				while ((c = fis.read(b)) != -1) {
					fos.write(b, 0, c);
				}
				// 关闭相关操作
				fos.flush();
				fis.close();
				// 保存成功信息
				this.addActionError(UploadResult.SUCCESS.getTitle());
			}
		} catch (FileNotFoundException e) {
			// 保存失败信息
			this.addActionError(UploadResult.NULLFILE.getTitle());
			e.printStackTrace();
		} catch (IOException e) {
			// 保存失败信息
			this.addActionError(UploadResult.UPLOADFAIL.getTitle());
			e.printStackTrace();
		}
		// 设置返回页面
		setSuccessResultValue("/index.jsp");
		return SUCCESS;

	}

}

常量:

package com.yl.config;


import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.InitializingBean;

/**
 * 图片系统类
 * 
 */
public class SysConfig implements InitializingBean {

	public static Boolean IS_DEBUG = true;
	

	/**
	 * 上传图片大小控制
	 */
	public static int MAX_FILE_SIZE = 1024 * 1024 * 100;

	/**
	 * 上传图片路径控制
	 */
	
	@SuppressWarnings("deprecation")
	public static String PUBLIC_PATH = ServletActionContext.getRequest().getRealPath("/") + "upload";

	private SysConfig() {
	}

	public static boolean isDebug() {
		return IS_DEBUG != null && IS_DEBUG;
	}

	public void setIS_DEBUG(Boolean iS_DEBUG) {
		IS_DEBUG = iS_DEBUG;
	}

	public void afterPropertiesSet() throws Exception {
	}
}

一个错误的结果enum封装,使用见action:

package com.yl.cons;

/**
 * 上传返回标志
 * 
 */
public enum UploadResult {
	SUCCESS((short) 0, "成功"), NULLFILE((short) 1, "找不到文件"), NOTIMG((short) 2,
			"非图片文件"), UPLOADFAIL((short) 3, "上传失败"), TooLargeFile((short) 4,
			"文件过大");
	/**
	 * 错误类型
	 */
	private short type;

	/**
	 * 错误名称
	 */
	private String title;

	private UploadResult(short type, String title) {
		this.type = type;
		this.title = title;
	}

	public short getType() {
		return type;
	}

	public String getTitle() {
		return title;
	}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118278.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java中Map的用法

    java中Map的用法Map是java中的接口,Map.Entry是Map的一个内部接口。Map提供了一些常用方法,如keySet()、entrySet()等方法。keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。Map<Stri

    2022年7月9日
    19
  • 深入理解 MySQL 事务:隔离级别、ACID 特性及其实现原理

    深入理解 MySQL 事务:隔离级别、ACID 特性及其实现原理什么是事务?事务(`Transaction`),一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元。事务通常由高级数据库操作语言或编程语言(如SQL,C++或Java)书写的用户程序的执行所引起,并用形如`begintransaction`和`endtransaction`语句(或函数调用)来界定。事务由事务开始(`begintransaction`)和事务结束(`endtransaction`)之间执行的全部操作组成。

    2022年5月26日
    26
  • cholesky分解_java toarray方法

    cholesky分解_java toarray方法接着LU分解继续往下,就会发展出很多相关但是并不完全一样的矩阵分解,最后对于对称正定矩阵,我们则可以给出非常有用的cholesky分解。这些分解的来源就在于矩阵本身存在的特殊的结构。对于矩阵A,如果没有任何的特殊结构,那么可以给出A=L*U分解,其中L是下三角矩阵且对角线全部为1,U是上三角矩阵但是对角线的值任意,将U正规化成对角线为1的矩阵,产生分解A=L*D*U,D为对角矩阵。如果A为对…

    2022年10月24日
    0
  • Http状态码406(Not Acceptable) 错误问题解决方法

    Http状态码406(Not Acceptable) 错误问题解决方法状态码406:HTTP协议状态码的一种,表示无法使用请求的内容特性来响应请求的网页。说白了就是后台的返回结果前台无法解析就报406错误。示例代码中请求代码,后台代码均正常,且有返回信息。如下图:$.ajax({url:’http://localhost:8080/findDsrwByDsrwid’,type:’post’,…

    2022年6月16日
    216
  • linux yum源配置文件_yum源配置文件详解

    linux yum源配置文件_yum源配置文件详解linux配置yum源的三种方法

    2022年8月13日
    3
  • 项目中常用的MySQL 优化

    项目中常用的MySQL 优化

    2021年7月5日
    82

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号