java:Spring框架3(AOP,SSH集成Demo)

1.AOP:

 

 Spring提供了4种实现AOP的方式:
    1.经典的基于代理的AOP
    2.@AspectJ注解驱动的切面
    3.纯POJO切面
    4.注入式AspectJ切面

  aop.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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 被代理目标 -->     
   <bean id="myService"  class="cn.zzsxt.aop2.MyServiceImpl"></bean>
   <!-- 前置通知(需要运行时动态织入的公共代码) -->
   <bean id="loggerAdvice" class="cn.zzsxt.aop2.MyBeforeAdvice"></bean>
   <!-- 后置通知 -->
   <bean id="myAfterAdvice" class="cn.zzsxt.aop2.MyAfterAdvice"></bean>
   <!-- 环绕通知 -->
   <bean id="myArroundAdvice" class="cn.zzsxt.aop2.MyArroundAdvice"></bean>
   <!-- 异常通知 -->
   <bean id="myThrowsAdivce" class="cn.zzsxt.aop2.MyThrowsAdvice"></bean>
   <aop:config>
               <!-- 
             配置切入点:限定通知织入业务方法的时机
             execution(* cn.zzsxt.aop2.*.*(..))
             第一个*代表:返回值类型,*可以匹配所有的返回值类型
             cn.zzsxt.aop2:被代理目标所在包
             第二个*代表:代表包的类,*可以匹配该包下的所有类或接口
             第三个*代表:代表类中的方法,*可以匹配该类下的所有方法
             ..代表方法中的参数    ..可以匹配所有的参数类型
              -->
           <aop:pointcut expression="execution(* cn.zzsxt.aop2.*.*(..))" id="mypointcut"/>
           <!-- 将通知和切入点告知给通知者 -->
           <aop:advisor advice-ref="loggerAdvice" pointcut-ref="mypointcut"/>
           <aop:advisor advice-ref="myAfterAdvice" pointcut-ref="mypointcut"/>
           <aop:advisor advice-ref="myArroundAdvice" pointcut-ref="mypointcut"/>
           <aop:advisor advice-ref="myThrowsAdivce" pointcut-ref="mypointcut"/>
   </aop:config>
</beans>        

  ConsoleLogger.java:

package cn.zzsxt.aop;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 日志处理
 * @author Think
 *
 */
public class ConsoleLogger implements Logger {

    @Override
    public void log(Method m) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(now);
        System.out.println(time+"方法["+m.getName()+"]被调用了!");
    }

}

  Logger.java:

package cn.zzsxt.aop;

import java.lang.reflect.Method;

public interface Logger {
    public void log(Method m);
}

  LogInvocation.java:

package cn.zzsxt.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * 使用JDK动态代理
 * @author Think
 *
 */
public class LogInvocation implements InvocationHandler {
    private Object target;//被代理目标
    private Logger logger = new ConsoleLogger();
    public LogInvocation(Object target){
        this.target=target;
    }
    /**
     * 生成代理
     * @return
     */
    public Object createProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //打印日志
        logger.log(method);
        //回调被代理目标的中的方法
        return method.invoke(target, args);
    }
    
    public static void main(String[] args) {
        //创建代理
        LogInvocation logInvocation = new LogInvocation(new MyServiceImpl());
        MyService myService = (MyService)logInvocation.createProxy();
        myService.login();
    }

}

  MyService.java:

package cn.zzsxt.aop;

public interface MyService {
    public void login();
}

  MyServiceImpl.java:

package cn.zzsxt.aop;

public class MyServiceImpl implements MyService {

