SpringMVC(22):使用springmvc+spring+jdbc 优化订单管理系统的示例(ID修改供应商明细的功能实现)

本文介绍了一种基于SpringMVC框架实现的供应商信息在线修改功能及文件上传处理流程。主要内容涵盖系统架构、数据库交互、文件上传限制及异常处理等方面。

2018年1月28日

【0】功能描述:

供应商修改与保存功能:(1)登陆成功后(login.jsp),sys.jsp 系统页面会有链接---“供应商修改”,点击跳转到补全供应商修改信息( providerModifySave.jsp),若是添加成功则会保存至数据库,并跳转供应商显示(providerlist.jsp),否则继续返回系统页面(sys.jsp);(2)供应商修改信息包括常用数据和文件上传;

【1】jar包/文件架构

jar包:


图1

文件结构:


图2



【2】数据库准备:

已经新建了smbms_provider表,并新增了几个记录,可以参考《SpringMVC(18):使用springmvc+spring+jdbc 优化订单管理系统的示例(供应商新增的功能实现)》:


图3


图4


【3】View层:

1.在sys.jsp添加以下代码:

	<h4>------------------点击下面的链接进行供应商信息修改:---------</h4>
	<br>
	<a href="${pageContext.request.contextPath}/usera/providerModify.html">跳转到供应商信息修改.</a>	
	<br/>


效果:

图5


2.新建/jsp/providerModifySave.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h5>这是providerModifySave页面!</h5>
	  <form action="${pageContext.request.contextPath }/usera/providerModifySave.html" method="post" enctype="multipart/form-data">
	          需要修改信息的供应商ID:<input type="text" name="id" value=""><br>
	                供应商编码 1:<input type="text" name="proCode" value=""/><br> 
		     供应商名称2 :<input type="text" name="proName" value=""/><br>  
	                联系人3:<input type="text" name="proContact" value=""/><br>  
	                供应商地址4 :<input type="text" name="proAddress" value=""/><br>  
	               供应商电话5 :<input type="text" name="proPhone" value=""/><br>  
	               传真6:<input type="text" name="proFax" value=""/><br>  
	               描述7 : <input type="text" name="proDesc" value=""/><br>  
		    <input type="hidden" id="errorinfo" value="${uploadFileError}">           
		          上传文件1-营业执照8:<input type="file" name="uploadProFiles"/><br/>
		    <input type="hidden" id="errorinfo" value="${uploadFileError}">    
		          上传文件2-组织机构代码照9:<input type="file" name="uploadProFiles"/><br/> 
	      <input type="submit" value="上传"/> 
	      <input type="reset" value="重置"/>  
   </form> 	
</body>
</html>


效果:
图6



【4】控制器方法:

