SSM框架系列之框架整合教程

很久之前就想写的教程,因为忙着找实习的原因,没有整理出来,首先SSM框架组合(SpringMVC+Spring+Mybatis)和SSH(Spring4.0+Struts2+Hibernate4.0)组合是外面企业里很常用的两种MVC架构,本博客介绍SSM框架组合,这种MVC架构的搭建过程

jar准备的话,可以用maven或者网上下载
SpringMVC需要的jar
这里写图片描述

jar作用详解(网上收集):
aopaliance.jar
包含了针对面向切面的接口,通常Spring等其它具备动态织入功能的框架依赖此包

spring-aop.jar
这个jar 文件包含在应用中使用Spring 的AOP 特性时所需的类和源码级元数据支持。使用基于AOP 的Spring特性,如声明型事务管理(Declarative Transaction Management),也要在应用里包含这个jar包。
外部依赖spring-core, (spring-beans,AOP Alliance, CGLIB,Commons Attributes)。

spring-aspects.jar
提供对AspectJ的支持,以便可以方便的将面向方面的功能集成进IDE中,比如Eclipse AJDT。
外部依赖。

spring-beans.jar
这个jar 文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control / Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件就可以了。
外部依赖spring-core,(CGLIB)。

spring-context.jar
这个jar 文件为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI 所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
外部依赖spring-beans, (spring-aop)。

spring-core.jar
这个jar 文件包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心,当然你也可以在自己的应用系统中使用这些工具类。
外部依赖Commons Logging, (Log4J)。

spring-expression.jar
Spring表达式语言需要的jar

spring-jdbc.jar
这个jar 文件包含对Spring 对JDBC 数据访问进行封装的所有类。
外部依赖spring-beans,spring-dao。

spring-test.jar
spring框架对junit框架简单封装的jar

spring-tx.jar
提供对事务的支持,事务的相关处理以及实现类就在这个jar包中

spring-context-support.jar
这个jar 文件包含支持UI模版(Velocity,FreeMarker,JasperReports),邮件服务,脚本服务(JRuby),缓存Cache(EHCache),任务计划Scheduling(uartz)方面的类。
外部依赖spring-context, (spring-jdbc, Velocity, FreeMarker, JasperReports, BSH, Groovy, JRuby, Quartz, EHCache)

spring-web.jar
这个jar 文件包含Web 应用开发时,用到Spring 框架时所需的核心类,包括自动载入Web Application Context 特性的类、Struts 与JSF 集成类、文件上传的支持类、Filter 类和大量工具辅助类。
外部依赖spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。

spring-webmvc.jar
这个jar 文件包含Spring MVC 框架相关的所有类。包括框架的Servlets,Web MVC框架,控制器和视图支持。当然,如果你的应用使用了独立的MVC 框架,则无需这个JAR 文件里的任何类。
外部依赖spring-web, (spring-support,Tiles,iText,POI)。

Mybatis需要的jar,mybatis-spring1.2.1.jar用于spring整合mybatis框架
这里写图片描述
jstl需要的jar,主要开发中,SSH框架习惯用Struts2提供的标签,SSM框架习惯用JSTL
这里写图片描述
Log4j需要的jar:
这里写图片描述
另外加入:aspectjweaver.jar:
aspectjweaver.jar是spring集成AspectJ LTW织入器所需包

需要AOP动态代理的需要加入:
cglib-nodep.jar

阿里连接池框架加入:druid.jar

权限安全框架Shiro加入:shiro.jar

Json解析需要加入的jar有:
这里写图片描述