    @Override
    public void login() {
        System.out.println("执行了login方法....");
    }

}

  

  aop2.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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 被代理目标 -->     
   <bean id="myService"  class="cn.zzsxt.aop3.MyServiceImpl"></bean>
   <!-- 定义通知 -->
   <bean id="myAdvice" class="cn.zzsxt.aop3.MyAdvice"></bean>
   <aop:config>
           <aop:pointcut expression="execution(* cn.zzsxt.aop3.*.*(..))" id="mypointcut"/>
           <!-- ref="通知的id" -->
           <aop:aspect ref="myAdvice">
               <!-- 前置通知 -->
               <aop:before method="before" pointcut="execution(* cn.zzsxt.aop3.*.login(..))"/>
               <!-- 后置通知 -->
               <aop:after-returning method="afterReturing" pointcut-ref="mypointcut"/>
               <!-- 环绕通知 -->
               <aop:around method="arround" pointcut-ref="mypointcut"/>
               <!-- 最终通知 -->
               <aop:after method="afterFinally" pointcut-ref="mypointcut"/>
               <!-- 异常通知 -->
               <aop:after-throwing method="afterThrow" pointcut-ref="mypointcut"/>
           </aop:aspect>
   </aop:config>
</beans>        

  MyAfterAdvice.java:

package cn.zzsxt.aop2;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
/**
 * 后置通知
 * @author Think
 *
 */
public class MyAfterAdvice implements AfterReturningAdvice {

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
         System.out.println("后置通知.....MyAfterAdvice..");
    }

}

  MyArroundAdvice.java:

package cn.zzsxt.aop2;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;


public class MyArroundAdvice implements MethodInterceptor{

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("MyArroundAdvice.....before....");
        Object value = methodInvocation.proceed();//执行被代理目标中的方法
        System.out.println("MyArroundAdvice....after...");
        return value;
    }

    
}

  MyBeforeAdvice.java:

package cn.zzsxt.aop2;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.aop.MethodBeforeAdvice;

public class MyBeforeAdvice implements MethodBeforeAdvice {

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(now);
        System.out.println(time+"方法["+method.getName()+"]被调用了!");
    }

}

  MyService.java:

package cn.zzsxt.aop2;

public interface MyService {
    public void login();
    public void testThrows(int flag);
}

  MyServiceImpl.java:

package cn.zzsxt.aop2;

public class MyServiceImpl implements MyService {

    @Override
    public void login() {
        System.out.println("执行了login方法....");
    }

    //测试异常通知
    public void testThrows(int flag) {
        if(flag>0){
            throw new NullPointerException("空指针异常,不能为空对象进行操作!");
        }
        throw new IndexOutOfBoundsException("下标越界异常!");
    }
}

  MyThrowsAdvice.java:

package cn.zzsxt.aop2;

import org.springframework.aop.ThrowsAdvice;

public class MyThrowsAdvice implements ThrowsAdvice {
    /**
     * 空指针异常
     * @param e
     */
    public void afterThrowing(NullPointerException e){
        System.out.println(e.getMessage());
    }
    
    /**
     * 下标越界异常
     * @param e
     */
    public void afterThrowing(IndexOutOfBoundsException e){
        System.out.println(e.getMessage());
    }
    
}

  Test.java:

package cn.zzsxt.aop2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("aop.xml");
        MyService myService = ac.getBean(MyService.class,"myService");
        myService.login();
        System.out.println("---------------------------------");
        myService.testThrows(1);
    }
}

Package : aop3:

  MyAdvice.java:

package cn.zzsxt.aop3;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
    //前置通知
    public void before(){
        System.out.println("前置通知....before()方法");
    }
    //后置通知
    public void afterReturing(){
        System.out.println("后置通知....afterReturing()方法");
    }
    //环绕通知
    public void arround(ProceedingJoinPoint pjp){
        System.out.println("环绕通知....before...");
        try {
            pjp.proceed();//执行目标方法
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("环绕通知....after...");
    }
    //异常通知
    public void afterThrow(){
        System.out.println("异常通知......");
    }    
    //最终通知
    public void afterFinally(){
        System.out.println("最终通知.....");
    }        
    
}

  MyService.java:

package cn.zzsxt.aop3;

public interface MyService {
    public void login();
    public void testThrows(int flag);
}

  MyServiceImpl.java:

package cn.zzsxt.aop3;

public class MyServiceImpl implements MyService {

    @Override
    public void login() {
        System.out.println("执行了login方法....");
    }

    //测试异常通知
    public void testThrows(int flag) {
        if(flag>0){
            throw new NullPointerException("空指针异常,不能为空对象进行操作!");
        }
        throw new IndexOutOfBoundsException("下标越界异常!");
    }
}

  Test.java:

