Spring+struts+ibatis(一)环境准备工作

首先我们先了解几个jar包的作用和一些未曾见过的接口和类
  • xwork-2.0.7.jar
XWork是一个标准的Command模式实现,并且完全从web层脱离出来。Xwork提供了很多核心功能:前端拦截机(interceptor),运行时表单属性验证,类型转换,强大的表达式语言(OGNL – the Object Graph Navigation Language),IoC(Inversion of Control反转控制)容器等。
其目的是:创建一个泛化的、可重用且可扩展的命令模式框架,而不是一个特定在某个领域使用的框架。
  • ServletResponseAware接口
此接口属于struts-core.jar中的接口,隶属于org.apache.struts2.interceptor.ServletResponseAware
详情请看我的这篇博客:

在Action类中获得HttpServletResponse对象的四种方法

  • commons-dbpc.jar
这里我们用到数据库连接池
主流数据库连接池之一(DBCP、c3p0、proxool),单独使用DBCP需要使用commons-dbpc.jar、commons-collections.jar、commons-pool.jar三个包,都可以在Apache组织的网站上下到(commons.apache.org)。

 一、环境准备​

    首先我们要建好不同的包,以及核心文件的存放位置,如下所示:
上面就是我们配置的包的位置信息,这里你可以自己定义出文件的位置,这个是公司一般的搭建教程,下面我们一步一步的解释我们搭建这些有什么用:

1、添加上图对应的jar包文件,一个不能少哦

2、编辑web.xml文件,将spring和struts添加进来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
   
    <display-name>Struts 2.0 Hello World</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
    </context-param>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
</web-app>

3、我们在项目中建立核心的config文件,用于存放spring和struts文件及其他的配置文件

applicationContext.xml文件

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="GBK"?>
     
    <!-- Spring中数据库配置 -->
    <import resource="systemManage/spring_sys_dataSourse.xml" />
 
</beans>

为了更好的管理和有层次,我们将数据库的连接文件放在config/systemManage/spring_sys_dataSource.xml文件中

spring_sys_dataSource.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
 
<beans>
 
    <!-- 配置数据库测试 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"    destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/tracesystem" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>
 
</beans>

4、struts.xml文件的修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
         
<struts>
 
     <constant name="struts.ui.theme" value="simple"/>
     <constant name="struts.i18n.encoding " value="UTF-8"/>
     <constant name="struts.objectFactory" value="spring" />
     <constant name="struts.action.extension" value="action,do"/>
      
     <!-- 设置文件上传最大size -->
     <constant name="struts.multipart.maxSize" value="20701096" />
      
     <!-- 抽象package -->
     <package name="globalResult" extends="struts-default" abstract="true">
         
     <!-- 拦截器 定义 -->
     <interceptors>
        <interceptor name="checkException" class="com.wang.commons.exception.ExceptionInterceptor" />
        <!-- 定义一个拦截器栈 -->
        <interceptor-stack name="mydefault">
                <interceptor-ref name="defaultStack" />
                <interceptor-ref name="checkException" />
            </interceptor-stack>
        </interceptors>
        <!-- 此默认interceptor是针对所有action的 -->
        <!-- 如果某个action中引入了interceptor, 则在这个action中此默认interceptor就会失效 -->
        <default-interceptor-ref name="mydefault" />
        <global-results>
            <result name="error">/pages/common/errorPage.jsp</result>
        </global-results>
        <global-exception-mappings>
            <exception-mapping result="error" exception="com.wang.commons.exception.SystemException"></exception-mapping>
        </global-exception-mappings>
 
        <action name ="fileUploadAction" class ="com.wang.action.upload.FileUploadAction">
            <interceptor-ref name="fileUpload"
                <param name="allowedTypes"
                 image/bmp,image/png,image/gif,image/pjpeg,image/jpg,image/JPG,image/jpeg,audio/x-mpeg  
               </param>      
               <param name="maximumSize">102400000</param
           </interceptor-ref>
        </action >
    </package>
         
     
</struts>

这里我想说的是,我在这里配置完全之后,去让tomcat加载这些配置的核心文件时,出现了一个下列的错误:

启动tomcat出现:警告: Settings: Could not parse struts.locale setting, substituting default VM locale

