欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring与iBATIS整合及Struts1文件的上传与下载1

程序员文章站 2022-04-05 14:51:05
...

案例是关于联系人信息列表展示,使用spring+struts+ibatis实现,附件有整个工程文件

 

1.联系人表的创建,使用的是MySQL

CREATE TABLE `contact` (
  `id` int(11) NOT NULL auto_increment,
  `firstName` varchar(20) default NULL,
  `lastName` varchar(20) default NULL,
  `email` varchar(20) default NULL,
  `imgPath` varchar(200) default 'None',
  `imgFileName` varchar(200) default 'None',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=gbk;
 

 

2.联系人的表的映射

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
          PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
          "http://ibatis.apache.org/dtd/sql-map-2.dtd">
      
<sqlMap namespace="Contact">
    <!--- Showing data by ID -->
    <typeAlias alias="contact" type="cn.com.servyou.ibatis_learn.entity.Contact"/>
    <typeAlias alias="address" type="cn.com.servyou.ibatis_learn.entity.Address"/>
 
    <!-- Contact映射 -->
    <resultMap id="get_user_result" class="contact">   
        <result property="id" column="id"/>    
        <result property="firstName" column="firstName"/>   
        <result property="lastName" column="lastName"/>   
        <result property="email" column="email"/>
        <result property="imgPath" column="imgPath"/>
        <result property="imgFileName" column="imgFileName"/>
        <result property="addresses" column="id" select="Contact.getAddressesByContactId"/>
    </resultMap>      
   
    <!-- Address映射 -->
    <!-- 
    <resultMap id="get_address_result" class="address">
        <result property="id" column="id"/>
        <result property="addressName" column="addressName"/>
        <result property="zipCode" column="zipCode"/>
        <result property="contactId" column="contact_id"/>
    </resultMap>
    -->   
     
         
    <select id="getContactByLastName" resultClass="contact" resultMap="get_user_result" parameterClass="java.lang.String">         
        select * from contact    
        where lastName = #lastName#
    </select>  
   
    <select id="getAllContact" resultClass="contact" resultMap="get_user_result">         
        select * from contact    
    </select>  
      
     <select id="getAddressesByContactId" resultClass="address"  parameterClass="int" >
        select * from address
        where contact_id = #contact_id# 
    </select>  
        
       
    <insert id="insert" parameterClass="cn.com.servyou.ibatis_learn.entity.Contact">          
        insert into  contact  
                       (firstName,lastName,email,imgPath,imgFileName)          
        values
                    (#firstName#, #lastName#, #email#,#imgPath#,#imgFileName#)          
    </insert>    
   
    <delete id="delete" parameterClass="cn.com.servyou.ibatis_learn.entity.Contact">
        delete from contact
        where lastName = #lastName#
    </delete>  
   
    <delete id="deleteContactByLastName" parameterClass="java.lang.String">
        delete from contact         
        where lastName = #value#
    </delete>  
       
    <update id="update" parameterClass="java.lang.Integer">
            update  contact  
                    set email = 'ok@hotmail.com'
            where id = #id#  
    </update>
     
    <update id="updateByLastName" parameterClass="contact">
        update contact
                set email = #email#
            where lastName = #lastName#
    </update>
</sqlMap>   
 

 

 

3.关于联系人的Dao,与Service的实现类的代码就省略了,下面只是给出接口的定义

IContactDao:

 

public interface IContactDao  {
    public List<Contact> findAll() throws DAOException;
   
    public Contact findByLastName(String lastName) throws DAOException;
   
    public void insert(Contact contact) throws DAOException;
   
    public void delete(Contact contact) throws DAOException;
   
    public void deleteByLastName(String lastName) throws DAOException;
     
    public void updateById(Integer id) throws DAOException;
   
    public void updateByLastName(Contact contact) throws DAOException;
   
}
 

 

 

IContactService:

 

public interface IContactService {
    public List<Contact> getAll() throws ServiceException;

    public void addContact(Contact contact) throws ServiceException;

    public void deleteContact(Contact contact) throws ServiceException;
   
    public void deleteContactByLastName(String lastName) throws ServiceException;

    public void updateContactById(Integer id) throws ServiceException;

    public void updateContactByLastName(Contact contact)
            throws ServiceException;

    public Contact findContactByLastName(String lastName)
            throws ServiceException;
} 
 

 

 

4.Spring配置文件

 

 此案例将配置文件分为四个:applicationContext.xml,applicationContext-dao.xml,applicationContext-service.xml,applicationContext-action.xml

 

   1) applicationContext.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     	http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
  
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close"> 
		<property name="driverClassName" 
			value="${dataSource.driverClassName}">
		</property>   
		<property name="url" value="${dataSource.url}"></property>
		<property name="username" value="${datasource.username}"></property>
		<property name="password" value="${dataSource.password}"></property>
	</bean>  
      
	<!-- WebLogicNativeJdbcExtractor,WebSphereNativeJdbcExtractor,C3P0NativeJdbcExtractor,
		CommonsDbcpNativeJdbcExtractor,JBossNativeJdbcExtractor,NativeJdbcExtractor,SimpleNativeJdbcExtractor
	-->
	<bean id="nativeJdbcExtractor"
		class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"
		lazy-init="true" />

	<bean id="oracleLobHandler"
		class="org.springframework.jdbc.support.lob.OracleLobHandler"
		lazy-init="true">
		<property name="nativeJdbcExtractor">
			<ref local="nativeJdbcExtractor" />
		</property>
	</bean>

	<bean id="sqlMapClient"
		class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation"
			value="classpath:config-sqlmap.xml" />
		<property name="dataSource" ref="dataSource" />
		<property name="lobHandler">
			<ref local="oracleLobHandler" />
		</property>
	</bean> 

	<!-- 事务管理 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!--事物拦截器 -->
	<bean id="transactionInterceptor"
		class="org.springframework.transaction.interceptor.TransactionInterceptor">
		<property name="transactionManager" ref="transactionManager" />
		<property name="transactionAttributes">
			<props>
				<prop key="*find*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="*get*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="*query*">PROPAGATION_REQUIRED,readOnly</prop>
				<prop key="*insert*">PROPAGATION_REQUIRED</prop>
				<prop key="*update*">PROPAGATION_REQUIRED</prop>
				<prop key="*delete*">PROPAGATION_REQUIRED</prop>
				<prop key="*add*">PROPAGATION_REQUIRED</prop>
				<prop key="*save*">PROPAGATION_REQUIRED</prop>
				<prop key="*remove*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
	
	<!-- 指明要拦截的类的规则 -->
	<bean
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="beanNames">
			<value>*Service</value>
		</property>
		<property name="interceptorNames">
			<list>
				<value>transactionInterceptor</value>  
			</list>
		</property>
	</bean> 
	<bean
		class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
		<property name="transactionInterceptor"
			ref="transactionInterceptor" />
	</bean>
</beans>
 

   2) applicationContext-dao.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     	http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<bean id="contactDao"
		class="cn.com.servyou.ibatis_learn.dao.impl.ContactDaoIBatisImpl">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>
	<bean id="adminDao"
		class="cn.com.servyou.ibatis_learn.dao.impl.AdminDaoIBatisImpl">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>
