最最基础的SSM框架整合demo

本文详细介绍了SSM框架(Spring、SpringMVC、MyBatis)的基础整合步骤,包括创建web项目、导入必备jar包、构建MVC三层架构。同时,还讲解了如何添加文件上传下载功能,涵盖了配置解析器、编写Controller和对应的JSP页面。最后,提到了@RequestMapping注解的使用及其参数说明。
摘要由CSDN通过智能技术生成

SSM最最基础的整合流程

一 搭建项目框架

1.创建web项目

2.导入jar包

​ 对应的包种类有:(这里顺序不分先后)

​ jackson依赖包

​ mybatis包

​ springmvc包

​ spring框架包

​ validation验证包

​ 文件上传依赖包

​ 其他包

3. 创建框架

M层:

​ com.xx.dao

​ com.xx.entity

​ com.xx.service

​ com.xx.serviceImpl

V层:

​ jsp页面

C层:

​ controller类

其他的

​ dao包对应的映射文件(两种方式):

「 1 」.将映射文件放在dao包中

「 2 」.创建一个mapper包

config层

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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" 
	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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
	<!--扫描注解 -->
	<context:component-scan base-package="xx.xx.xx.*" />
	 <!-- 加载db.properties文件中的内容 -->  
    <context:property-placeholder location="classpath:config/db.properties"/>
	<!--配置DBCP数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" scope="singleton">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}?useUnicode=true&amp;characterEncoding=UTF8" />
		<property name="username" value="${user}" />
		<property name="password" value="${password}" />
		<property name="initialSize" value="10" />
		<property name="maxActive" value="50" />
		<property name="maxIdle" value="10" />
		<property name="minIdle" value="5" />
		<property name="maxWait" value="10000" />
	</bean>
	<!--配置SqlSessionFactory -->
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:config/mybatis.xml"></property>
	    <property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
	
	</bean>
	<!--配置MapperScannerConfigurer -->
	  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="xx.xx.xx.dao" />
		<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
	</bean>
	<!--配置事务管理器 -->
	<bean id="txMgr"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--配置声明式事务 -->
	<tx:advice transaction-manager="txMgr" id="txAdvice">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="REQUIRED" read-only="true" />
			<tx:method name="search*" propagation="REQUIRED" read-only="true" />
			<tx:method name="get*" propagation="REQUIRED" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 配置声明式事务管理 -->
	<aop:config>
		<aop:pointcut expression="execution(* xx.xx.xx.service.*.*(..))"
			id="txSrvMethod" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txSrvMethod" />
	</aop:config>

</beans>

2.db.properties

#数据源配置信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/user
user=root
password=123@qwe

3.mybatis.mxl

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
 <!--配置别名 --> 
	<typeAliases>
	  <package name="com.wl.web.entity"/>
	</typeAliases>
	
</configuration>

4.spring-mvc.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-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
	<!--开启注解,扫描包 -->
	<context:component-scan base-package="xx.xx.xx.controller" />

	<!--启动spring的mvc注解 -->
	<mvc:annotation-driven />

	<!--静态资源的处理 -->
	<mvc:resources location="/js/" mapping="/js/**" /><!-- 这里的文件路径要和项目中的文件路径保持一致 -->

	<!--配置拦截器 -->
	<!-- <mvc:interceptors>
		<mvc:interceptor>
			配置拦截器需要拦截的路径
			<mvc:mapping path="/**" />
			<bean class="com.wl.web.interceptor.LoginInterceptor">
				<property name="excludedUris">
					<list>
						<value>/user/toLogin</value>
						<value>/user/login</value>
						<value>/resources/</value>
					</list>
				</property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors> -->


	<!-- 配置文件上传解析器 -->

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--文件上传的最大值,单位:字节 byte 1*1024*1024 -->
		<property name="maxUploadSize" value="1000000"></property>
		<property name="defaultEncoding" value="utf-8"></property>
	</bean>

	<!--配置视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>
	<!-- 配置前端控制器 -->
	<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:config/spring-mvc.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>customer.jsp</welcome-file>
	</welcome-file-list>

	<!-- 编码方式转化为 -->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
    <!-- 配置监听器 如何将配置文件放在同一个xml中,则不需要监听器了.  -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

