利用struts2,mybatis,spring,三大框架写的一个简单的查询程序

来源:互联网 发布:全球风暴 知乎 编辑:程序博客网 时间:2024/05/23 01:12

我们现在开发都是用框架技术,用框架比较方便.可以节省我们很多时间.我用了三大框架写了一个程序,使用maven导的包.大家可以一起学习学习,指点指点.

只是项目结构:


使用框架技术,我们首先就要导包.我是用的是maven导的包 pom.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" 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/context        http://www.springframework.org/schema/context/spring-context.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"><context:annotation-config /><!-- 包名 --><context:component-scan base-package="com.yc" /><!-- 使用spring自带的属性文件读取类完成读取配置文件的操作 --><bean id="pphc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:db.properties" /></bean><!-- 配置dbcp数据源... 数据库联接池 ( jndi-> tomcat的数据库联接池 ) / c3p0 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxActive" value="${jdbc.maxActive}" /><property name="minIdle" value="${jdbc.minIdle}" /><property name="maxIdle" value="${jdbc.maxIdle}" /></bean><!-- 针对 mybaits的整合配置 --><!-- 配置  sqlsessionorg.mybatis.spring.SqlSessionFactoryBean.class --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="mapperLocations" value="classpath*:com/yc/ssm/dao/*.xml"></property></bean><!-- 配置扫描器  用于扫描所有的  mpper文件--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 配置要扫描的映射文件对应的接口目录 --><property name="basePackage" value="com.yc.ssm.dao"></property><!-- 指定  这个  scaaner所使用的   session工厂--><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean><!--  事务管理器 ->jdbc--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/> </bean>   <!-- 配置增强 --><tx:advice id="txAdvice" transaction-manager="txManager"><!-- 切入点: 这里要加入的就是切入点表达式 --><tx:attributes><!-- 查询的方法上配置只读事务.. --><!--其它的方法上加入事务.. --><tx:method name="get*"  rollback-for="true"/><tx:method name="find*" rollback-for="true"/><tx:method name="load*" rollback-for="true" /><tx:method name="datagrid*"  rollback-for="true" /><tx:method name="get*"  propagation="REQUIRED"/><tx:method name="del*"  propagation="REQUIRED"/><tx:method name="update*"  propagation="REQUIRED"/><tx:method name="modify*"  propagation="REQUIRED"/><tx:method name="save*"  propagation="REQUIRED"/><tx:method name="remove*"  propagation="REQUIRED"/><tx:method name="repair*"  propagation="REQUIRED"/><tx:method name="insert*"  propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 配置切面 --><aop:config><aop:pointcut id="service"expression="execution(* com.yc.ssm.biz.impl.*.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="service" /></aop:config> </beans> 



这个是数据库的脚本

create database ssm;use ssm;drop table if exists student;create table student(id char(40) primary key,sname varchar(100) not null,age int)engine=innodb default charset=utf8;insert into student values('1','掌声',22);




jdnc的连接 

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://localhost\:3306/ssm?useUnicode\=true&characterEncoding\=UTF-8jdbc.username=rootjdbc.password=ajdbc.maxActive=150jdbc.minIdle=5jdbc.maxIdle=20



beans.xml  配置信息


<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" 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/context        http://www.springframework.org/schema/context/spring-context.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"><context:annotation-config /><!-- 包名 --><context:component-scan base-package="com.yc" /><!-- 使用spring自带的属性文件读取类完成读取配置文件的操作 --><bean id="pphc"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:db.properties" /></bean><!-- 配置dbcp数据源... 数据库联接池 ( jndi-> tomcat的数据库联接池 ) / c3p0 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxActive" value="${jdbc.maxActive}" /><property name="minIdle" value="${jdbc.minIdle}" /><property name="maxIdle" value="${jdbc.maxIdle}" /></bean><!-- 针对 mybaits的整合配置 --><!-- 配置  sqlsessionorg.mybatis.spring.SqlSessionFactoryBean.class --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="mapperLocations" value="classpath*:com/yc/ssm/dao/*.xml"></property></bean><!-- 配置扫描器  用于扫描所有的  mpper文件--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 配置要扫描的映射文件对应的接口目录 --><property name="basePackage" value="com.yc.ssm.dao"></property><!-- 指定  这个  scaaner所使用的   session工厂--><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean><!--  事务管理器 ->jdbc--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/> </bean>   <!-- 配置增强 --><tx:advice id="txAdvice" transaction-manager="txManager"><!-- 切入点: 这里要加入的就是切入点表达式 --><tx:attributes><!-- 查询的方法上配置只读事务.. --><!--其它的方法上加入事务.. --><tx:method name="get*"  rollback-for="true"/><tx:method name="find*" rollback-for="true"/><tx:method name="load*" rollback-for="true" /><tx:method name="datagrid*"  rollback-for="true" /><tx:method name="get*"  propagation="REQUIRED"/><tx:method name="del*"  propagation="REQUIRED"/><tx:method name="update*"  propagation="REQUIRED"/><tx:method name="modify*"  propagation="REQUIRED"/><tx:method name="save*"  propagation="REQUIRED"/><tx:method name="remove*"  propagation="REQUIRED"/><tx:method name="repair*"  propagation="REQUIRED"/><tx:method name="insert*"  propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 配置切面 --><aop:config><aop:pointcut id="service"expression="execution(* com.yc.ssm.biz.impl.*.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="service" /></aop:config> </beans> 
</pre><pre name="code" class="html">
</pre><pre name="code" class="html">

beans-web.xml 是web层的配置

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" 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/context        http://www.springframework.org/schema/context/spring-context.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">                 <!-- 配置action  bean的id就是 action的class名字 -->                <bean id="StudentAction" class="com.yc.ssm.web.action.StudentAction"         scope="prototype">        <property name="studentBiz" ref="studentBiz"></property>                </bean>          </beans>
struts.xml是struts的控制层

<?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>    <constant name="struts.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" /><constant name="struts.objectFactory" value="spring"/>    <package name="default" namespace="/" extends="struts-default"><action name="student_*" class="StudentAction" method="{1}"><result name="add_success">/add_success.jsp</result></action>    </package></struts>

student 类
package com.yc.ssm.bean;import java.io.Serializable;public class Student implements Serializable {/** *  */private static final long serialVersionUID = -8480199388973683250L;private String id;private String sname;private Integer age;@Overridepublic String toString() {return "Student [id=" + id + ", sname=" + sname + ", age=" + age + "]";}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Student(String id, String sname, Integer age) {super();this.id = id;this.sname = sname;this.age = age;}public Student() {super();}}
StdeuntBiz接口

