1. 程式人生 > >ssm簡單增刪改查案例

ssm簡單增刪改查案例

此文章僅供新手參考或老手溫習

一、建立maven web專案,這裡就不多講了.

二、新增pom檔案資訊

<properties>
  	<spring.version>4.3.10.RELEASE</spring.version>
  	<commons-lang.version>2.6</commons-lang.version>
  	<commons-logging.version>1.2</commons-logging.version>
  	<mybatis.version>3.4.5</mybatis.version>
  	<mybatis-spring.version>1.3.1</mybatis-spring.version>
  	<mysql.version>5.1.10</mysql.version>
  	<druid.version>1.0.14</druid.version>
  	<log4j.vresion>1.2.17</log4j.vresion>
  	<jstl.version>1.2</jstl.version>
  	<jsp-api.version>2.2</jsp-api.version>
  	<servlet-api.version>3.1.0</servlet-api.version>
  	<aspectjweaver.version>1.8.13</aspectjweaver.version>
  </properties>
  
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-core</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-beans</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-web</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-tx</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jdbc</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-expression</artifactId>
  		<version>${spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-lang</groupId>
  		<artifactId>commons-lang</artifactId>
  		<version>${commons-lang.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>commons-logging</groupId>
  		<artifactId>commons-logging</artifactId>
  		<version>${commons-logging.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis</artifactId>
  		<version>${mybatis.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis-spring</artifactId>
  		<version>${mybatis-spring.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>${mysql.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>com.alibaba</groupId>
  		<artifactId>druid</artifactId>
  		<version>${druid.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>log4j</groupId>
  		<artifactId>log4j</artifactId>
  		<version>${log4j.vresion}</version>
<!--   		<type>bundle</type> -->
  	</dependency>
  	<dependency>
  		<groupId>jstl</groupId>
  		<artifactId>jstl</artifactId>
  		<version>${jstl.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet.jsp</groupId>
  		<artifactId>jsp-api</artifactId>
  		<version>${jsp-api.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>javax.servlet-api</artifactId>
  		<version>${servlet-api.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.aspectj</groupId>
  		<artifactId>aspectjweaver</artifactId>
  		<version>${aspectjweaver.version}</version>
  	</dependency>
  	
  	
  	<dependency>
	    <groupId>org.apache.maven.plugins</groupId>
	    <artifactId>maven-resources-plugin</artifactId>
	    <version>2.5</version>
	</dependency>
  </dependencies>

三、新增web.xml檔案資訊

<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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</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:spring/spring-*.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

四、springmvc.xml

<context:annotation-config />
	<context:component-scan base-package="com.ssm.controller" />
	
	<mvc:annotation-driven />
	<mvc:default-servlet-handler/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

五、spring-dao.xml

<!-- 資料庫連線池 -->
	<!-- 載入配置檔案 -->
	<context:property-placeholder location="classpath:config/database.properties"/>
	<!-- 資料庫連線池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="maxActive" value="10" />
		<property name="minIdle" value="5" />
	</bean>
	<!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 資料庫連線池 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 載入mybatis的全域性配置檔案 -->
<!-- 		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> -->
		<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
	</bean>
	<!-- 自動掃描 將Mapper介面生成代理注入到Spring -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ssm.mapper" />
<!-- 		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->
	</bean>

六、spring-service.xml

<context:component-scan base-package="com.ssm.service" />
	
	<!-- 事務管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 資料來源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 傳播行為 -->
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 切面 -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* com.ssm.service.*.*(..))" />
	</aop:config>

七、database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

八、Java程式碼部分

1.PageController

@Controller
public class PageController {

	@RequestMapping("/")
	public String index() {
		return "index";
	}
}

2.UserController

@Controller
@RequestMapping("/users")
public class UsersController {

	@Autowired
	private UserService userServie;
	
	@RequestMapping("/toAddUser")
	public String toAddUser() {
		return "addUser";
	}
	
	@RequestMapping("/toUpdateUser/{uid}")
	public String toUpdateUser(@PathVariable("uid")Integer uid,Map<String,Object> map) {
		if(uid != null) {
			try {
				Users users = userServie.findOne(uid);
				map.put("user", users);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "updateUser";
	}
	
	@RequestMapping("/userinfo")
	public String user(Map<String, Object> map) {
		List<Users> findAll = userServie.findAll();
		map.put("userList", findAll);
		return "userinfo";
	}
	
	@RequestMapping("/addUser")
	@ResponseBody
	public String addUser(Users users) {
		if(users != null) {
			try {
				userServie.addUsers(users);
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		}else {
			return "not null";
		}
	}
	
	@RequestMapping("/updateUser")
	@ResponseBody
	public String updateUser(Users users) {
		if(users != null) {
			try {
				userServie.updateUsers(users);
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		}else {
			return "not null";
		}
	}
	
	@RequestMapping("/deleteUser/{uid}")
	@ResponseBody
	public String deleteUser(@PathVariable("uid")Integer uid) {
		if(uid != null) {
			try {
				userServie.deleteUsers(uid);
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		}else {
			return "not null";
		}
	}
}

3.實體類

public class Users {
    private Integer uid;

    private String name;

    private String username;

    private String password;

    private String gender;

    private Integer age;

    private Date createdate;

    private Date lastlogindate;

    private Integer locked;
    
    get set.......
}

4.service和mapper就不貼出來了(mybatis逆向工程就可以直接搞定mapper和pojo)

九、JSP部分

  1.userinfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>
<style type="text/css">
	table{
		margin:0 auto;
		width:1000px;
		height:300px;
		background:#000;
	}
	td,th{
		background:#FFF;
	}
</style>
</head>
<body>
	<h2>Show User</h2>
	<hr>
	<table border="0" cellspacing="1">
		<tr>
<!-- 			<th>uid</th> -->
			<th>name</th>
			<th>username</th>
<!-- 			<th>password</th> -->
			<th>gender</th>
			<th>age</th>
			<th>createDate</th>
			<th>lastLoginDate</th>
			<th>locked</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${userList }" var="user">
		<tr>
<%-- 			<td>${user.uid}</td> --%>
			<td>${user.name}</td>
			<td><a href="javascript:void(0);" onclick="updateUser('${user.uid}');">${user.username}</a></td>
<%-- 			<td>${user.password}</td> --%>
			<td>${user.gender}</td>
			<td>${user.age}</td>
			<td><fmt:formatDate value="${user.createdate}" pattern="yyyy-MM-dd" /></td>
			<td><fmt:formatDate value="${user.lastlogindate}" pattern="yyyy-MM-dd" /></td>
			<td>${user.locked}</td>
			<td><a href="javascript:void(0);" onclick="deleteUser('${user.uid}','${user.username}');">刪除</a></td>
		</tr>
		</c:forEach>
	</table>
	<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
	<script type="text/javascript">
		function updateUser(uid){
			window.location.href="${pageContext.request.contextPath}/users/toUpdateUser/"+uid;
		}
		function deleteUser(uid,username){
			if(confirm("確定要刪除 "+username+" ?")){
				$.post("${pageContext.request.contextPath}/users/deleteUser/"+uid,function(data){
					if(data = 'success'){
						window.location.href="${pageContext.request.contextPath}/users/userinfo";
					}else{
						alert(data);
					}
				});
			}
		}
	</script>
</body>
</html>

2.其他JSP頁面就只是畫頁面而已就不貼了

十、最後完整的專案結構