SpringMVC(18):使用springmvc+spring+jdbc 优化订单管理系统的示例(供应商新增的功能实现)
程序员文章站
2022-07-11 11:41:57
...
2018年1月28日
【0】功能要求
供应商新增功能:(1)登陆成功后(login.jsp),sys.jsp 系统页面会有供应商新增按钮,点击跳转到补全供应商信息( provideradd.jsp),若是添加成功则会保存至数据库,并跳转供应商列表显示(providerlist.jsp),否则继续返回用户添加页面( provideradd.jsp);(2)供应商信息包括数据和文件上传;
【1】jar包/文件架构
jar包:
图1
文件结构:
图2
【2】View层
在sys.jsp添加以下代码:
<h4>下面是点击链接跳转:添加供应商。</h4>
<a href="${pageContext.request.contextPath}/usera/provideradd.html">跳转到添加供应商.</a>
页面效果:
新建provideradd.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
<!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>
<h4>provideradd:请在下面填写需要添加的供应商信息:</h4>
<form action="${pageContext.request.contextPath }/usera/providersave"
method="post" enctype="multipart/form-data">
供应商编码 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="uploadFiles"/><br/>
<input type="hidden" id="errorinfo" value="${uploadFileError}">
上传文件2-组织机构代码照9:<input type="file" name="uploadFiles"/><br/>
<input type="submit" value="上传"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>
页面效果:
图3
【3】Controller层:
在ProviderController.java作以下修改:
package com.Provider.Controller;
import java.io.File;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import com.Provider.Service.ProviderService;
import com.Provider.entities.Provider;
import com.User.Controller.UserController;
import com.User.entities.User;
@Controller
@RequestMapping("/usera")
public class ProviderController {
private Logger log = Logger.getLogger(UserController.class.getName());
@Autowired
private ProviderService providerService;
@RequestMapping("/providerlist.html")
public String getProviderList(Model model,
@RequestParam(name="queryProviderCode",required=false)String queryProviderCode,
@RequestParam(name="queryProviderName",required=false)String queryProviderName) throws SQLException{
log.info("getUserList ====> queryUserName: "+queryProviderCode);
log.info("getUserList ====> queryUserRole: "+queryProviderName);
List<Provider> providerlist = null;
if(queryProviderCode == null){
queryProviderCode = "";
}
if(queryProviderName == null){
queryProviderName = "";
}
providerlist = providerService.getProviderList(queryProviderCode,queryProviderName);
model.addAttribute("prolist",providerlist);
return "providerlist";
}
@RequestMapping(value="/provideradd",method=RequestMethod.GET)
public String add(@ModelAttribute Provider provider){
System.out.println("ProviderController-add");
return "provideradd";
}
@RequestMapping(value="/providersave",method=RequestMethod.POST)
public String save(Provider provider,Model model,
HttpServletRequest request,HttpSession session,
@RequestParam(value="uploadFiles",required=false)MultipartFile[] uploadFiles) throws SQLException{
System.out.println("ProviderController-save");
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<uploadFiles.length;i++){
MultipartFile uploadFile = uploadFiles[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 "useradd";
}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 "useradd";
}
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 "useradd";
}
}
}
System.out.println("flag:"+flag);
if(flag){
System.out.println("new provider info1: "+provider);
provider.setPic_BusinessLic(pic_BusinessLic);
provider.setPic_OrgCodeCer(pic_OrgCodeCer);
provider.setCreateBy(((User)session.getAttribute("currentUser")).getId());
System.out.println("new provider info2: "+provider);
providerService.save(provider);
return "redirect:/usera/providerlist.html";
}
return "provideradd";
}
}
解释:(1)上面定义了几个处理器方法:显示,添加和保存;
(2)多文件上传,使用数组:equestParam(value="uploadFiles",required=false)MultipartFile[] uploadFiles;
(3)session保存了登陆者的信息,因此可以保存setCreateBy;
【4】Service层接口与实现类:
ProviderService.java:
package com.Provider.Service;
import java.sql.SQLException;
import java.util.List;
import com.Provider.entities.Provider;
public interface ProviderService {
public List<Provider> getProviderList(String queryProviderCode,String queryProviderName) throws SQLException;
public boolean save(Provider provider) throws SQLException;
}
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 List<Provider> getProviderList(String queryProviderCode, String queryProviderName) throws SQLException {
return providerDao.getProviderList(queryProviderCode,queryProviderName);
}
@Override
public boolean save(Provider provider) throws SQLException {
boolean result = false;
if(providerDao.save(provider) == 1){
result = true;
}
return result;
}
}
【5】Dao层接口与实现类:
ProviderDao.java:
package com.Provider.Dao;
import java.sql.SQLException;
import java.util.List;
import com.Provider.entities.Provider;
public interface ProviderDao {
List<Provider> getProviderList(String queryProviderCode, String queryProviderName) throws SQLException;
public int save(Provider provider) throws SQLException;
}
ProviderDaoImpl.java:(使用的是jdbc的操作)
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 List<Provider> getProviderList(String queryProviderCode, String queryProviderName) throws SQLException {
List<Provider> providerlist = new ArrayList<Provider>();
sql = "select proCode,proName,proContact ,proPhone,proFax ,creatiomDate "
+ " from smbms_provider "
+ " where proCode like CONCAT('%','"+queryProviderCode+"','%')"
+ " and proName like CONCAT('%','"+queryProviderName+"','%');" ;
System.out.println("providerdao执行的sql: "+sql);
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();
rs = stmt.executeQuery(sql);
while(rs.next()){
Provider pro= new Provider();
pro.setProCode(rs.getString("proCode"));
pro.setProName(rs.getString("proName"));
pro.setProContact(rs.getString("proContact"));
pro.setProPhone(rs.getString("proPhone"));
pro.setProFax(rs.getString("proFax"));
pro.setCreationDate(rs.getDate("creatiomDate"));
providerlist.add(pro);
}
if(stmt!=null){
stmt.close();
}
if(rs!=null){
rs.close();
}
return providerlist;
}
@Override
public int save(Provider provider) throws SQLException {
Logger log = Logger.getLogger(UserController.class.getName());
int count = 0;
SimpleDateFormat createDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
provider.setCreationDate(new Date());
String createDate = createDateFormat.format(provider.getCreationDate());
System.out.println("ProviderDao-add");
//第二种方法
sql = "insert into smbms_provider "
+ "(proCode,proName,proAddress,proFax,proDesc,"
+ "proContact,createdBy,creatiomDate,"
+ "pic_BusinessLic,pic_OrgCodeCer) "
+ "values"
+ "('"
+provider.getProCode()+"','"
+provider.getProName()+"','"
+provider.getProAddress()+"','"
+provider.getProFax()+"','"
+provider.getProDesc()+"','"
+provider.getProContact()+"',"
+provider.getCreateBy()+",'"
+createDate+"','"
+provider.getPic_BusinessLic()+"','"
+provider.getPic_OrgCodeCer()+"'"
+")";
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);
if(stmt!=null){
stmt.close();
}
if(rs!=null){
rs.close();
}
return count;
}
}
【6】供应商显示结果页面
新建providerlist.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<h4>这是providerlist,负责展示供应商信息!</h4>
<c:forEach items="${prolist}" var="arr">
<c:out value="${arr.proCode}"></c:out>
<c:out value="${arr.proName}"></c:out>
<c:out value="${arr.proFax}"></c:out>
<c:out value="${arr.proPhone}"></c:out>
<c:out value="${arr.proContact}"></c:out>
<c:out value="${arr.creationDate}"></c:out>
<br>
</c:forEach>
</body>
</html>
【7】配置文件
spring配置文件(/resources/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>
springmvc配置文件(/resources/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>
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】测试结果:
测试输入:
图4
打印日志:
ProviderController-add
ProviderController-save
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===>uploadFiles
格式-flag: true
18/02/04 00:06:37 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\1517674966575_Personal.jpg
开始-flag: true
文件数量-flag: true
2.2 new fileName===>uploadFiles
格式-flag: true
18/02/04 00:06:37 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\1517674764202_Personal.jpg
flag:true
new provider info1: Provider [id=null, proCode=003, proName=shunfeng, proDesc=KuaiDi, proContact=no3, proPhone=88888888, proFax=0213-13, createBy=null, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=null, pic_OrgCodeCer=null, proAddress=]
new provider info2: Provider [id=null, proCode=003, proName=shunfeng, proDesc=KuaiDi, proContact=no3, proPhone=88888888, proFax=0213-13, createBy=4, creationDate=null, modifyDate=null, modifyBy=null, pic_BusinessLic=D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1517674764202_Personal.jpg, pic_OrgCodeCer=D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1517674966575_Personal.jpg, proAddress=]
ProviderDao-add
add - sql1: insert into smbms_provider (proCode,proName,proAddress,proFax,proDesc,proContact,createdBy,creatiomDate,pic_BusinessLic,pic_OrgCodeCer) values('003','shunfeng','','0213-13','KuaiDi','no3',4,'2018-02-04 00:06:37','D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1517674764202_Personal.jpg','D:\java_ee_eclipse\mmb_workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\springmvc5\statics\uploadfilesProvider\1517674966575_Personal.jpg')
add_result_row - sql: SELECT ROW_COUNT();
输出结果:
图5
图6