package cn.zzsxt.aop3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("aop2.xml");
        MyService myService = ac.getBean(MyService.class,"myService");
        myService.login();
        System.out.println("------------------");
        myService.testThrows(1);
    }
}

  

  aop4.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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 开启切面的自动扫描 -->
  
   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
   <!-- 被代理目标 -->     
   <bean id="myService"  class="cn.zzsxt.aop4.MyServiceImpl"></bean>
   <bean id="myAdvice"  class="cn.zzsxt.aop4.MyAnnotationLogger"></bean>
  
</beans>        

  MyAnnotationLogger.java:

package cn.zzsxt.aop4;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//<bean id="myAdvice" class="cn.zzsxt.aop3.MyAdvice"></bean>
@Aspect
public class MyAnnotationLogger {
        
        //前置通知
        @Before("execution(* cn.zzsxt.aop4.*.*(..))")
        public void before(){
            System.out.println("前置通知....before()方法");
        }
        //后置通知
        @AfterReturning(value="execution(* cn.zzsxt.aop4.*.*(..))",returning="value")
        public void afterReturing(){
            System.out.println("后置通知....afterReturing()方法");
        }
        
        //环绕通知
        @Around("execution(* cn.zzsxt.aop4.*.*(..))")
        public void arround(ProceedingJoinPoint pjp){
            System.out.println("环绕通知....before...");
            try {
                pjp.proceed();//执行目标方法
            } catch (Throwable e) {
                e.printStackTrace();
            }
            System.out.println("环绕通知....after...");
        }
        //异常通知
        @AfterThrowing(value="execution(* cn.zzsxt.aop4.*.*(..))",throwing="e")
        public void afterThrow(Exception e){
            System.out.println("异常通知......");
        }    
        
        //最终通知
        @After("execution(* cn.zzsxt.aop4.*.*(..))")
        public void afterFinally(){
            System.out.println("最终通知.....");
        }        
        
}

  MyService.java:

package cn.zzsxt.aop4;

public interface MyService {
    public void login();
    public void testThrows(int flag);
}

  MyServiceImpl.java:

package cn.zzsxt.aop4;

public class MyServiceImpl implements MyService {

    @Override
    public void login() {
        System.out.println("执行了login方法....");
    }

    //测试异常通知
    public void testThrows(int flag) {
        if(flag>0){
            throw new NullPointerException("空指针异常,不能为空对象进行操作!");
        }
        throw new IndexOutOfBoundsException("下标越界异常!");
    }
}

  Test.java:

package cn.zzsxt.aop4;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("aop4.xml");
        MyService myService = ac.getBean(MyService.class,"myService");
        myService.login();
    }
}
 

2.SSH集成Demo:

    

  jar大概:

  

   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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 1.加载jdbc.properties文件(可选) -->    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>
    <!-- 2.配置数据源 dataSource -->    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${driver}"></property>
        <property name="jdbcUrl" value="${url}"></property>
        <property name="user" value="${username}"></property>
        <property name="password" value="${password}"></property>
    </bean>
    <!-- 3.配置sessionFactory,并注入数据源 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>cn/zzsxt/ssh/entity/Userinfo.hbm.xml</value>
            </list>
        </property>
    </bean>
    <!-- 4.配置hibernateTemplate,并注入sessionFactory -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 5.配置Dao,并注入hibernateTemplate -->
    <bean id="userinfoDao" class="cn.zzsxt.ssh.dao.impl.UserinfoDaoImpl">
        <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
    <!-- 6.配置Service,并注入Dao -->
    <bean id="userinfoService" class="cn.zzsxt.ssh.service.impl.UserinfoServiceImpl">
        <property name="userinfoDao" ref="userinfoDao"></property>
    </bean>
    <!-- 7.配置Action,并注入Service -->
    <bean id="userinfoAction" class="cn.zzsxt.ssh.action.UserinfoAction" scope="prototype">
        <property name="userinfoService" ref="userinfoService"></property>
    </bean>
    
    
    <!-- 配置spring声明式事务 -->
    <!-- 配置事务管理器 ,注入sessionFactory-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 事务的传播式行为 -->
        <tx:attributes>