这里写图片描述
新建一个resource的资源文件
配置mybatis和spring
ok,现在配置XML
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">
<!-- MyBatis的配置文件 -->
<configuration>

	<settings> 
        <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->   
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings>
<!-- 这些根据项目需要进行配置 -->
	<typeAliases>
		<typeAlias type="com.appms.entity.User" alias="User"/>
		<typeAlias type="com.appms.entity.Role" alias="Role"/>
		<typeAlias type="com.appms.entity.Menu" alias="Menu"/>
		<typeAlias type="com.appms.entity.Member" alias="Member"/>
		<typeAlias type="com.appms.entity.Knowledge" alias="Knowledge"/>
		<typeAlias type="com.appms.entity.Produce" alias="Produce"/>
		<typeAlias type="com.appms.entity.News" alias="News" />
		<typeAlias type="com.appms.entity.GroupClassify" alias="GroupClassify"/>
		<typeAlias type="com.appms.entity.GroupPost" alias="GroupPost"/>
		<typeAlias type="com.appms.entity.Period" alias="Period"/>
		<typeAlias type="com.appms.entity.KLClassify" alias="KLClassify"/>
		<typeAlias type="com.appms.entity.Knowledge" alias="Knowledge"/>
		<typeAlias type="com.appms.entity.Video" alias="Video"/>
		<typeAlias type="com.appms.entity.VideoClassify" alias="VideoClassify"/>
		<typeAlias type="com.appms.entity.Retroaction" alias="Retroaction"/>
		<typeAlias type="com.appms.entity.PageData" alias="pd"/>
		<typeAlias type="com.appms.entity.Page" alias="Page"/>
	</typeAliases>
	
	<!-- -->
	<plugins>
		<plugin interceptor="com.appms.plugin.PagePlugin">
			<property name="dialect" value="mysql"/>
			<property name="pageSqlId" value=".*listPage.*"/>
		</plugin>
	</plugins>
	
</configuration>