配置对应的文件,导入相关的文件.

如Easyui文件,css文件,img文件.

如果要实现一个简单的用户增删改查功能

例图:

Snipaste_2019-04-17_10-47-07

Snipaste_2019-04-17_10-47-15

进行各个包中类的编写

config包中的配置文件编写
数据源配置:

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" 
	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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
	<!--扫描注解 -->
	<context:component-scan base-package="com.wl.web.*" />
	 <!-- 加载db.properties文件中的内容 -->  
    <context:property-placeholder location="classpath:config/db.properties"/>
	<!--配置DBCP数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" scope="singleton">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}?useUnicode=true&amp;characterEncoding=UTF8" />
		<property name="username" value="${user}" />
		<property name="password" value="${password}" />
		<property name="initialSize" value="10" />
		<property name="maxActive" value="50" />
		<property name="maxIdle" value="10" />
		<property name="minIdle" value="5" />
		<property name="maxWait" value="10000" />
	</bean>
	<!--配置SqlSessionFactory -->
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:config/mybatis.xml"></property>
	    <property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
	
	</bean>
	<!--配置MapperScannerConfigurer -->
	  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.wl.web.dao" />
		<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
	</bean>
	<!--配置事务管理器 -->
	<bean id="txMgr"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--配置声明式事务 -->
	<tx:advice transaction-manager="txMgr" id="txAdvice">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="REQUIRED" read-only="true" />
			<tx:method name="search*" propagation="REQUIRED" read-only="true" />
			<tx:method name="get*" propagation="REQUIRED" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 配置声明式事务管理 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.wl.web.service.*.*(..))"
			id="txSrvMethod" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txSrvMethod" />
	</aop:config>

</beans>

db.properties外部文件

#数据源配置信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/user
user=root
password=123@qwe

mybatis.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
 <!--配置别名 --> 
	<typeAliases>
	  <package name="com.wl.web.entity"/>
	</typeAliases>
	
</configuration>

spring-mvc.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-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
	<!--开启注解,扫描包 -->
	<context:component-scan base-package="com.wl.web.controller" />

	<!--启动spring的mvc注解 -->
	<mvc:annotation-driven />

	<!--静态资源的处理 -->
	<mvc:resources location="/js/" mapping="/js/**" />

	<!--配置拦截器 -->
	<!-- <mvc:interceptors>
		<mvc:interceptor>
			配置拦截器需要拦截的路径
			<mvc:mapping path="/**" />
			<bean class="com.wl.web.interceptor.LoginInterceptor">
				<property name="excludedUris">
					<list>
						<value>/user/toLogin</value>
						<value>/user/login</value>
						<value>/resources/</value>
					</list>
				</property>
			</bean>
		</mvc:interceptor>
	</mvc:interceptors> -->


	<!-- 配置文件上传解析器 -->

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--文件上传的最大值,单位:字节 byte 1*1024*1024 -->
		<property name="maxUploadSize" value="1000000"></property>
		<property name="defaultEncoding" value="utf-8"></property>
	</bean>

	<!--配置视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

web文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>
	<!-- 配置前端控制器 -->
	<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:config/spring-mvc.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>customer.jsp</welcome-file>
	</welcome-file-list>

	<!-- 编码方式转化为 -->
	<filter>
		<filter-name>encodingFilter</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>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
    <!-- 配置监听器  -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

entity

package com.wl.web.entity;

public class User {
	private Integer id;
	private String name;
	private String phone;
	private String address;
	private String note;

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(Integer id, String name, String phone, String address,
			String note) {
		super();
		this.id = id;
		this.name = name;
		this.phone = phone;
		this.address = address;
		this.note = note;
	}

	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 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 getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", phone=" + phone
				+ ", address=" + address + ", note=" + note + "]";
	}

}

dao

package com.wl.web.dao;

import java.util.List;

import com.wl.web.entity.User;

public interface UserDao {
 