</beans>
 

 

   3) applicationContext-service.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     	http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<bean id="contactService"
		class="cn.com.servyou.ibatis_learn.service.impl.ContactServiceImpl">
		<property name="contactDao" ref="contactDao" />
	</bean>
	<bean id="adminService"
		class="cn.com.servyou.ibatis_learn.service.impl.AdminServiceImpl">
		<property name="adminDao" ref="adminDao" />
	</bean>
</beans>

   4)applicationContext-action.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     	http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     	http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	<bean name="/addContact,/delContact,/updateContact,/queryAllContact,/downContactImg"
		class="cn.com.servyou.ibatis_learn.web.action.ContactAction">
		<property name="contactService" ref="contactService" />
	</bean>
</beans>
	

5.Struts配置文件

 

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

<struts-config>
	<data-sources/>
	<form-beans>
		<form-bean name="contactForm"
				   type="cn.com.servyou.ibatis_learn.web.form.ContactForm" />
		<form-bean name="adminForm" 
		           type="cn.com.servyou.ibatis_learn.web.form.AdminForm"/>
		<form-bean name="uploadForm" type="cn.com.servyou.ibatis_learn.web.form.UploadForm"></form-bean>
	</form-beans>
	<global-exceptions>
		<!--  <exception key="errors.exception" type="java.lang.Exception" path="/WEB-INF/pages/common/error.jsp"/>-->
	</global-exceptions>
	<global-forwards /> 
	<action-mappings>
	<!-- 联系人管理Action开始 -->
		<action path="/addContact" 
				type="org.springframework.web.struts.DelegatingActionProxy"
				name="contactForm"
				validate="true"
				input="/queryAllContact.do"
				parameter="doAddContact"
				scope="request">
			<forward name="success"
					 path="/WEB-INF/pages/admin/contact_list.jsp"
					 redirect="false" />
			<forward name="failure" 
					 path="/WEB-INF/pages/common/failure.jsp" 
					 redirect="false" />
		</action>
		<action path="/delContact"  
				type="org.springframework.web.struts.DelegatingActionProxy"
				scope="request" 
				parameter="doDeleteContact">
			<forward name="success" 
					 path="/WEB-INF/pages/admin/contact_list.jsp" redirect="false" />
			<forward name="failure"          
					 path="/WEB-INF/pages/common/failure.jsp" redirect="false" />
		</action>
		<action path="/updateContact" 
				name="contactForm" 
				type="org.springframework.web.struts.DelegatingActionProxy"
				scope="request"
				parameter="doUpdateContact"
				input="/WEB-INF/pages/admin/list_contact.jsp">
			<forward name="success"
					 path="/WEB-INF/pages/common/success.jsp" 
					 redirect="false" />
			<forward name="failure"
					 path="/WEB-INF/pages/common/failure.jsp" 
					 redirect="false" />
		</action>
		<action path="/queryAllContact" 
				type="org.springframework.web.struts.DelegatingActionProxy"
				parameter="doQueryAllContact"
				scope="request">
			<forward name="success"
					 path="/WEB-INF/pages/admin/contact_list.jsp"/>
		</action>
		<action path="/downContactImg"
				type="org.springframework.web.struts.DelegatingActionProxy"
				parameter="doDownloadImgFile"
				scope="request">
		</action>
		<!-- 联系人管理Action结束 -->
		
		<!-- 管理员Action开始 -->
		<!-- input应该理解为是表单验证失败后转向的页面 -->
		<action path="/login" 
				type="cn.com.servyou.ibatis_learn.web.action.AdminAction"
				name="adminForm"
				scope="request">
				<forward name="success" path="/WEB-INF/pages/admin/contact_list.jsp"></forward>
				<forward name="failure" path="/WEB-INF/pages/common/failure.jsp"></forward>
		</action>      
		<action path="/contact_detail"
		        type="cn.com.servyou.ibatis_learn.web.action.ContactDetailAction"
		        scope="request">
		        <forward name="success" path="/WEB-INF/pages/admin/contact_detail.jsp"></forward>
		        <forward name="failure" path="/WEB-INF/pages/common/failure.jsp"></forward>
		        </action>
		<!-- 管理员Action结束 -->	    
	</action-mappings>
	
	<!-- 资源文件开始 -->
	<message-resources parameter="cn.com.servyou.ibatis_learn.ApplicationResource" />
	<!-- 资源文件结束 -->
	
	<!-- spring 2.5.5 ContextLoaderPlugIn在spring-webmvc-struts.jar中 -->
	<!-- Struts插件开始 -->
	<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> 
		<set-property property="contextConfigLocation" 
					  value="/WEB-INF/classes/context/applicationContext.xml,/WEB-INF/classes/context/applicationContext-action.xml,/WEB-INF/classes/context/applicationContext-dao.xml,/WEB-INF/classes/context/applicationContext-service.xml"/>
	</plug-in>
	<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
   		<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
	</plug-in>
	<!-- Struts插件结束 -->
