首页 > 其他分享 >Spring+struts+ibatis(一)环境准备工作

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

时间:2022-11-29 14:05:01浏览次数:59  
标签:String Spring struts ibatis ex SystemException new import public

首先我们先了解几个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)。


 一、环境准备

    首先我们要建好不同的包,以及核心文件的存放位置,如下所示:

Spring+struts+ibatis(一)环境准备工作_2.5.1 ssh

Spring+struts+ibatis(一)环境准备工作_2.5.1 ssh_02

上面就是我们配置的包的位置信息,这里你可以自己定义出文件的位置,这个是公司一般的搭建教程,下面我们一步一步的解释我们搭建这些有什么用:

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

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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文件

<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Spring中数据库配置 -->
<import resource="systemManage/spring_sys_dataSourse.xml" />

</beans>

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

spring_sys_dataSource.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<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文件的修改

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<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

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

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 文件上传的限制类

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的学习笔记哦!如果我的文档做的很好的话,记住我,或者关注我,​​少帅的博客​​!还有就是我还是一名研究生,还没找到工作,如果您有好工作可以向我推荐哦。



作者:少帅


标签:String,Spring,struts,ibatis,ex,SystemException,new,import,public
From: https://blog.51cto.com/u_15683012/5894912

相关文章

  • iBATIS 3 试用手记 - The FUTURE
    iBATIS3试用手记-TheFUTURE-  iBATIS以其对SQL控制的灵活性而受到许多大型项目的青睐,它不像Hibernate那样是完全面向对象的,iBATIS是一个半自动化的O/RMappin......
  • ibatis参数传递小技巧 - 疯狂的菠菜
    ibatis参数传递小技巧-疯狂的菠菜-ITeye技术网站使用ibatis操作数据库的时候,如果这个操作需要一些参数,一般我们会使用map将这些参数封装起来,然后调用SqlMapClie......
  • spring mvc获取路径参数的几种方式
    springmvc获取路径参数的几种方式 SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request......
  • Spring mvc 返回json格式 - 龙企阁
    第一次使用springmvc,在此也算是记录一下以防忘记,希望有经验的朋友指出不足的地方一、使用maven管理jar。<dependency><groupId>org.codehaus.jackson</groupId><artif......
  • spring中依赖注入与aop讲解
    一、依赖注入这个属于IOC依赖注入,也叫控制反转,IOC是说类的实例由容器产生,而不是我们用new的方式创建实例,控制端发生了改变所以叫控制反转。<?xmlversion="1.0"encoding="U......
  • SpringCloud Alibaba(四) - Nacos 配置中心
    1、环境搭建1.1依赖<!--nacos注册中心注解@EnableDiscoveryClient--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-......
  • SpringMVC异常处理
    异常处理方式* 配置简单异常处理器SimpleMappingExceptionResolver* 配置自定义异常处理器自定义异常处理步骤* 创建异常处理器实现HandlerExceptio......
  • SpringBoot 实际项目开发中工厂模式的巧妙使用
    简单工厂模式:     简单工厂模式是创建型模式,创建型模式顾名思义,也就是说在创建对象的时候,遇到了瓶颈才会选择的设计模式。那么该什么情况使用呢。  简单工厂模式......
  • Spring Boot测试
    SpringBoot测试一、了解单元测试单元测试(UnitTest)是为了检验程序的正确性。一个单元可能是单个程序、类、对象、方法等,它是应用程序的最小可测试部件。单元测试的必......
  • SpringBoot 2.4.0版本后解决跨域问题
    packagecom.atguigu.gulimall.gateway.config;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;impor......