这时候该怎么办呢?我上网查了些文档说明,

这是默认语言环境没有配置:有两种方法可以解决
第一种:在WEB-INF/struts.properties或者src/struts.properties文件中如下配置:
struts.locale=en_GB
第二种:或者在struts.xml中如下配置;
<constant name="struts.locale" value="en_GB" /> 
使用是UTF-8在struts.properties文件中配置:
struts.locale=en_UTF-8 或 struts.locale=zh_UTF-8。这里建议第一种,第二种死活不行!

5、对应struts中的异常拦截类

ExceptionInterceptor.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.wang.commons.exception;
 
import java.io.IOException;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
 
public class ExceptionInterceptor extends AbstractInterceptor {
 
    public String intercept(ActionInvocation actionInvocation) throws Exception {
 
       String result = "";
 
       try {
 
           result = actionInvocation.invoke();
 
       } catch (DataAccessException ex) {
 
           throw new SystemException("数据库操作失败!");
 
       } catch (NullPointerException ex) {
 
           throw new SystemException("空指针,调用了未经初始化或者是不存在的对象!");
 
       } catch (IOException ex) {
 
           throw new SystemException("IO读写异常!");
 
       } catch (ClassNotFoundException ex) {
 
           throw new SystemException("指定的类不存在!");
 
       } catch (ArithmeticException ex) {
 
           throw new SystemException("数学运算异常!");
 
       } catch (ArrayIndexOutOfBoundsException ex) {
 
           throw new SystemException("数组下标越界!");
 
       } catch (IllegalArgumentException ex) {
 
           throw new SystemException("调用方法的参数错误!");
 
       } catch (ClassCastException ex) {
 
           throw new SystemException("类型强制转换错误!");
 
       } catch (SecurityException ex) {
 
           throw new SystemException("违背安全原则异常!");
 
       } catch (SQLException ex) {
 
           throw new SystemException("操作数据库异常!");
 
       } catch (NoSuchMethodError ex) {
 
           throw new SystemException("调用了未定义的方法!");
 
       } catch (InternalError ex) {
 
           throw new SystemException("Java虚拟机发生了内部错误!");
 
       } catch (Exception ex) {
 
           throw new SystemException("程序内部错误,操作失败!");
 
       }
 
       return result;
 
    }
 
}

SystemException.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.wang.commons.exception;
 
public class SystemException extends RuntimeException {
 
    public SystemException(String frdMessage) {
        super(createFriendlyErrMsg(frdMessage));
    }
 
    public SystemException(Throwable throwable){
        super(throwable);
    }
 
    public SystemException(Throwable throwable, String frdMessage){
       super(throwable);
    }
 
  
    /**
     * 创建友好的报错信息
     * */
    private static String createFriendlyErrMsg(String msgBody) {
 
       String prefixStr = "抱歉,";
       String suffixStr = "请稍后再试或与管理员联系!";
        
       StringBuffer friendlyErrMsg = new StringBuffer();
       friendlyErrMsg.append(prefixStr);
       friendlyErrMsg.append(msgBody);
       friendlyErrMsg.append(suffixStr);
 
       return friendlyErrMsg.toString();
 
    }
 
}

FileUploadAction.java 文件上传的限制类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package com.wang.action.upload;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletResponseAware;
 
import com.opensymphony.xwork2.ActionSupport;
 
 
 
/**
 * @author shenjw
 
 */