</struts-config>

 

  6.web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name>spring_ibatis_web</display-name>
	<description>
		This project description " how spring and ibatis integration
	</description>
	<!-- 使用ContextLoaderListener加载Spring配置文件,创建Spring容器 -->
	<!--  
		<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
		/WEB-INF/classes/context/applicationContext*.xml
		</param-value> 
		</context-param> 
		<listener>  
		<listener-class>
		org.springframework.web.context.ContextLoaderListener
		</listener-class>
		</listener>
	-->
	
	<!-- struts framework 's controler start -->
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>
			org.apache.struts.action.ActionServlet
		</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
		<init-param>
			<param-name>debug</param-name>
			<param-value>3</param-value>
		</init-param>
		<init-param>
			<param-name>detail</param-name>
			<param-value>3</param-value>
		</init-param>
		<load-on-startup>0</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!-- struts framework 's controler end -->

	<!-- 编码过滤器开始 -->
	<filter>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>
			cn.com.servyou.ibatis_learn.web.filter.EncodingFilter
		</filter-class>
		<init-param>
			<description>用于为POST请求设置编码</description>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 编码过滤器开始 -->
	
	<!-- 文件上传Servlet开始 -->
	<servlet>
		<servlet-name>UploadFileServlet</servlet-name>
		<servlet-class>cn.com.servyou.ibatis_learn.web.servlet.UploadFileServlet</servlet-class>
		<init-param>
			<param-name>savePath</param-name>
			<param-value>upload</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>UploadFileServlet</servlet-name>
		<url-pattern>/uploadFile</url-pattern>
	</servlet-mapping>
	<!-- 文件上传Servlet结束 -->
	
	<!-- 判断是否已经登录的Filter开始 -->
	<filter>
		<filter-name>LoginJudgeFilter</filter-name>
		<filter-class>
			cn.com.servyou.ibatis_learn.web.filter.LoginJudgeFilter
		</filter-class>
		<init-param>
			<param-name>loginPage</param-name>
			<param-value>/login.jsp</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>LoginJudgeFilter</filter-name>
		<url-pattern>/admin/*</url-pattern>
	</filter-mapping>

	<!-- 判断是否已经登录的Filter结束 -->


	<!-- 配置session超时时间开始 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
	<!-- 配置session超时时间结束 -->
	
	<!-- 配置错误页开始 -->
	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/common/errorPage404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/common/errorPage500.jsp</location>
	</error-page>
	<error-page>
		<error-code>400</error-code>
		<location>/WEB-INF/common/errorPage400.jsp</location>
	</error-page>
	<!-- 配置错误页结束 -->
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.jsp</welcome-file>
		<welcome-file>login.jsp</welcome-file>
		<welcome-file>welcome.html</welcome-file>
		<welcome-file>welcome.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

   7.ContactForm

 

public class ContactForm extends ValidatorActionForm {
	private static final long serialVersionUID = -1671970332130779842L;

	private Integer id;

	private String firstName; 

	private String lastName;

	private String email;
	
        /**与页面的<input type="file" name="photoFile">对应,sturts1底层使用的apache的
             commons-fileupload来实现对流的封装*/
	private FormFile photoFile;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		logger.debug("get property firstName="+firstName);
		return firstName;
	}

	public void setFirstName(String firstName) {
		logger.debug("set property firstName="+firstName);
		this.firstName = firstName;
	}

	public String getLastName() {
		logger.debug("get property lastName="+lastName);
		return lastName;
	}

	public void setLastName(String lastName) {
		logger.debug("set property lastName="+lastName);
		this.lastName = lastName;
	}

	public String getEmail() {
		logger.debug("set property email="+email);
		return email;
	}

	public void setEmail(String email) {
		logger.debug("set property email="+email);
		this.email = email;
	}

  public FormFile getPhotoFile() {
    return photoFile;
  }

  public void setPhotoFile(FormFile photoFile) {
    this.photoFile = photoFile;
  }
}

   8.ContactAction

 

 

