很多新手都头疼于SSM上传图片如何实现,今天就来做个最简单的例子进行展示
开发工具以及环境:eclipse、navicat、mysql、tomcat7
一、数据库的设计
在navicat新建一个用户表people,字段分别是id、姓名、性别、手机、地址、图片
以下是我的目录结构
二、SSM的配置
1)引入SSM常用jar包,百度一下网上蛮多的
2)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">
<display-name>01.mybatis</display-name>
<!-- 配置SpringMVC编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 启动SpringMVC -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 参数:读取spring-mvc.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 启动spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 修改路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
3)spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:contenxt="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描Controller所在的包 -->
<contenxt:component-scan base-package="com.wt.controller"/>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器:简化在Controller类编写的视图路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 文件上传的解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传图片的最大尺寸 10M-->
<property name="maxUploadSize" value="10485760"></property>
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
</beans>
4)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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 读取jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 创建DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- 创建SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 关联连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载sql映射文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- Mapper接口的扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper接口所在包路径 -->
<property name="basePackage" value="com.wt.dao"/>
</bean>
<!-- 开启Spring的IOC注解扫描 -->
<context:component-scan base-package="com.wt"/>
<!-- 开启Spring的事务 -->
<!-- -事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 启用Spring事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
5)jdbc.properties
//你的数据库名和密码配置
jdbc.url=jdbc:mysql://127.0.0.1/people
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
6)log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
三、复制粘贴代码
user.java
package com.wt.model;
import org.springframework.web.multipart.MultipartFile;
public class User {
private Integer id;
private String name;
private String gender;
private String phone;
private String address;
private String image;
private MultipartFile logoImage;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public MultipartFile getLogoImage() {
return logoImage;
}
public void setLogoImage(MultipartFile logoImage) {
this.logoImage = logoImage;
}
}
UserDao.java
package com.wt.dao;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.wt.model.User;
@Repository("UserDao")
@Mapper
public interface UserDao {
public int addUser(User user);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wt.dao.UserDao">
<!-- 添加用户 -->
<insert id="addUser" parameterType="com.wt.model.User">
insert into user (name,gender,phone,address,image)
values ( #{name}, #{gender}, #{phone}, #{address}, #{image})
</insert>
</mapper>
MyUtil.java
package com.wt.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyUtil {
/**
* 获得时间字符串
*/
public static String getStringID(){
String id=null;
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
id=sdf.format(date);
return id;
}
}
UserService.java
package com.wt.service;
import javax.servlet.http.HttpServletRequest;
import com.wt.model.User;
public interface UserService {
/*public String selectUserById(Integer id);*/
public String addUser(User user,HttpServletRequest request);
}
UserServiceImpl.java
package com.wt.service.impl;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wt.dao.UserDao;
import com.wt.model.User;
import com.wt.service.UserService;
import com.wt.util.MyUtil;
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public String addUser(User user, HttpServletRequest request) {
String newFileName = "";
String fileName = user.getLogoImage().getOriginalFilename();
//选择了文件
if(fileName.length() > 0){
String realpath = request.getServletContext().getRealPath("/user");
//实现文件上传
String fileType = fileName.substring(fileName.lastIndexOf('.'));
//防止文件名重名
newFileName = MyUtil.getStringID() + fileType;
user.setImage("user/"+newFileName);
File targetFile = new File(realpath, newFileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//上传
try {
user.getLogoImage().transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
//保存到数据库中
userDao.addUser(user);
return "user/userInfo";
}
}
UserController.java
package com.wt.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wt.model.User;
import com.wt.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/addUser")
public String addUser(User user,HttpServletRequest request) {
return userService.addUser(user,request);
}
}
IndexController.java
package com.wt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//控制器
@Controller
@RequestMapping("")
public class IndexController {
//首页
@RequestMapping("/index")
public String index() {
return "index";
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>用户输入页面</title>
</head>
<body>
<form:form action="user/addUser.action" method="post" enctype="multipart/form-data" >
<table border=1 style="border-collapse: collapse">
<caption>
<font size=4 face=华文新魏>添加用户</font>
</caption>
<tr>
<td>姓名</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="gender" value="男" checked="checked"/>男
<input type ="radio" name="gender" value="女"/>女
</td>
</tr>
<tr>
<td>手机</td>
<td>
<input type="text" name="phone">
</td>
</tr>
<tr>
<td>地址</td>
<td>
<input type="text" name="address">
</td>
</tr>
<tr>
<td>头像</td>
<td>
<input type="file" name="logoImage"/>
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="submit" value="提交" />
</td>
<td align="left">
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
userInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ 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>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户信息页面</title>
</head>
<body>
<table border=1 style="border-collapse: collapse">
<tr>
<!-- <td>头像</td> -->
<td colspan="2">
<img alt="" width="250" height="250"src="${user.image}"/>
</td>
</tr>
<tr>
<td>姓名</td>
<td>
${user.name }
</td>
</tr>
<tr>
<td>性别</td>
<td>
${user.gender}
</td>
</tr>
<tr>
<td>手机</td>
<td>
${user.phone}
</td>
</tr>
<tr>
<td>地址</td>
<td>
${user.address }
</td>
</tr>
</table>
</body>
</html>
四、运行截图
1、右键项目名run as---run on server
2、在地址栏输入http://localhost/People/index.action
3、用户信息输入界面截图
4、添加完整信息进行跳转
点击提交,就可以看到用户信息页面已经显示图片
可以在navicat中看到图片的地址已经保存到数据库中
其实上传的图片都会保存在eclipse的workplace中,详细路径如下
G:\workplace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\People\user