	/**查询所有
	 * @return
	 */
	public List<User> getAllUser();
	
	/**增加
	 * @param user
	 * @return
	 */
	public int addUser(User user);
	
	/**修改
	 * @param id
	 * @return
	 */
	public int updateUser(User user);
	
	/**删除
	 * @param user
	 * @return
	 */
	public int deleteUser(Integer id);
}

mapper

<?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.wl.web.dao.UserDao">
	<!-- 查询 -->
	<select id="getAllUser" resultType="user">
		select * from userinfo
	</select>
	<!-- 添加 -->
	<insert id="addUser" parameterType="user">
		insert into userinfo
		(name,phone,address,note)value(#{name},#{phone},#{address},#{note})
	</insert>
	<!-- 修改 -->
	<update id="updateUser">
	update userinfo set name=#{name},phone=#{phone},address=#{address},note=#{note} where id=#{id}
	</update>
	<!-- 删除 -->
	<delete id="deleteUser" parameterType="int">
	delete from userinfo where id=#{id}
	</delete>
	
</mapper>

service

package com.wl.web.service;

import java.util.List;

import com.wl.web.entity.User;

public interface UserService {

	/**
	 * 查询所有
	 * 
	 * @return
	 */
	public List<User> getAllUser();

	/**
	 * 增加
	 * 
	 * @param user
	 * @return
	 */
	public int addUser(User user);

	/**
	 * 修改
	 * 
	 * @param id
	 * @return
	 */
	public int updateUser(User user);

	/**
	 * 删除
	 * 
	 * @param user
	 * @return
	 */
	public int deleteUser(Integer id);
}

serviceImpl

package com.wl.web.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.wl.web.dao.UserDao;
import com.wl.web.entity.User;
import com.wl.web.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Resource
	private UserDao uDao;

	@Override
	public List<User> getAllUser() {
		return uDao.getAllUser();
	}

	@Override
	public int addUser(User user) {
		return uDao.addUser(user);
	}

	@Override
	public int updateUser(User user) {
		return uDao.updateUser(user);
	}

	@Override
	public int deleteUser(Integer id) {
		return uDao.deleteUser(id);
	}

}

controller

package com.wl.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wl.web.entity.User;
import com.wl.web.service.UserService;

@Controller
public class UserController {
	@Resource
	private UserService us;

	/**
	 * 查询所有用户
	 * 
	 * @param user
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/select")
	@ResponseBody
	public List<User> getAllUser(User user) {

		List<User> uList = us.getAllUser();
		System.out.println(uList);
		return uList;
	}

	/**
	 * 添加所有用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public int addUser(User user, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		return us.addUser(user);
	}

	/**
	 * 修改所有用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public int updateUser(User user) {
		return us.updateUser(user);
	}

	/**
	 * 删除所有用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public int deleteUpdate(@RequestParam("index") int id) {
		return us.deleteUser(id);
	}
}

jsp页面编写

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%
	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>产品管理页面</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="js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="js/easyui/themes/icon.css">
<script type="text/javascript" src="js/easyui/jquery.min.js"></script>
<script type="text/javascript" src="js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript"
	src="js/easyui/locale/easyui-lang-zh_CN.js"></script>

</head>

<body>


	<script type="text/javascript">
		$(function() {
			$("#dg").datagrid({
				url : "select",
				title : "客户管理",
				toolbar : "#addbt",
				width : 700,
				height : 400,
				pagination : true,
				pageList : [ 2, 4, 6 ],
				pageSize : 2,
				columns : [ [ {
					field : 'name',
					title : '姓名',
					width : 100,
					align : 'center'
				}, {
					field : 'phone',
					title : '电话',
					width : 100,
					align : 'center'
				}, {
					field : 'address',
					title : '地址',
					width : 100,
					align : 'center'
				}, {
					field : 'note',
					title : '备注',
					width : 100,
					align : 'center'
				}, {
					field : 'update',
					title : '修改',
					width : 100,
					align : 'center',
					formatter : updatePro
				}, {
					field : 'delete',
					title : '删除',
					width : 100,
					align : 'center',
					formatter : deletePro
				} ] ],
				onLoadSuccess : function() {
					$(".easyui-linkbutton").linkbutton();
				}
			});
		});

		/* 点击添加按钮 */
		function addInfo() {
			$("#addPro_window").window("open");
		}