public class ContactAction extends MappingDispatchAction {
	private Logger logger = Logger.getLogger(ContactAction.class);
	private IContactService contactService;

	public IContactService getContactService() {
		return contactService;
	}

	public void setContactService(IContactService contactService) {
		this.contactService = contactService;
	}

	public ActionForward doAddContact(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Contact contact = new Contact();
		ContactForm contactForm = (ContactForm) form;
		FormFile photo = contactForm.getPhotoFile();
		String savePath = this.getServlet().getServletContext().getRealPath("/");
		//保证无论是在Windows还是Linux,或Unix,类Unix都可以部署
		savePath = System.getProperty("os.name").indexOf("Win") >= 0 ? savePath+"\\upload\\image\\":savePath+"/upload/image/";  
		File saveDir = new File(savePath);
		if(!saveDir.exists()){
		  saveDir.mkdirs();
		}
		String fileName = photo.getFileName();
		//获取文件类型
		String suffix =fileName.substring(fileName.indexOf(".")+1);
		//利用当前时间作为文件名,保证文件名的唯一性
		String destFileName = System.currentTimeMillis()+(new Random().nextInt(1000)+24)+"."+suffix;
		File dest = new File(saveDir,destFileName);
		FilesUtil.copyFile(photo.getInputStream(), dest);
		//设置图片在服务器上的存储路径,以及设置图片的文件名称
		contact.setImgPath(destFileName);
		contact.setImgFileName(fileName);
		BeanUtils.copyProperties(contact, form);
		boolean flag = false;
		ActionForward forward = mapping.findForward("failure");
		List<Contact> contacts = new ArrayList<Contact>();
		try {
			contactService.addContact(contact);
			flag = true;
			contacts = contactService.getAll();
			if(photo != null)//销毁临时文件
			  photo.destroy();
			request.setAttribute("contacts", contacts);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		forward = flag == true ? mapping.findForward("success") : forward;
		return forward;
	}
	
	   public ActionForward doDownloadImgFile(ActionMapping mapping,
           ActionForm form, HttpServletRequest request,
           HttpServletResponse response) throws Exception {
	     //联系人的lastName
	     String contactLastName = request.getParameter("contactLastName");
	     Contact contact = contactService.findContactByLastName(contactLastName);
	     String fileSavePath = getServlet().getServletContext().getRealPath("/");
	     //操作系统类型是否是Windows
	     boolean isWinSystem = System.getProperty("os.name").indexOf("Win") >= 0 ;
	     fileSavePath = fileSavePath + (isWinSystem ? "upload\\image":"upload/image"); 
	     String filePath = fileSavePath + (isWinSystem ? "\\":"/")+contact.getImgPath();
	     File imgFile = new File(filePath);
	     InputStream inputStream = new FileInputStream(imgFile);
	     OutputStream outputStream = response.getOutputStream();
	     //响应头设置附件,以二进流形式下载
	     response.setHeader("Content-Disposition",
             "attachment;filename=" +
             URLEncoder.encode(contact.getImgFileName(), "GBK"));
	     response.setContentType("application/octet-stream");
	     FilesUtil.copyFile(inputStream, outputStream);
	     return null;
	   }

	public ActionForward doDeleteContact(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.debug("enter ContactAction's doDeleteContact method ...");
		String lastName = request.getParameter("lastName");
		logger.debug(lastName);
		boolean flag = false;
		List<Contact> contacts = new ArrayList<Contact>();
		ActionForward forward = mapping.findForward("failure");
		try {
			contactService.deleteContactByLastName(lastName);
			flag = true;
			contacts = contactService.getAll();
			request.setAttribute("contacts", contacts);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		forward = flag == true ? mapping.findForward("success") : forward;
		return forward;
	}

	public ActionForward doUpdateContact(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return super.execute(mapping, form, request, response);
	}

	public ActionForward doQueryContact(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return super.execute(mapping, form, request, response);
	}

	public ActionForward doQueryAllContact(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.debug("enter ContactAction's method doQueryAllContact");
		List<Contact> contacts = new ArrayList<Contact>();
		try {
			contacts = contactService.getAll();
			request.setAttribute("contacts", contacts);
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		if (contacts != null)
			logger.debug(contacts.size());
		request.setAttribute("contacts", contacts);
		return mapping.findForward("success");
	}
}
 

   9.页面contact_list.jsp

 

 

<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@page import="java.net.URLEncoder"%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>Contact List</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<!--
			<link rel="stylesheet" type="text/css" href="styles.css">
		-->
		<link href="<%=path%>/style/jquery.multiSelect.css" rel="stylesheet" type="text/css">
		<link href="<%=path%>/style/style_default.css" rel="stylesheet" type="text/css">
		<script type="text/javascript" src="<%=path%>/js/jquery.js"></script>
<script type="text/javascript">
 	  /*获取本地上传的照片路径*/  
     function getPath(obj) {  
              if (obj) {  
                  //ie  
                  if (window.navigator.userAgent.indexOf("MSIE") >= 1) {  
                      obj.select();  
                      // IE下取得图片的本地路径  
                      return document.selection.createRange().text;  
                  }  
                  //firefox  
                  else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {  
                      if (obj.files) {  
                          // Firefox下取得的是图片的数据  
                          return obj.files.item(0).getAsDataURL();  
                      }  
                      return obj.value;  
                  }  
                  return obj.value;  
              }  
          }  
          
          /*预览照片*/  
          function previewPhoto(){  
               var picsrc=getPath(document.all.photo_select);  
               var picpreview=document.getElementById("preview");  
               if(!picsrc){   
                return  
               }  
               if(window.navigator.userAgent.indexOf("MSIE") >= 1) {  
                    if(picpreview) {  
                     try{  
                            picpreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = picsrc;  
                           }catch(ex){  
                      alert("文件路径非法,请重新选择!") ;  
                      return false;  
                     }  
                }else{   
                   picpreview.innerHTML="<img src='"+picsrc+"' />";  
                }  
              }  
          }  
          
         /*校验图片大小*/  
          function checkPhoto(){  
              var photo = getPath(document.all.photo_select);  
              if(!photo){  
                  alert("请选择一个本地图片文件!");  
                  return;  
              }  
              var imgObj = new Image();  
              imgObj.src = photo;  
              var width = imgObj.width;  
              var height = imgObj.height;  
              ///获取正确的图片尺寸大小,兼容ie6、7、8  
              try{  
                  if((typeof width=="undefined" || width==0) && (typeof height=="undefined" || height==0)){  
                     var picpreview=document.getElementById("preview");  
                     if(picpreview && picpreview.filters && picpreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src) {  
                        var tempDiv=document.createElement("div");  
                        picpreview.appendChild(tempDiv);  
                        tempDiv.style.width="10px";  
                        tempDiv.style.height="10px";  
                        tempDiv.style.diplay="none";  
                         tempDiv.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);";  
                         tempDiv.ID="previewTemp";  
                         var url=picpreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src;  
                         tempDiv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=url;  
                        width=tempDiv.offsetWidth;  
                        height=tempDiv.offsetHeight;  
                        picpreview.removeChild(tempDiv);  
                        }  
                     }  
                 }  
                 catch(e){  
                 }  
              
              if(photo.toLowerCase().indexOf("http://") > - 1){  
              alert("必须提供本机硬盘上的图片上传!");  
              return false;  
             }  
             alert("照片宽:"+width+"像素 \n照片高:"+height+"像素");  
         }  
</script>  
	</head>

	<body>
		<table style="border-color: aqua" border="1" cellpadding="2"
			align="center">
			<tbody>
				<tr>
					<th>
						联系人firstName
					</th>
					<th>
						联系人lastName
					</th>
					<th>
						联系人email
					</th>
					<th>
						联系人头像
					<th>
				</tr>
				<logic:iterate id="contact" name="contacts" indexId="index">
					<tr>
						<td>
							<bean:write name="contact" property="firstName" />
							<a
								href="<%=path%>/contact_detail.do?firstName=<bean:write name="contact" property="firstName"/>"></a>
						</td>
						<td>
							&nbsp;
							<bean:write name="contact" property="lastName" />
							<a
								href="<%=path%>/contact_detail.do?lastName=<bean:write name="contact" property="lastName"/>"></a>
						</td>
						<td>
							&nbsp;
							<font style="color: red;"><bean:write name="contact"
									property="email" /> </font>
						</td>
						<td>
							<div id="contact_Img">
								<img src="<%=path%>/upload/image/<bean:write name="contact" property="imgPath"/>" width="200" height="200">
							</div>
							<br>
							<a href="<%=path%>/downContactImg.do?contactLastName=<bean:write name="contact" property="lastName"/>">下载图片</a>
						</td>
						<td>
							<input type="hidden" id="contactName" value="<bean:write name="contact" property="lastName" />">
							<a href="<%=path%>/delContact.do?lastName=<bean:write name="contact" property="lastName" />">删除</a>
						</td>
					</tr>
				</logic:iterate>
			</tbody>
		</table>

		<hr>
		<html:javascript formName="/addContact"/>
		<html:form action="/addContact" method="post"  enctype="multipart/form-data" onsubmit="return validateContactForm(this);">
			<table style="elevation: level" border="1" cellspacing="1"
				cellpadding="1" align="center">
				<thead>
					<tr>
						<td colspan="2" align="center">
							添加联系人
						</td>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td align="center">
							联系人firstName
						</td>
						<td>
							<html:text property="firstName" name="contactForm"></html:text><br/>
							<span style="color: red;"><html:errors  property="firstName"/></span>
						</td>
					</tr>
					<tr>
						<td align="center">
							联系人lasttName
						</td>
						<td>
							<html:text property="lastName" name="contactForm"></html:text><br/>
							<span style="color: red;"><html:errors  property="lastName"/></span>
						</td>
					</tr>
					<tr>
						<td align="center">
							联系人email
						</td>
						<td>
							<html:text property="email" name="contactForm"></html:text><br/>
							<span style="color: red;"><html:errors  property="email"/></span>
						</td>
					</tr>
					<TR>
                		<TD  class="Edit_item">照片:</TD>
                		<TD  class="Edit_content">
                		<div id="preview" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); width:160px;height:180px;border:solid 1px black;">  
                		</div>
              			<br>
                  		<html:file property="photoFile" styleId="photo_select" styleClass="Edit_input"  onchange="previewPhoto();" size="50"></html:file>
                  		<br>
                  		<input type="button" value="校验图片" onclick="checkPhoto();"/>
                  		</TD>
              		</TR>
					<tr>
						<td colspan="2" align="center"><html:submit value="添加"></html:submit>
						</td>
					</tr>
				</tbody> 
			</table> 
			<br/>
		</html:form>
	</body>
</html>

  Spring与iBATIS整合及Struts1文件的上传与下载1
            
    
    博客分类: SSI iBATISSpringBeanStrutsAOP