1.providerController.java添加两个处理方法(providerModify、providerModifySave):

	@RequestMapping(value="/providerModify.html",method=RequestMethod.GET)
	public String providerModify(@ModelAttribute Provider providerModify){
		System.out.println("ProviderController-providerModify");
		System.out.println("build a new model attribute: "+providerModify.toString());
		return "providerModifySave";
	}
	
	@RequestMapping(value="/providerModifySave.html",method=RequestMethod.POST)
	public String providerModifySave(Provider providerModify,HttpSession session,
								HttpServletRequest request,
								@RequestParam(value="uploadProFiles",required=false)MultipartFile[] uploadProFiles) throws SQLException{
		System.out.println("ProviderController-providerModifySave");
		System.out.println("providerModify: "+providerModify.toString());
		String errorInfo = null;
		String pic_OrgCodeCer  = null;
		String pic_BusinessLic = null;
		boolean flag = true;
		//获取保存文件的绝对路径
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfilesProvider");
		System.out.println("2.1 uploadFile path ===>"+path);		
		for(int i=0;i<uploadProFiles.length;i++){
			MultipartFile uploadFile = uploadProFiles[i];
			System.out.println("开始-flag: "+flag);
			if(!uploadFile.isEmpty()){
				if(i==0){
					errorInfo = "uploadFileError!";
				}else if(i==1){
					errorInfo = "uploadWpError!";
				}
				System.out.println("文件数量-flag: "+flag);
				String oldFileName = uploadFile.getOriginalFilename();
				String prefix = FilenameUtils.getExtension(oldFileName);
				int filesize = 500000;
				if(uploadFile.getSize() > filesize){
					request.setAttribute("uploadFileError", "* 上传大小不得超过5000KB");
					System.out.println("* 上传大小不得超过5000KB");
					flag = false;
					System.out.println("文件大小-flag: "+flag);
					return "provideradd";
				}else if(prefix.equalsIgnoreCase("jpg")
						   || prefix.equalsIgnoreCase("png")
						   || prefix.equalsIgnoreCase("jpeg")
						   || prefix.equalsIgnoreCase("pneg")){
					//上传格式正确,重命名文件
					String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
					System.out.println("2.2 new fileName===>"+uploadFile.getName());
					//新建这么一个文件,FILE API
					File targetFile = new File(path,fileName); 
					if(!targetFile.exists()){
						targetFile.mkdirs();
					}
					System.out.println("格式-flag: "+flag);
					//保存
					try{
						//上传
						uploadFile.transferTo(targetFile);
					}catch (Exception e){
						e.printStackTrace();
						request.setAttribute("uploadFileError", "* 上传失败! ");
						System.out.println("* 上传失败! ");
						flag = false;
						System.out.println("上传-flag: "+flag);
						return "provideradd";
					}
					if(i==0){
						pic_OrgCodeCer = path+File.separator+fileName;
						log.info("2.3 pic_OrgCodeCer ==>"+pic_OrgCodeCer );
					}else if(i==1){
						pic_BusinessLic = path+File.separator+fileName;
						log.info("2.4 pic_BusinessLic==>"+pic_BusinessLic);
					}
					
				}else{
					request.setAttribute("uploadFileError", "* 上传格式错误!");
					System.out.println("* 上传格式错误!");
					flag = false;
					return "provideradd";
				}
			}
		}
		System.out.println("flag:"+flag);
		if(flag){
			System.out.println("modify provider info1: "+providerModify);
			providerModify.setPic_BusinessLic(pic_BusinessLic);
			providerModify.setPic_OrgCodeCer(pic_OrgCodeCer);
			providerModify.setModifyBy(((User)session.getAttribute("currentUser")).getId());
			System.out.println("modify provider info2: "+providerModify.toString());
			if(providerService.modify(providerModify)){
				System.out.println("2.5 modify provider success..");
				return "redirect:/usera/providerlist.html";
			}
		}
		return "sys";
	}
	


【5】Service层

1. /Service/providerService.java 接口添加modify()方法:


package com.Provider.Service;

import java.sql.SQLException;
import java.util.List;
import com.Provider.entities.Provider;

public interface ProviderService {	
	public boolean modify(Provider providerModify) throws SQLException;
}

2. providerServiceImpl.java实现类:


package com.Provider.Service;

import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Provider.Dao.ProviderDao;
import com.Provider.entities.Provider;

@Service("providerService")
public class ProviderServiceImpl implements ProviderService {
	@Autowired
	ProviderDao providerDao;

	@Override
	public boolean modify(Provider providerModify) throws SQLException {
		System.out.println("ProviderServiceImpl-modify");
		boolean result = false;
		if(providerDao.modify(providerModify) == 1){
			result = true;
		}
		return result;
		
	}
}


【6】Dao层

1. /Dao/ProviderDao.java接口添加modify()方法:

package com.Provider.Dao;

import java.sql.SQLException;
import java.util.List;
import com.Provider.entities.Provider;

public interface ProviderDao {
	int modify(Provider providerModify) throws SQLException;
}


2.ProviderDaoImpl.java:

package com.Provider.Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.Provider.entities.Provider;
import com.User.Controller.UserController;

@Component("providerDao")
public class ProviderDaoImpl implements ProviderDao {
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private String sql;