SpringMVC的配置:

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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">
	
	<mvc:annotation-driven/>	
	<mvc:default-servlet-handler/>
	
	<context:component-scan base-package="com.appms.controller" />

	<!-- 对静态资源文件的访问  restful-->     
	<mvc:resources mapping="/assets/**" location="/,/assets/" />
	<mvc:resources mapping="/admin/**" location="/,/admin/" />
	<mvc:resources mapping="/source/**" location="/,/source/" />
	<mvc:resources mapping="/images/**" location="/,/images/" />
	<mvc:resources mapping="/music/**" location="/,/music/" />
	<mvc:resources mapping="/uploadFile/**" location="/,/uploadFile/" />
	<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
	<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" /> 

	<!-- 访问拦截 
  	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**/**"/>
			<bean class="com.appweb.interceptor.LoginHandlerInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>
	  -->  
	 
	<!-- 配置SpringMVC的视图解析器 -->
	<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" />  
	
</beans>

Spring的配置:

<?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.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx.xsd">
	
		<!-- 启用注解 -->
	<context:annotation-config />
	
	<!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
	<context:component-scan base-package="com.appms">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
    	<property name="dataSource" ref="dataSource"></property>
 	</bean>
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
		<property name="locations">  
			<list>  
                 <value>/WEB-INF/classes/dbconfig.properties</value>  
            </list>  
        </property>  
	</bean> 
	
	<!-- 阿里 druid数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">  
         <!-- 数据库基本信息配置 -->
         <property name="url" value="${url}" />  
         <property name="username" value="${username}" />  
         <property name="password" value="${password}" />  
         <property name="driverClassName" value="${driverClassName}" />  
         <property name="filters" value="${filters}" />  
   		 <!-- 最大并发连接数 -->
         <property name="maxActive" value="${maxActive}" />
         <!-- 初始化连接数量 -->
         <property name="initialSize" value="${initialSize}" />
         <!-- 配置获取连接等待超时的时间 -->
         <property name="maxWait" value="${maxWait}" />
         <!-- 最小空闲连接数 -->
         <property name="minIdle" value="${minIdle}" />  
   		 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />  
         <property name="validationQuery" value="${validationQuery}" />  
         <property name="testWhileIdle" value="${testWhileIdle}" />  
         <property name="testOnBorrow" value="${testOnBorrow}" />  
         <property name="testOnReturn" value="${testOnReturn}" />  
         <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
         <!-- 打开removeAbandoned功能 -->
         <property name="removeAbandoned" value="${removeAbandoned}" />
         <!-- 1800秒,也就是30分钟 -->
         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
         <!-- 关闭abanded连接时输出错误日志 -->   
         <property name="logAbandoned" value="${logAbandoned}" />
	</bean>  
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception"/>
			<tx:method name="insert*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>
	
	<aop:aspectj-autoproxy proxy-target-class="true"/>
	
	<!-- 事物处理 -->
	<aop:config>
		<aop:pointcut id="pc" expression="execution(* com.appms.service..*(..))" />
		<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
	</aop:config>
	
	<!-- 配置mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- mapper扫描 -->
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
    </bean>
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>
	
	<!--  Shiro start  -->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="ShiroRealm" />
		</bean>
		
		<!-- 項目自定义的Realm -->
	    <bean id="ShiroRealm" class="com.appms.shiro.ShiroRealm" ></bean>
		
		<!-- Shiro Filter -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<property name="securityManager" ref="securityManager" />
			
			<property name="loginUrl" value="/" />
			
			<property name="successUrl" value="/main/index" />
			
			<property name="unauthorizedUrl" value="/login_toLogin" />
			
			<property name="filterChainDefinitions">
				<value>
				/source/**					= anon
				/images/** 					= anon
				/music/**					= anon
				/uploadFiles/**				= anon
				/plugins/** 				= anon
				/uploadFiles/**			 	= anon
	           	/code.do 					= anon
	           	/login_login	 			= anon
	           	/**							= authc
				</value>
			</property>
		</bean>
	<!--  Shiro end  -->
	
   
</beans>

jsbc和log4j的配置

url:jdbc:mysql://127.0.0.1:3306/db_app?autoReconnect=true&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 
driverClassName:com.mysql.jdbc.Driver
username:root
password:root
       
filters:stat
   
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
maxIdle:15
   
timeBetweenEvictionRunsMillis:60000
minEvictableIdleTimeMillis:300000
   
validationQuery:SELECT 'x'
testWhileIdle:true
testOnBorrow:false
testOnReturn:false

maxOpenPreparedStatements:20
removeAbandoned:true
removeAbandonedTimeout:1800
logAbandoned:true

log4j配置

### set log levels ### 
log4j.rootLogger = info , Console , D
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sql.PreparedStatement=INFO
#output2file
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 
log4j.appender.D.File = D\:/logs/log.log 
log4j.appender.D.Append = true 
log4j.appender.D.Threshold = INFO \#\# \u8F93\u51FAinfo\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7 
log4j.appender.D.layout = org.apache.log4j.PatternLayout 
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n 
 

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>AppManagerSystem</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/ApplicationContext.xml</param-value>
  </context-param>
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <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>
  <!-- 连接池 启用Web监控统计功能 -->
  <filter>
    <filter-name>DruidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
      <param-name>exclusions</param-name>
      <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>DruidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>
  <!-- -->
  <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.appms.filter.LoginFilter</filter-class>
  </filter>
  <filter>
    <filter-name>startFilter</filter-name>
    <filter-class>com.appms.filter.StartFilter</filter-class>
  </filter>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <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:spring/ApplicationContext-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>
			org.springframework.web.filter.DelegatingFilterProxy
		</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <session-config>
    <session-timeout>600</session-timeout>
  </session-config>
</web-app>

现在以Dao代理的方式实习数据获取

package com.appms.dao;

public interface DAO {
	
	/**
	 * 保存对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object save(String str, Object obj) throws Exception;
	
	/**
	 * 修改对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object update(String str, Object obj) throws Exception;
	
	/**
	 * 删除对象 
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object delete(String str, Object obj) throws Exception;

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForObject(String str, Object obj) throws Exception;

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForList(String str, Object obj) throws Exception;
	
	/**
	 * 查找对象封装成Map
	 * @param s
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForMap(String sql, Object obj, String key , String value) throws Exception;
	
}

DaoSupport.java

package com.appms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

@Repository("daoSupport")
public class DaoSupport implements DAO {

	@Resource(name = "sqlSessionTemplate")
	private SqlSessionTemplate sqlSessionTemplate;
	
	/**
	 * 保存对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object save(String str, Object obj) throws Exception {
		return sqlSessionTemplate.insert(str, obj);
	}
	
	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object batchSave(String str, List objs )throws Exception{
		return sqlSessionTemplate.insert(str, objs);
	}
	
	/**
	 * 修改对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object update(String str, Object obj) throws Exception {
		return sqlSessionTemplate.update(str, obj);
	}

	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public void batchUpdate(String str, List objs )throws Exception{
		SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
		//批量执行器
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
		try{
			if(objs!=null){
				for(int i=0,size=objs.size();i<size;i++){
					sqlSession.update(str, objs.get(i));
				}
				sqlSession.flushStatements();
				sqlSession.commit();
				sqlSession.clearCache();
			}
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object batchDelete(String str, List objs )throws Exception{
		return sqlSessionTemplate.delete(str, objs);
	}
	
	/**
	 * 删除对象 
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object delete(String str, Object obj) throws Exception {
		return sqlSessionTemplate.delete(str, obj);
	}
	 
	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForObject(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectOne(str, obj);
	}

	/**
	 * 查找对象
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object findForList(String str, Object obj) throws Exception {
		return sqlSessionTemplate.selectList(str, obj);
	}
	
	public Object findForMap(String str, Object obj, String key, String value) throws Exception {
		return sqlSessionTemplate.selectMap(str, obj, key);
	}
	
}

写个实体信息类:

package com.appms.entity;

import java.util.List;

public class Member {
	
	/**
	 * 会员账号
	 */
	private String memberID;
	
	/**
	 * 会员密码
	 */
	private String password;
	
	/**
	 * 会员级别
	 */
	private String rank;
	
	/**
	 * 会员积分
	 */
	private int credit;
	
	/**
	 * 会员手机号
	 */
	private String phone;
	
	/**
	 * 会员皮肤
	 */
	private String imgPath;
	
	/**
	 * 邮箱
	 */
	private String email;
	
	private List<GroupPost> postes;

	private List<Retroaction> retroaction;
	
	public String getMemberID() {
		return memberID;
	}

	public void setMemberID(String memberID) {
		this.memberID = memberID;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRank() {
		return rank;
	}

	public void setRank(String rank) {
		this.rank = rank;
	}

	public int getCredit() {
		return credit;
	}

	public void setCredit(int credit) {
		this.credit = credit;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getImgPath() {
		return imgPath;
	}

	public void setImgPath(String imgPath) {
		this.imgPath = imgPath;
	}
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public List<GroupPost> getPostes() {
		return postes;
	}

	public void setPostes(List<GroupPost> postes) {
		this.postes = postes;
	}

	public List<Retroaction> getRetroaction() {
		return retroaction;
	}

	public void setRetroaction(List<Retroaction> retroaction) {
		this.retroaction = retroaction;
	}
	
}

其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="MemberMapper">

	<resultMap type="Member" id="memberResultMap">
		<id column="memberID" property="memberID"/>
		<result column="password" property="password"/>
		<result column="rank" property="rank"/>
		<result column ="credit" property="credit"/>
		<result column="phone" property="phone"/>
		<result column="imgPath" property="imgPath"/>
		<result column="email" property="email"/>
		<collection property="postes" ofType="GroupPost">
			<id column="postID" property="postID"/>
			<result column="postTitle" property="postTitle"/>
			<result column="postContent" property="postContent"/>
			<result column="likeAmount" property="likeAmount"/>
			<result column="commentAmount" property="commentAmount"/>
			<result column="commitTime" property="commitTime"/>
		</collection>
		<collection property="retroaction" ofType="Retroaction">
			<id column="rID" property="rID" />
			<result column="content" property="content" />
			<result column="commitTime" property="commitTime" />
		</collection>
	</resultMap>
	
	<!-- 修改 -->
	<update id="editM" parameterType="pd" flushCache="false">
		update tb_members
			set memberID			= #{memberID},
				password			= #{password},
				rank				= #{rank},
				credit 				= #{credit},
				phone				= #{phone}
		where
			memberID = #{memberID}
	</update>
	
	<!-- 通过会员账号获取数据 -->
	<select id="findByMId" parameterType="pd" resultType="pd" useCache="false">
		select
			p.memberID,
			p.password,
			p.rank,
			p.credit,
			p.phone,
			p.imgPath
		from
			tb_members p
		where
			memberID = #{memberID}
	</select>
	
	<!-- 删除会员信息 -->
	<delete id="deleteM" parameterType="String" flushCache="false">
		delete from tb_members
		where 
		memberID = #{memberID}
	</delete>
	
	<!-- 批量删除会员信息 -->
	<delete id="deleteAllM" parameterType="String" flushCache="false">
		delete from tb_members
		where memberID in
		<foreach item="item" index="index" collection="array" open="(" separator="," close=")">
			#{item}
		</foreach>
	</delete>
	
	<!-- 用户信息列表(全部) -->
	<select id="memberListPage" parameterType="page" resultType="pd" useCache="false">
		select m.memberID,
			   m.password,
			   m.rank,
			   m.credit,
			   m.phone,
			   m.imgPath
		from tb_members m
	</select>
	
	<!-- 用户信息列表 -->
	<select id="memberList" parameterType="pd" resultType="pd" useCache="false">
		select m.memberID,
			   m.password,
			   m.rank,
			   m.credit,
			   m.phone
		from tb_members m
	</select>
	
	<!-- 按月统计注册用户数量 -->
	<select id="queryCount" parameterType="String" resultType="Long">
		select year(regTime),
			   count(*) 
		from tb_member group by year(regTime) 
	</select>
	
	<!-- 搜索会员信息 -->
	<select id="queryMemberInfo" parameterType="pd" resultType="pd" useCache="false">
		select m.memberID,
			   m.password,
			   m.rank,
			   m.phone,
			   m.imgPath
		from tb_members m 
		where m.memberID like "%"#{keyword}"%"
	</select>
	
</mapper>

写个BaseController:

package com.appms.base;


import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.appms.entity.Page;
import com.appms.entity.PageData;
import com.appms.logger.Logger;
import com.appms.utils.UuidUtil;

public class BaseController {
	
	protected Logger logger = Logger.getLogger(this.getClass());

	private static final long serialVersionUID = 6357869213649815390L;
	
	/**
	 * 得到PageData
	 */
	public PageData getPageData(){
		return new PageData(this.getRequest());
	}
	
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return new ModelAndView();
	}
	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
		return request;
	}

	/**
	 * 得到32位的uuid
	 * @return
	 */
	public String get32UUID(){
		
		return UuidUtil.get32UUID();
	}
	
	/**
	 * 得到分页列表的信息 
	 */
	public Page getPage(){
		return new Page();
	}
	
	public static void logBefore(Logger logger, String interfaceName){
		logger.info("");
		logger.info("start");
		logger.info(interfaceName);
	}
	
	public static void logAfter(Logger logger){
		logger.info("end");
		logger.info("");
	}
	
}

