- 浏览: 734914 次
- 性别:
- 来自: 嘉兴
文章分类
- 全部博客 (386)
- Struts1.1 (2)
- Database (18)
- Core Java (15)
- Log4j (4)
- SSH (0)
- Dao (1)
- Architecture Design (1)
- References (2)
- Eclipse&MyEclipse (10)
- Hibernate (7)
- Spring (8)
- JavaMail (1)
- Data Structure And Algorithm (48)
- Struts 2 (2)
- SSI (1)
- SSL (2)
- JSTL (1)
- EJB3 (2)
- NET (2)
- XML (2)
- Components (2)
- Ant (3)
- Multi Thread (1)
- Performance Monitoring (1)
- Web Server (17)
- Oracle (1)
- jQuery (8)
- Regular Expression (1)
- Weblogic (1)
- Exception (1)
- Security (2)
- File Manipulation (1)
- JavaScript (12)
- JVM (2)
- HTML&DIV&CSS (4)
- Android (10)
- Beyond GFW (0)
- Business (0)
- SVN (6)
- 虚拟主机 (1)
- Virtual Host (3)
- My mentality (5)
- OS (15)
- ISPMP (3)
- Magento (5)
- Jsoup&HttpClient (7)
- LINUX (9)
- Database Design (0)
- Power Designer (1)
- TaobaoOpenPlatform (2)
- C/C++ (3)
- Maven (11)
- Quartz (1)
- Load Balance (1)
- Zabbix (4)
- Product&Business (1)
- Pay Interface (1)
- Tomcat (2)
- Redis (1)
- 集群 (1)
- Session (1)
- 共享Session (1)
- Jedis (1)
- jenkins (1)
- 持续集成 (1)
- Web前端 (1)
最新评论
-
aqq331325797:
特意注册账号上来说一句。牛逼!
swagger2.2.2 与 spring cloud feign冲突 -
KitGavinx:
跨顶级域名怎么保持sessionid一致?
Tomcat7集群共享Session 基于redis进行统一管理 -
jaychang:
dujianqiao 写道HI ,能否给一个完整的demo 啊 ...
淘宝订单同步方案 - 丢单终结者 -
GGGGeek:
找了一会儿,感觉mybatis应该没有这种操作,直到发现博主的 ...
mybatis collection list string -
dujianqiao:
HI ,能否给一个完整的demo 啊 ?
淘宝订单同步方案 - 丢单终结者
案例是关于联系人信息列表展示,使用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> <bean:write name="contact" property="lastName" /> <a href="<%=path%>/contact_detail.do?lastName=<bean:write name="contact" property="lastName"/>"></a> </td> <td> <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_web.rar (7.7 MB)
- 下载次数: 84
相关推荐
struts2、spring、ibatis整合实例 struts2、spring、ibatis整合实例 struts2、spring、ibatis整合实例 struts2、spring、ibatis整合实例
struts1 spring ibatis整合项目源码struts1 spring ibatis整合项目源码struts1 spring ibatis整合项目源码struts1 spring ibatis整合项目源码struts1 spring ibatis整合项目源码struts1 spring ibatis整合项目源码
1. **添加依赖**:首先,在项目的pom.xml文件中,需要添加Struts2、Spring和iBatis的依赖库,确保版本兼容。 2. **配置Struts2**:创建struts.xml配置文件,定义Action类和结果页面。同时,需要在web.xml中配置...
在提供的"spring+struts2+ibatis整合的jar包"中,lib1可能包含了这三个框架以及它们的依赖库。这些jar文件是运行整合应用必不可少的组件,它们包含了框架的API、实现和一些工具类,帮助开发者快速搭建和运行整合项目...
"Struts2+Spring+iBatis整合"是一个典型的MVC(Model-View-Controller)架构实现,适用于构建大型企业级应用。下面将详细介绍这三个框架以及它们整合的关键点。 **Struts2** 是一个基于MVC设计模式的Web应用框架,...
`Struts+Spring+Ibatis整合框架搭建配置文档.doc`应该详细阐述了如何配置Spring以管理Struts2的Action和iBatis的数据源及SqlSession。 3. **iBatis**:iBatis是一个SQL映射框架,它将SQL语句与Java代码分离,使得...
在与Struts2和iBatis的整合中,Spring主要负责管理Bean的生命周期和依赖关系,以及事务的统一管理。Spring的事务管理可以基于编程式或者声明式,后者通过@Transactional注解实现,更符合开闭原则,降低了代码的耦合...
在这个“struts2+spring3+ibatis项目整合案例”中,我们将深入探讨这三个框架如何相互配合,实现项目的集成。 Struts2作为MVC(Model-View-Controller)架构的实现,主要负责处理用户请求,控制应用的流程。它提供...
### Struts+Spring+Ibatis整合框架搭建配置详解 在当今复杂的软件开发环境中,整合不同的框架以构建高效、可维护的应用程序变得尤为重要。Struts、Spring与Ibatis(现称MyBatis)作为三个功能互补的Java框架,它们...
**Spring、Struts2 和 iBatis 整合详解** 在Java Web开发中,Spring、Struts2 和 iBatis 是三个非常重要的框架。它们分别负责不同层面的任务:Spring 提供了全面的依赖注入(DI)和面向切面编程(AOP),用于管理...
Struts2、Spring和iBatis是Java Web开发中常用的三大框架,它们分别负责MVC模式中的动作控制、依赖注入及持久层操作。本项目整合了这三个框架,并使用MySQL作为数据库,实现了一个基础的用户登录注册查询删除的功能...
在这个特定的案例中,我们关注的是"Ibatis Spring Struts"的整合。这三个框架分别是:Ibatis(一个轻量级的持久层框架),Spring(一个全面的企业级应用开发框架),以及Struts(一个用于构建MVC(Model-View-...
通过这个"Struts1+Spring+iBatis-jar包",开发者可以避免手动下载和管理各个框架的依赖,简化项目的初始化工作,集中精力于业务逻辑的实现。然而,需要注意的是,虽然这三者可以良好集成,但在现代Web开发中,Struts...
Struts2+Spring+Hibernate和Struts2+Spring+Ibatis是两种常见的Java Web应用程序集成框架,它们分别基于ORM框架Hibernate和轻量级数据访问框架Ibatis。这两种框架结合Spring,旨在提供一个强大的、可扩展的、易于...
本实例关注的是“ibatis+Spring+struts2”的整合,这是一个经典的Java Web开发组合,用于实现数据访问、业务逻辑控制和用户界面交互。下面我们将深入探讨这三个组件及其整合的关键知识点。 1. **iBATIS**:iBATIS...
5. 整合过程:通常,整合这三大框架需要配置Struts2的struts.xml、Spring的applicationContext.xml以及iBatis的sqlMapConfig.xml等文件。还需要在Struts2的Action类中注入Spring管理的bean,以便于调用业务服务。...
在"Struts+Spring+Ibatis整合的Jar包"中,这三者通过合理的配置和接口调用相互协同工作,实现了数据访问、业务逻辑处理和用户界面展示的完美结合。首先,Struts2作为控制器,接收用户的请求并转发给Spring管理的业务...
1. **引入依赖**:首先,在项目中引入Struts2、Spring和iBatis的相应库。 2. **配置Struts2**:编写struts.xml配置文件,定义Action类及其对应的处理方法和结果视图。 3. **配置Spring**:创建spring配置文件,如...
这个"Struts+Spring+Ibatis示例"提供了一个基础的整合应用,帮助开发者理解这三者如何协同工作。 **Struts** 是一个基于 Model-View-Controller (MVC) 设计模式的Java web框架,主要负责处理用户请求,控制应用程序...
Struts+spring+ibatsi框架整合实例