package com.yc.ssm.biz;import com.sun.tools.javac.util.List;import com.yc.ssm.bean.Student;public interface StudentBiz {public int delete(String id);public void update(Student student);public Student findById(String id);public int add(Student student);public List<Student> findAll();}
接口的实现类

package com.yc.ssm.biz.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.sun.tools.javac.util.List;import com.yc.ssm.bean.Student;import com.yc.ssm.biz.StudentBiz;import com.yc.ssm.dao.StudentDao;//使用注解注入@Service("studentBiz")public class StudentBizImpl implements StudentBiz{@Autowiredpublic StudentDao studentDao;@Overridepublic int delete(String id) {return studentDao.delete(id);}public void setStudentDao(StudentDao studentDao) {this.studentDao = studentDao;}@Overridepublic void update(Student student) {studentDao.update(student);}@Overridepublic Student findById(String id) {return studentDao.findById(id);}@Overridepublic int add(Student student) {return studentDao.add(student);}@Overridepublic List<Student> findAll() {return null;}}
StudentDao类

package com.yc.ssm.dao;import com.yc.ssm.bean.Student;public interface StudentDao {public int delete(String id);public void update(Student student);public Student findById(String id);public int add(Student student);}

StudentDao.XML

<?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.yc.ssm.dao.StudentDao"><resultMap type="com.yc.ssm.bean.Student" id="BaseResultMap"><id column="id" property="id" jdbcType="CHAR"/><result column="sname" property="sname" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="INTEGER"/></resultMap><delete id="delete" parameterType="java.lang.String">delete from student where id=#{id}</delete><insert id="add" parameterType="com.yc.ssm.bean.Student">insert into student(id,sname,age) values (#{id},#{sname},#{age})</insert><update id="update"  parameterType="com.yc.ssm.bean.Student">update student set sname=#{sname},age=#{age} where id=#{id}  </update><select id="findById" resultMap="BaseResultMap" parameterType="java.lang.String">select * from student where id=#{id}</select> </mapper>

StudentAction类

package com.yc.ssm.web.action;import java.util.ArrayList;import java.util.Map;import java.util.UUID;import org.apache.struts2.interceptor.SessionAware;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;import com.sun.tools.javac.util.List;import com.yc.ssm.bean.Student;import com.yc.ssm.biz.StudentBiz;public class StudentAction extends ActionSupport implements ModelDriven<Student>,SessionAware {private static final long serialVersionUID = -6376764196089300549L;private StudentBiz studentBiz;private Student student;private Map<String,Object> session;public void setStudent(Student student) {this.student = student;}public Student getModel() {student =new Student();return student;}public String doAdd(){student.setId(UUID.randomUUID().toString());System.out.println(student.toString());System.out.println(studentBiz);studentBiz.add(student);return "add_success";}public String doUpdate(){this.studentBiz.update(student);return super.SUCCESS;}public String del(){this.studentBiz.delete(student.getId());return super.SUCCESS;}public String findAll(){List<Student> list=this.studentBiz.findAll();this.session.put("list", list);return super.SUCCESS;}public void setStudentBiz(StudentBiz studentBiz){this.studentBiz=studentBiz;}public void setSession(Map<String,Object> arg0){this.session=arg0;}}

测试类  我只测试了  添加 和  使用id 查询的的方法  

package com.yc.ssmTest;import static org.junit.Assert.*;import java.util.UUID;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.yc.ssm.bean.Student;import com.yc.ssm.biz.StudentBiz;public class test {private StudentBiz studentBiz;@Beforepublic void before(){ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");studentBiz=(StudentBiz) ac.getBean("studentBiz");}@Testpublic void TestAdd(){Student s=new Student();s.setId(UUID.randomUUID().toString());s.setAge(22);s.setSname("得分");studentBiz.add(s);}@Testpublic void TestfindById(){studentBiz.findById("1");}}

add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%><!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>添加</title>  </head>    <body>  <center>  <h1>添加学生</h1>  <hr />  <form name="myform" action="student_doAdd.action" method="post">  学生名:<input type="text" name="sname" /><br />  年龄:<input type="text" name="age" /><br />    <input type="submit" value="添加" />    </form>    </center>     </body></html>
add_success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%><!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>添加成功</title>  </head>      <body>    添加成功<br>  </body></html>

这个就是简单的利用三大框架写的小程序,我们要记住配置是由于编码的.在使用框架的时候,大家可以一起讨论讨论







0 0
原创粉丝点击