业务层代码Service:

package com.appms.service.member;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.appms.dao.DaoSupport;
import com.appms.entity.Member;
import com.appms.entity.Page;
import com.appms.entity.PageData;

@Service("memberService")
public class MemberService {

	@Resource(name="daoSupport")
	DaoSupport dao;
	
	/**
	 * 通过会员账号获取信息
	 */
	public PageData findByUId(PageData pd) throws Exception{
		return (PageData)dao.findForObject("MemberMapper.findByMId", pd);
	}
	
	/**
	 * 修改会员信息
	 */
	public void editM(PageData pd)throws Exception{
		dao.update("MemberMapper.editM", pd);
	}
	
	/**
	 * 删除会员信息
	 */
	public void deleteM(PageData pd)throws Exception{
		dao.delete("MemberMapper.deleteM", pd);
	}
	
	/**
	 * 批量删除会员信息
	 */
	public void deleteAllM(String[] mids)throws Exception{
		dao.delete("MemberMapper.deleteAllM",mids);
	}
	
	/**
	 * 会员信息列表
	 */
	public List<PageData> listPdPageM(Page page)throws Exception{
		return (List<PageData>)dao.findForList("MemberMapper.memberListPage", page);
	}
	
	/**
	 * 会员信息列表
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> listM(PageData pd)throws Exception{
		return (List<PageData>)dao.findForList("MemberMapper.memberList", pd);
	}
	
	public List<Long> getCount()throws Exception{
		return (List<Long>)dao.findForObject("MemberMapper.queryCount", null);
	}
	
	
	/**
	 * 模糊查询
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<PageData> queryM(PageData pd)throws Exception{
		return (List<PageData>)dao.findForList("MemberMapper.queryMemberInfo", pd);
	}
	
}

Controller层代码:

package com.appms.controller.member;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

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

import com.appms.base.BaseController;
import com.appms.entity.Page;
import com.appms.entity.PageData;
import com.appms.service.member.MemberService;
import com.appms.utils.AppUtil;
import com.appms.view.ObjectExcelView;

@Controller
@RequestMapping(value="/member")
public class MemberController extends BaseController{
	
	@Resource(name="memberService")
	private MemberService memberService;
	
	/**
	 * 编辑会员信息
	 */
	@RequestMapping(value="/editM",produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object editM()throws Exception{
		Map<String,String> map = new HashMap<String, String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYDATA[] = pd.get("KEYDATA").toString().split(",");
		pd.put("memberID", KEYDATA[0]);
		pd.put("password", KEYDATA[1]);
		pd.put("rank", KEYDATA[2]);
		pd.put("credit", KEYDATA[3]);
		pd.put("phone", KEYDATA[4]);
		memberService.editM(pd);
		map.put("result", "success");
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 跳转到编辑页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goEditM")
	public ModelAndView goEditM()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String ID = pd.getString("memberID");
		
		if(null != ID&& !"".equals(ID)){
			ID = ID.trim();
			pd.put("memberID", ID);
			pd = memberService.findByUId(pd);
			mv.setViewName("/member/member_edit");	
			mv.addObject("pd",pd);
		}
		return mv;
	}
	
	/**
	 * 是否存在会员信息
	 */
	@RequestMapping(value="/hasM")
	@ResponseBody
	public Object hasM() throws Exception{
		return null;
	}
	
	/**
	 * 获取所有的会员信息
	 */
	@RequestMapping(value="/listMember")
	public ModelAndView listMemberInfo(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String memberID = pd.getString("memberID");
		if(null != memberID && !"".equals(memberID)){
			memberID = memberID.trim();
			pd.put("memberID", memberID);
		}
		page.setShowCount(5);
		page.setPd(pd);
		mv.addObject("page",page);
		List<PageData> infoList = memberService.listPdPageM(page);
		mv.setViewName("/member/member_list");
		mv.addObject("memberInfoList",infoList);
		mv.addObject("pd", pd);
		return mv;
	}
	
	/**
	 * 模糊查询
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryM")
	public ModelAndView queryM()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String keyword = pd.getString("keyword");
		keyword = new String(keyword.getBytes("iso-8859-1"),"UTF-8");
		if(keyword!=null&&!"".equals(keyword)){
			keyword = keyword.trim();
			pd.put("keyword", keyword);
			List<PageData> memberInfo = memberService.queryM(pd);
			mv.setViewName("member/member_list");
			mv.addObject("memberInfoList", memberInfo);
		}
		return mv;
	}
	
	/**
	 * 导出Excel
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportExcel")
	public ModelAndView exportExcel()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		//检索条件
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		
		titles.add("用户名");
		titles.add("密码");
		titles.add("级别");
		titles.add("积分");
		titles.add("手机号");
		
		dataMap.put("titles", titles);
		
		List<PageData> memberList = memberService.listM(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<memberList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", memberList.get(i).getString("memberID"));
			vpd.put("var2", memberList.get(i).getString("password"));
			vpd.put("var3", memberList.get(i).getString("rank"));
			vpd.put("var4", memberList.get(i).get("credit").toString());
			vpd.put("var5", memberList.get(i).getString("phone"));
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		
		return mv;
	}
	
}

为了代码安全性,将jsp全部放在WEB-INF下面:

这里写图片描述
jsp页面代码,用cstl获取数据

<%@page import="com.appms.base.Const"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!doctype html>
<html>
<head>
	<base href="<%=basePath %>">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>${pd.SYSNAME}</title>
  <meta name="description" content="这是一个 index 页面">
  <meta name="keywords" content="index">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <link rel="icon" type="image/png" href="assets/i/favicon.png">
  <link rel="apple-touch-icon-precomposed" href="assets/i/app-icon72x72@2x.png">
  <meta name="apple-mobile-web-app-title" content="Amaze UI" />
  <link rel="stylesheet" href="assets/css/amazeui.min.css"/>
  <link rel="stylesheet" href="assets/css/admin.css">
  <script type="text/javascript">window.jQuery || document.write("<script src='source/js/jquery-1.9.1.min.js'>\x3C/script>");</script>
  <script type="text/javascript" src="source/js/jquery.tips.js"></script><!--提示框-->
 
</head>
<body>
<!--[if lte IE 9]>
<p class="browsehappy">你正在使用<strong>过时</strong>的浏览器,Amaze UI 暂不支持。 请 <a href="http://browsehappy.com/" target="_blank">升级浏览器</a>
  以获得更好的体验!</p>
<![endif]-->

   <!-- 页面顶部¨ -->
   <%@ include file="../admin/head.jsp"%>

<div class="am-cf admin-main">
  
  <!-- 左侧菜单• -->
  <%@ include file="../admin/left.jsp"%>
		
  <!-- content start -->
  <div class="admin-content">

    <div class="am-cf am-padding">
      <div class="am-fl am-cf"><strong class="am-text-primary am-text-lg"><a href="main/index">首页</a></strong> / <small>会员管理</small></div>
    </div>

    <div class="am-g">
      <div class="am-u-md-6 am-cf">
        <div class="am-fl am-cf">
          <div class="am-btn-toolbar am-fl">
            <div class="am-btn-group am-btn-group-xs">
              <a class="am-btn am-btn-default" href="member/exportExcel.do" style="background-color: white;"><span class="am-icon-save"></span>导出Excel</a>
            </div>
          </div>
        </div>
      </div>
      <div class="am-u-md-3 am-cf">
        <div class="am-fr">
          <div class="am-input-group am-input-group-sm">
            <input type="text" class="am-form-field" id="keyword"/>
                <span class="am-input-group-btn">
                  <input type="button" class="am-btn am-btn-default" onclick="queryInfo();" value="搜索" />
                </span>
          </div>
        </div>
      </div>
    </div>

    <div class="am-g">
      <div class="am-u-sm-12">
        <form class="am-form">
          <table class="am-table am-table-striped am-table-hover table-main">
            <thead>
              <tr>
              	<th>图片</th>
                <th>账号</th>
                <th>密码</th>
                <th>级别</th>
                <th>积分</th>
                <th>手机</th>
                <th>操作</th>
              </tr>
          </thead>
          <tbody>
          <c:choose>
          	<c:when test="${not empty memberInfoList}">
          	<c:forEach items="${memberInfoList}" var="u" varStatus="vs">
            <tr>
              <td><img src="${pageContext.request.contextPath}${u.imgPath}" width="30px" height="30px" /></td>
              <td>${u.memberID}</td>
              <td>${u.password}</td>
              <td>${u.rank}</td>
              <td>${u.credit}</td>
              <td>${u.phone}</td>
              <td>
                <div class="am-btn-toolbar">
                  <div class="am-btn-group am-btn-group-xs">
                    <a href="member/goEditM.do?memberID=${u.memberID}" style="background-color: white;" class="am-btn am-btn-default am-btn-xs am-text-secondary"><span class="am-icon-pencil-square-o"></span> 编辑</a>
                  </div>
                </div>
              </td>
            </tr>
           
            </c:forEach>
            </c:when>
            <c:otherwise>
			<tr class="main_info">
				<td colspan="10">没有相关数据</td>
			</tr>
			</c:otherwise>
          </c:choose>
          </tbody>
        </table>
          <div class="am-cf">
  共 15 条记录
  <div class="am-fr">
    <ul class="am-pagination">
      <li class="am-disabled"><a href="#">«</a></li>
      <li><a href="#">1</a></li>
      <li><a href="#">2</a></li>
      <li><a href="#">3</a></li>
      <li><a href="#">4</a></li>
      <li><a href="#">5</a></li>
      <li><a href="#">»</a></li>
    </ul>
  </div>
</div>
          <hr />
          <p>注:.....</p>
        </form>
      </div>

    </div>
  </div>
  <!-- content end -->

</div>

<footer>
  <hr>
  <p class="am-padding-left">© 2017 E创工作室开发. <a href="http://www.mianfeimoban.com/" target="_blank">网站模板</a></p>
</footer>
<script type="text/javascript">
	function queryInfo(){
		var keyword = $("#keyword").val();
		window.location.href="member/queryM.do?keyword="+keyword;
	}
</script>
<!--[if lt IE 9]>
<script src="assets/js/jquery1.11.1.min.js"></script>
<script src="assets/js/modernizr.js"></script>
<script src="assets/js/polyfill/rem.min.js"></script>
<script src="assets/js/polyfill/respond.min.js"></script>
<script src="assets/js/amazeui.legacy.js"></script>
<![endif]-->

<!--[if (gte IE 9)|!(IE)]><!-->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/amazeui.min.js"></script>
<!--<![endif]-->
<script src="assets/js/app.js"></script>
</body>
</html>

这里写图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smileNicky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值