	@Override
	public int modify(Provider providerModify) throws SQLException {
		System.out.println("providerDao-modify");
		Logger log = Logger.getLogger(UserController.class.getName());
		SimpleDateFormat modifyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		providerModify.setModifyDate(new Date());
		String modifyDate = modifyDateFormat.format(providerModify.getModifyDate());
		int count = 0;
		//第二种方法  	
		sql = "update smbms_provider SET "
				+"proCode='"+providerModify.getProCode()+"',"
				+"proName='"+providerModify.getProName()+"',"
				+"proAddress='"+providerModify.getProAddress()+"',"
				+"proFax='"+providerModify.getProFax()+"',"
				+"proDesc='"+providerModify.getProDesc()+"',"
				+"proContact='"+providerModify.getProContact()+"',"
				+"pic_BusinessLic='"+providerModify.getPic_BusinessLic()+"',"
				+"pic_OrgCodeCer='"+providerModify.getPic_OrgCodeCer()+"',"
				+"modifyDate='"+modifyDate+"',"
				+"modifyBy="+providerModify.getModifyBy()+" "	
				+"where id="+ providerModify.getId()+";";
		String sql2 = " SELECT ROW_COUNT();";
		
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		stmt = conn.createStatement();
		System.out.println("add - sql1: "+sql);
		stmt.execute(sql);
		System.out.println("add_result_row - sql: "+sql2);
		rs = stmt.executeQuery(sql2);
		rs.next();
		count = rs.getInt(1);
		System.out.println("count: "+count);
		if(stmt!=null){
			stmt.close();
		}
		if(rs!=null){
			rs.close();
		}
		return count;
	}
	
}


【7】配置文件:

1. spring配置文件 -- applicationContext-jdbc.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:context="http://www.springframework.org/schema/context"
 	xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context 
        	http://www.springframework.org/schema/context/spring-context-4.0.xsd
        	http://www.springframework.org/schema/aop
        	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        ">
	<context:component-scan base-package="com.User.Dao"></context:component-scan>
	<context:component-scan base-package="com.User.Service"></context:component-scan>
	<context:component-scan base-package="com.Role.Dao"></context:component-scan>
	<context:component-scan base-package="com.Role.Service"></context:component-scan>
	<context:component-scan base-package="com.Provider.Dao"></context:component-scan>
	<context:component-scan base-package="com.Provider.Service"></context:component-scan>
</beans>

2. springmvc配置文件 -- /springmvc-servlet.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:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
     <!--mvc静态资源访问   -->
	 <mvc:resources mapping="/statics/**" location="/statics/"/>
	
   	<!-- 一键式配置 -->
    <context:component-scan base-package="com.User.Controller"></context:component-scan>
    <context:component-scan base-package="com.Provider.Controller"></context:component-scan>  
    <context:component-scan base-package="com.User"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>  
  
    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->  
    <!--prefix 前缀+suffix 后缀  -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>         
  	
  	<!-- 全局异常处理 -->
  	<!--  -->
  	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  		<property name="exceptionMappings">
  			<props>
  				<prop key="java.lang.RuntimeException">login</prop>
  			</props>
  		</property>
  	</bean>
  	
  	<!-- 配置MultipartResolver -->
  	<bean id="multipartResolver" 
  	  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  	 	<property name="maxUploadSize" value="5000000"></property>
  	 	<property name="defaultEncoding" value="UTF-8"></property> 
  	 </bean>
  	 
</beans> 


3. web.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    id="WebApp_ID" version="2.5">  
  
      <!-- 这个指定了log4j.xml放置的目录 -->
    <context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value> 
	</context-param>
	 <!-- 一定要加上这个listener -->
	<listener>  
	    <listener-class>  
	        org.springframework.web.util.Log4jConfigListener 
	    </listener-class>  
	</listener> 
  
    <!-- 配置 DispatcherServlet -->
    <servlet>  
        <servlet-name>springmvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:springmvc-servlet.xml</param-value>  
        </init-param>  
        <!--容器启动时就被加载了    -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>springmvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
       	
   	<filter>
		<filter-name>springUtf8Encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>springUtf8Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <welcome-file-list>
    	<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
    </welcome-file-list>
    
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <!-- 配置Spring的ContextLoaderListener监听器,初始化spring容器 -->
    <listener>
    	<listener-class>
    	 	org.springframework.web.context.ContextLoaderListener
    	</listener-class>
    </listener>