<!--             <tx:method name="add*" propagation="REQUIRED"/> -->
<!--             <tx:method name="update*" propagation="REQUIRED"/> -->
<!--             <tx:method name="delete*" propagation="REQUIRED"/> -->
<!--             <tx:method name="get*" propagation="REQUIRED"/> -->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <!-- 定义切入点 -->
        <aop:pointcut expression="execution(* cn.zzsxt.ssh.service.*.*(..))" id="mypoint"/>
        <!-- 将事务通知和切入点告知通知者 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
    </aop:config>
</beans>        

  jdbc.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

  struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="sshDemo" extends="struts-default">
        <!-- 伪类 -->
        <action name="user-*" class="userinfoAction" method="{1}">
            <result name="list">/list.jsp</result>
            <result name="success" type="redirectAction">user-list</result>
            <result name="error">/add.jsp</result>
        </action>
    </package>
</struts>        

  web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>sshDemo</display-name>
  <!-- 配置ContextLoaderListener,解析spring的配置文件,默认在WEB-INF下查找名称为applicationContext.xml -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 指定配置文件的位置 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>
  <!-- struts2的核心过滤器 -->
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  

  UserinfoAction.java:

package cn.zzsxt.ssh.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

import cn.zzsxt.ssh.entity.Userinfo;
import cn.zzsxt.ssh.service.UserinfoService;

public class UserinfoAction extends ActionSupport implements ServletRequestAware{
    private UserinfoService userinfoService;
    private HttpServletRequest request;
    private Userinfo user;
    
    public void setUserinfoService(UserinfoService userinfoService) {
        this.userinfoService = userinfoService;
    }

    public Userinfo getUser() {
        return user;
    }

    public void setUser(Userinfo user) {
        this.user = user;
    }

    /**
     * 查询所有用户
     * @return
     * @throws Exception
     */
    public String list() throws Exception {
        List<Userinfo> list = userinfoService.getAll();
        request.setAttribute("list", list);
        return "list";
    }

    /**
     * 添加用户
     * @return
     * @throws Exception
     */
    public String add() throws Exception {
        int count = userinfoService.add(user);
        if(count>0){
            return this.SUCCESS;
        }
        return this.ERROR;
    }

    @Override
    public void setServletRequest(HttpServletRequest arg0) {
        this.request=arg0;
    }
}

  UserinfoDao.java:

package cn.zzsxt.ssh.dao;

import java.util.List;

import cn.zzsxt.ssh.entity.Userinfo;

public interface UserinfoDao {
    /**
     * 查询所有用户信息
     * @return
     */
    List<Userinfo> getAll();
    /**
     * 根据userId查询用户详情
     * @param userId
     * @return
     */
    Userinfo getById(int userId);
    /**
     * 新增用户
     * @param user
     * @return
     */
    int add(Userinfo user);
    /**
     * 修改用户
     * @param user
     * @return
     */
    int update(Userinfo user);
    
    /**
     * 删除用户
     * @param userId
     * @return
     */
    int delete(int userId);
    
}

  UserinfoDaoImpl.java:

package cn.zzsxt.ssh.dao.impl;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;

import cn.zzsxt.ssh.dao.UserinfoDao;
import cn.zzsxt.ssh.entity.Userinfo;

public class UserinfoDaoImpl  implements UserinfoDao {
    private HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public List<Userinfo> getAll() {
//        List<Userinfo> list = (List<Userinfo>)hibernateTemplate.find("from Userinfo");
        List<Userinfo> list = hibernateTemplate.loadAll(Userinfo.class);
        return list;
    }

    @Override
    public Userinfo getById(int userId) {
        return hibernateTemplate.get(Userinfo.class, userId);
    }

