最最基礎的SSM框架整合demo

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文件.

以上.

源代碼全都在文章中了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章