</web-app>  


【8】测试结果:

打印日志:

UserServiceImpl-login
18/02/08 00:41:39 INFO Controller.UserController: UserDaoImpl.loginMatch
sql: select * from smbms_user where userName='mmb0889' and userPassword='scua';
8888
4
18/02/08 00:41:39 INFO Controller.UserController: 后台找一下有没有这个username和password: User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
18/02/08 00:41:39 INFO Controller.UserController: user.toString(): User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
18/02/08 00:41:39 INFO Controller.UserController: 刚刚存入了一个session对象:User [id=4, userCode=test01, userName=mmb0889, userPassword=scua, gender=2, birthdayString=null, birthday=1991-12-29, phone=0000, address=maoming, userRole=110, createdBy=1, creationDate=2017-12-17, creationDateString=null, modifyBy=null, modifyDate=null, modifyDateString=null, idPicPath=null, workPicPath=null, roleName=null]
ProviderController-providerModify
build a new model attribute: Provider [id=null, proCode=null, proName=null, proDesc=null, proContact=null, proPhone=null, proFax=null, createBy=null, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=null, pic_OrgCodeCer=null, proAddress=null]
ProviderController-providerModifySave
providerModify: Provider [id=2, proCode=0022, proName=TianMao, proDesc=NianHuo, proContact=No33, proPhone=88888888, proFax=0213-22, createBy=null, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=null, pic_OrgCodeCer=null, proAddress=TianHe]
2.1 uploadFile path ===>D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider
开始-flag: true
文件数量-flag: true
2.2 new fileName===>uploadProFiles
格式-flag: true
18/02/08 00:42:05 INFO Controller.UserController: 2.3 pic_OrgCodeCer ==>D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021937800_Personal.jpg
开始-flag: true
文件数量-flag: true
2.2 new fileName===>uploadProFiles
格式-flag: true
18/02/08 00:42:05 INFO Controller.UserController: 2.4 pic_BusinessLic==>D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021733889_Personal.jpg
flag:true
modify provider info1: Provider [id=2, proCode=0022, proName=TianMao, proDesc=NianHuo, proContact=No33, proPhone=88888888, proFax=0213-22, createBy=null, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=null, pic_OrgCodeCer=null, proAddress=TianHe]
modify provider info2: Provider [id=2, proCode=0022, proName=TianMao, proDesc=NianHuo, proContact=No33, proPhone=88888888, proFax=0213-22, createBy=null, creationDate=null, modifyDate=null, modifyBy=4, pic_BusinessLic=D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021733889_Personal.jpg, pic_OrgCodeCer=D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021937800_Personal.jpg, proAddress=TianHe]
ProviderServiceImpl-modify
providerDao-modify
add - sql1: update smbms_provider SET proCode='0022',proName='TianMao',proAddress='TianHe',proFax='0213-22',proDesc='NianHuo',proContact='No33',pic_BusinessLic='D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021733889_Personal.jpg',pic_OrgCodeCer='D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1518021937800_Personal.jpg',modifyDate='2018-02-08 00:42:05',modifyBy=4 where id=2;
add_result_row - sql:  SELECT ROW_COUNT();
count: 1
2.5 modify provider success..
18/02/08 00:42:05 INFO Controller.UserController: getUserList ====> queryUserName: null
18/02/08 00:42:05 INFO Controller.UserController: getUserList ====> queryUserRole: null
providerdao执行的sql: select proCode,proName,proContact ,proPhone,proFax ,creatiomDate   from smbms_provider  where proCode  like CONCAT('%','','%') and proName  like CONCAT('%','','%');


测试输入:


图7


修改成功后,跳转供应商信息展示:


图8

文件上传成功:


图9


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后台技术汇

对你的帮助,是对我的最好鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值