public class FileUploadAction extends ActionSupport implements
        ServletResponseAware {
 
    //private static final Logger log = Logger.getLogger(FileUploadAction.class);
 
    private static final long serialVersionUID = 6154973269813444328L;
 
    private File addfile;
 
    private String addfileContentType;
 
    private String addfileFileName;
 
    private String fileName;
 
    private HttpServletResponse response;
 
 
    private String uploadFlag;
 
    public String getUploadFlag() {
        return uploadFlag;
    }
 
    public void setUploadFlag(String uploadFlag) {
        this.uploadFlag = uploadFlag;
    }
 
    public FileUploadAction() {
 
    }
 
     
 
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
 
    }
 
    public File getAddfile() {
        return addfile;
    }
 
    public void setAddfile(File addfile) {
        this.addfile = addfile;
    }
 
    public String getAddfileContentType() {
        return addfileContentType;
    }
 
    public void setAddfileContentType(String addfileContentType) {
        this.addfileContentType = addfileContentType;
    }
 
    public String getAddfileFileName() {
        return addfileFileName;
    }
 
    public void setAddfileFileName(String addfileFileName) {
        this.addfileFileName = addfileFileName;
    }
 
    /**
     * 增加了从EXT上传控件上传文件的标志参数uploadFlag,
     * 从EXT控件上传文件时addfileContentType无论传什么文件,
     * 类型都是application/octet-stream,所以写了一个根据扩展名取文件类型的方法
     * @author huangsq
     * @date   2010-7-12
     */
    public String execute() {
        String tempFileId = "";
        InputStream is = null;
        try {
            is = new FileInputStream(addfile);
            int len = (new Long(addfile.length()).intValue());
            byte[] filedata = new byte[len];
            is.read(filedata);
            System.out.println("---------------"+len);
            //file.setFileContent(filedata);
            String fName = URLDecoder.decode(fileName, "UTF-8");
            //file.setFileName(fName);
             
             
//          if(uploadFlag != null){
//              file.setFileContentType(getFileContentType(fName));
//          }else{
//              file.setFileContentType(addfileContentType);
//          }
             
            back(response, true, tempFileId);
        } catch (Exception ex) {
            back(response, false, ex.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        return NONE;
    }
    /**
     * EXT上传控件返回的参数为一个json的数组,原控件返回的是一段html的代码
     * @param response
     * @param success
     * @param message
     */
    private void back(HttpServletResponse response, boolean success,
            String message) {
        //response.setContentType(StringTools.CONTENT_TYPE);
        PrintWriter out = null;
        try {
            out = new PrintWriter(response.getOutputStream());
            if (uploadFlag == null) {
 
                out.println("<html>");
                out.println("<body>");
                out.println("<xml id='result'");
                out.println(" success="" + success + "">");
                out.println(message);
                out.println("</xml>");
                out.println("<script>");
                out.println("var doc = document.getElementById("result");");
                out.println("parent.fileBack(doc);");
                out.println("</script>");
                out.println("</body></html>");
            } else {
                out.println("{success:true,fileId:'" + message + "'}");
            }
        } catch (IOException ex) {
            //log.error(ex.toString(), ex);
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }
 
    public String getFileName() {
        return fileName;
    }
 
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    //按文件名得到文件扩展类型
    public String getFileContentType(String fileName){
        String fileType="application/octet-stream";
        if(fileName==null){
            return fileType;
        }
        int extIndex=fileName.lastIndexOf(".");
        if(extIndex!=-1){
            String extName=fileName.substring(extIndex);
            if(extName!=null){
                fileType=(String) FILE_COMNTENTTYPE.get(extName.toLowerCase());
            }
        }
        return fileType;
    }
    private static Map FILE_COMNTENTTYPE=new HashMap();
    static{
        FILE_COMNTENTTYPE.put(".doc","application/msword");
        FILE_COMNTENTTYPE.put(".xls","application/vnd.ms-excel");
        FILE_COMNTENTTYPE.put(".txt","text/plain");
        FILE_COMNTENTTYPE.put(".htm","text/html");
        FILE_COMNTENTTYPE.put(".html","text/html");
        FILE_COMNTENTTYPE.put(".ppt","application/vnd.ms-powerpoint");
        FILE_COMNTENTTYPE.put(".jpg","image/jpeg");
        FILE_COMNTENTTYPE.put(".jpeg","image/jpeg");
        FILE_COMNTENTTYPE.put(".exe","application/x-msdownload");
        FILE_COMNTENTTYPE.put(".png","image/png");
        FILE_COMNTENTTYPE.put(".xml","text/xml");
         
    }
     
     
}


这里我们就先说到这里,这是所有事情的开始,倘若没有这个技巧搭建所需的,我们将不能得到我们的结果。下一讲中我将开始spring的学习笔记哦!如果我的文档做的很好的话,记住我,或者关注我,少帅的博客!还有就是我还是一名研究生,还没找到工作,如果您有好工作可以向我推荐哦。











原文地址:https://www.cnblogs.com/wang3680/p/3459851.html