		/* 点击确认添加按钮 */
		function submitProForm() {
			var flag = $("#addProForm").form("validate");
			var name = $("#name").val();
			var phone = $("#phone").val();
			var address = $("#address").val();
			var note = $("#note").val();

			if (flag) {
				$.post("add", {
					name : name,
					phone : phone,
					address : address,
					note : note
				}, function(addInfo) {
					if (addInfo) {
						$.messager.alert("提示", "新增成功");
						$("#addPro_window").window("close");
						$("#dg").datagrid("reload"); //通过调用reload方法,让datagrid刷新显示数据
					} else {
						$.messager.alert("提示", "新增失败");
					}

				}, "json");
			}
		}
		//点击取消按钮
		function clearProForm() {
			$("#addProForm").form("clear");
			$("#addPro_window").window("close");
		}

		/* 修改 */
		function updatePro(value, row, index) {

			return "<a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-edit' style='cursor: pointer;' οnclick='updateInfo("
					+ index + ")'>修改</a>";

		}
		/* 删除 */
		function deletePro(value, row, index) {

			return "<a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-cancel' style='cursor: pointer;' οnclick='deleteInfo("
					+ row.id + ")'>删除</a>";

		}
		/* 点击修改按钮 */
		function updateInfo(index) {
			//将当前行数据填入表单
			var data = $("#dg").datagrid("getData"); //获取datagrid对应的json数据(对象集合)
			var row = data.rows[index]; //获取第index行对应的json对象。 index为传递过来的索引参数,从0开始,就像数组下标。
			$("#updateProForm").form("load", row); //爽!使用form的load方法,快速将json对象的数据显示到 弹出窗口的表单元素之中。
			$("#updatePro_window").window("open"); //打开窗口。   
		}
		/* 点击修改保存按钮 */
		function submitupdateProForm() {
			var name = $("#name1").val();
			var phone = $("#phone1").val();
			var address = $("#address1").val();
			var note = $("#note1").val();

			$.post("update", $("#updateProForm").serialize(), function(res) {

				$.messager.alert("提示", "修改成功"); //此处建议修改为$.messager.alert()方法,请查阅帮助文档,自行修改。
				$("#updatePro_window").window("close");
				$("#dg").datagrid("reload");

			}, "json");
		}
		/* 点击修改取消按钮 */
		function closeUpdateProForm() {
			$("#updateProForm").form("clear");
			$("#updatePro_window").window("close");
		}

		/* 点击删除按钮 */
		function deleteInfo(index) {
			var data = $("#dg").datagrid("getData");
			var row = data.rows[index];
			$.messager.confirm('确认对话框', '您确定要删除该产品吗?', function(r) {
				if (r) {
					$.post("delete", {
						index : index
					}, function(deleteInfo) {
						$.messager.alert("提示", "删除成功!!");
						$("#dg").datagrid("load");
					}, "json");
				}
			});
		}
	</script>

	<table id="dg"></table>
	<div id=addbt>
		<a href='javascript:void(0)' class='easyui-linkbutton'
			iconCls='icon-add' style='cursor: pointer;' οnclick='addInfo()'>添加</a>
	</div>
	<!--新增产品信息-->
	<div id="addPro_window" class="easyui-window" title="新增产品信息"
		data-options="modal:true,closed:true,iconCls:'icon-save'"
		style="width:500px;height:300px;padding:10px;">
		<form id="addProForm" action="add">
			<table cellpadding="5">
				<tr>
					<td>姓名:</td>
					<td><input class="easyui-textbox" type="text" name="name"
						id="name" data-options="required:true"></input></td>

				</tr>

				<tr>
					<td>电话:</td>
					<td><input class="easyui-textbox" type="text" name="phone"
						id="phone" data-options="required:true"></input></td>
				</tr>