    @Override
    public int add(Userinfo user) {
        int count=0;
        try {
            hibernateTemplate.save(user);
            count=1;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int update(Userinfo user) {
        int count=0;
        try {
            hibernateTemplate.update(user);
            count=1;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int delete(int userId) {
        int count=0;
        try {
            Userinfo user = hibernateTemplate.get(Userinfo.class, userId);
            hibernateTemplate.delete(user);
            count=1;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return count;
    }

}

  Userinfo.java:

package cn.zzsxt.ssh.entity;

import java.io.Serializable;

public class Userinfo implements Serializable{
    private int userId;
    private String userName;
    private String userPass;
    private int userType;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPass() {
        return userPass;
    }
    public void setUserPass(String userPass) {
        this.userPass = userPass;
    }
    public int getUserType() {
        return userType;
    }
    public void setUserType(int userType) {
        this.userType = userType;
    }
    
}

  Userinfo.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="cn.zzsxt.ssh.entity.Userinfo">
        <id name="userId">
            <generator class="native"></generator>
        </id>
        <property name="userName"></property>
        <property name="userPass"></property>
        <property name="userType"></property>
    </class>
</hibernate-mapping>    

  UserinfoService.java:

package cn.zzsxt.ssh.service;

import java.util.List;

import cn.zzsxt.ssh.entity.Userinfo;

public interface UserinfoService {
    /**
     * 查询所有用户信息
     * @return
     */
    List<Userinfo> getAll();
    /**
     * 根据userId查询用户详情
     * @param userId
     * @return
     */
    Userinfo getById(int userId);
    /**
     * 新增用户
     * @param user
     * @return
     */
    int add(Userinfo user);
    /**
     * 修改用户
     * @param user
     * @return
     */
    int update(Userinfo user);
    
    /**
     * 删除用户
     * @param userId
     * @return
     */
    int delete(int userId);
}

  UserinfoServiceImpl.java:

package cn.zzsxt.ssh.service.impl;

import java.util.List;

import cn.zzsxt.ssh.dao.UserinfoDao;
import cn.zzsxt.ssh.entity.Userinfo;
import cn.zzsxt.ssh.service.UserinfoService;

public class UserinfoServiceImpl implements UserinfoService {
    private UserinfoDao userinfoDao;
    
    public void setUserinfoDao(UserinfoDao userinfoDao) {
        this.userinfoDao = userinfoDao;
    }

    @Override
    public List<Userinfo> getAll() {
        return userinfoDao.getAll();
    }

    @Override
    public Userinfo getById(int userId) {
        return userinfoDao.getById(userId);
    }

    @Override
    public int add(Userinfo user) {
        return userinfoDao.add(user);
    }

    @Override
    public int update(Userinfo user) {
        return userinfoDao.update(user);
    }

    @Override
    public int delete(int userId) {
        return userinfoDao.delete(userId);
    }

}

  Test:

package cn.zzsxt.ssh.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.zzsxt.ssh.entity.Userinfo;
import cn.zzsxt.ssh.service.UserinfoService;

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserinfoService userinfoService = ac.getBean(UserinfoService.class,"userinfoService");
//        Userinfo user = new Userinfo();
//        user.setUserName("test");
//        user.setUserPass("test");
//        user.setUserType(1);
//        int count = userinfoService.add(user);
//        System.out.println(count);
        List<Userinfo> list = userinfoService.getAll();
        for (Userinfo userinfo : list) {
            System.out.println(userinfo.getUserId()+"--"+userinfo.getUserName()+"--"+userinfo.getUserPass()+"--"+userinfo.getUserType());
        }
    }
}
 

  list.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>
<%
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>
  </head>
  
  <body>
      <table align="center" width="800" border="1">
      <caption>
          <a href="add.jsp">添加</a>
      </caption>
          <tr>
              <th>用户编号</th>
              <th>用户名称</th>
              <th>用户类型</th>
              <th>操作</th>
          </tr>
          <s:if test="#request.list.size==0">
              <tr>
                  <td colspan="4">暂无用户信息!</td>
              </tr>
          </s:if>
          <s:else>
              <s:iterator value="#request.list" var="user">
                  <tr>
                      <td><s:property value="#user.userId"/></td>
                      <td><s:property value="#user.userName"/></td>
                      <td>
                          <s:if test="#user.userType==1">普通用户</s:if>
                          <s:else>VIP用户</s:else>
                      </td>
                      <td>修改 删除</td>
                  </tr>
              </s:iterator>
          </s:else>
      </table>
  </body>
</html>

  

  

原文地址:https://www.cnblogs.com/kuangzhisen/p/7441196.html