				<tr>
					<td>地址:</td>
					<td><input type="text" class="easyui-text" id="address"
						name="address" data-options="required:true">
					</td>
				</tr>
				<tr>
					<td>备注:</td>
					<td><input type="text" class="easyui-text" id="note"
						name="note" data-options="required:true">
					</td>
				</tr>
			</table>
		</form>
		<div style="text-align:center;padding:5px">
			<a href="javascript:void(0)" class="easyui-linkbutton" type="button"
				οnclick="submitProForm()">确认添加</a> <a href="javascript:void(0)"
				class="easyui-linkbutton" οnclick="clearProForm()">重新填写</a>
		</div>
	</div>

	<!--修改产品信息-->
	<div id="updatePro_window" class="easyui-window" title="修改产品信息"
		data-options="modal:true,closed:true,iconCls:'icon-save'"
		style="top:100px;left:500px;width:500px;height:300px;padding:10px;">
		<form id="updateProForm" action="update">
			<table cellpadding="5">
				<tr>
					<td><input type="hidden" name="id"></input></td>
				</tr>
				<tr>
					<td>姓名:</td>
					<td><input class="easyui-textbox" type="text" name="name"
						id="name1" data-options="required:true"></input></td>

				</tr>

				<tr>
					<td>电话:</td>
					<td><input class="easyui-textbox" type="text" name="phone"
						id="phone1" data-options="required:true"></input></td>
				</tr>

				<tr>
					<td>地址:</td>
					<td><input type="text" class="easyui-text" id="address1"
						name="address" data-options="required:true">
					</td>
				</tr>
				<tr>
					<td>备注:</td>
					<td><input type="text" class="easyui-text" id="note1"
						name="note" data-options="required:true">
					</td>
				</tr>
			</table>
		</form>
		<div style="text-align:center;padding:5px">
			<a href="javascript:void(0)" class="easyui-linkbutton" type="button"
				οnclick="submitupdateProForm()">保存</a> <a href="javascript:void(0)"
				class="easyui-linkbutton" οnclick="closeUpdateProForm()">重置</a>
		</div>
	</div>
</body>
</html>

运行效果

Snipaste_2019-04-17_11-07-44

以上.

添加一个文件上传下载功能

步骤

1.完成Spring与SpringMVC框架的搭建及相关配置.

再mvc-servlet.xml文件中配置文件上传解析器.

添加如下配置文件

<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--文件上传的最大值,单位:字节 byte 1*1024*1024 -->
		<property name="maxUploadSize" value="1000000"></property>
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="maxInMemorySize" value="100000"></property>
	</bean>

2.重新编写一个Controller类

package com.wl.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file/")
public class FileController {

	/**
	 * 传统单文件上传 http://localhost:8080/ssm4/file/singleFileUpload
	 * 
	 * @param myfile
	 * @param request
	 * @return
	 */
	@RequestMapping("singleFileUpload")
	public String singleFileUpload(MultipartFile myfile,
			HttpServletRequest request) {
		String name = myfile.getOriginalFilename();// 表单中name属性值
		String olName = myfile.getOriginalFilename();// 获取上传文件的名字
		System.out.println("name" + name);
		System.out.println("olName" + olName);
		// 获取保存文件的路径
		String path = request.getServletContext().getRealPath("/file");
		File file = new File(path, olName);
		try {
			myfile.transferTo(file);// 上传
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * ajax单文件上传 http://localhost:8080/ssm4/file/singleFileUpload2
	 * 
	 * @param myfile
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("singleFileUpload2")
	public Map singleFileUpload2(MultipartFile myfile,
			HttpServletRequest request) {
		Map map = new HashMap();
		String name = myfile.getName();
		String olName = myfile.getOriginalFilename();
		System.out.println("name" + name);
		System.out.println("olName" + olName);
		String path = request.getServletContext().getRealPath("/file");
		File file = new File(path, olName);
		map.put("success", true);
		try {
			myfile.transferTo(file);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
		}
		return map;
	}

	/**
	 * 传统多文件上传 http://localhost:8080/ssm4/file/moreFileUpload
	 * 
	 * @param myfileList
	 * @param request
	 * @return
	 */
	@RequestMapping("moreFileUpload")
	public String moreFileUpload(
			@RequestParam("myfile") List<MultipartFile> myfileList,
			HttpServletRequest request) {
		if (myfileList != null && myfileList.size() > 0) {
			for (MultipartFile myfile : myfileList) {
				String name = myfile.getName();
				String olName = myfile.getOriginalFilename();
				System.out.println("name" + name);
				System.out.println("olName" + olName);
				String path = request.getServletContext().getRealPath("/file");
				File file = new File(path, olName);
				try {
					myfile.transferTo(file);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return "success";
		} else {
			return "error";
		}
	}

	/** 文件下载
	 * @param request
	 * @param filename
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "download", method = RequestMethod.GET)
	// 匹配的是href中的download请求
	public ResponseEntity<byte[]> download(HttpServletRequest request,
			@RequestParam("filename") String filename, Model model)
			throws IOException {
		String path = request.getSession().getServletContext()
				.getRealPath("file");// 服务器中文件存放的位置
		File file = new File(path + File.separator + filename);// 新建一个文件
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
				headers, HttpStatus.CREATED);
	}

}

再编写对应的jsp页面用来接收@RequestMapping注解

这里为@Requestmapping做简单的解释:

@RequestMapping 参数说明

value:定义处理方法的请求的 URL 地址。(重点)

method:定义处理方法的 http method 类型,如 GET、POST 等。(重点)

params:定义请求的 URL 中必须包含的参数。或者不包含某些参数。(了解)

headers:定义请求中 Request Headers 必须包含的参数。或者不包含某些参数。(了解)

@RequestMapping 有两种标注方式,一种是标注在类级别上,一种是标注在方法级别上。标注在方法上时,value 表示访问该方法的 URL 地址。标注在类上时,value 相当于一个命名空间,即访问该 Controller 下的任意方法都需要带上这个命名空间。

上面的案例就是用的标注在方法级别上的,标注在方法上,value可以访问该方法的URL地址.

编写对应的HTML页面

本例需要的对应的HTML页面:

1.传统单文件上传所对应的HTML类

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	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>My JSP 'index.jsp' starting page</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">
	-->
</head>

<body>
	<form action="file/singleFileUpload" method="post"
		enctype="multipart/form-data">
		请选择文件:<input type="file" name="myfile" /><br />
		 <input type="submit" value="提交" />
	</form>
</body>
</html>

2.ajax单文件上传

fileUpload2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</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">
	<script type="text/javascript" src="js/easyui/jquery.min.js"></script>
   <script type="text/javascript">
     //登录
     function upload(){
     	var formData = new FormData($('#fm')[0]); 
     	alert(formData);
       $.ajax({
           type:"post",
           url:"file/singleFileUpload2",
           data:formData,
           dataType:"json",
           processData : false,
		   contentType : false,
           success:function(res){
             if(res.success){
                alert("上传成功!");
             }else{
               alert("上传失败!");
             }
           }
       });
       
     }
   </script>
  </head>
  <body>
  
   <form id="fm" method="post" enctype="multipart/form-data">
           请选择文件: <input type="file" name="myfile"/><br/>
        <input type="button" value="提交" onclick="upload()"/>
   </form>
  </body>
</html>

3.传统多文件上传

moreFileUpload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>多文件上传</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">
	-->
  </head>
  
  <body>
   <form action="file/moreFileUpload" method="post" enctype="multipart/form-data">
           请选择文件1: <input type="file" name="myfile"/><br/>
            请选择文件2: <input type="file" name="myfile"/><br/>
        <input type="submit" value="提交" />
   </form>
  </body>
</html>

4.文件下载

download.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	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>My JSP 'index.jsp' starting page</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">
</head>

<body>
	<h3>文件下载</h3>
	<a href="file/download?filename=SSM整合_1701.txt">下载头像</a>
</body>
</html>

Tip:对应的跳转页面,easyui未给出

如果用的是tomcat服务器,记得在对应的文件目录下创建File文件.

以上.

源代码全都在文章中了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值