一个完整的ssh简单项目(学生老师信息的增删改查)

不羁岁月 提交于 2019-12-04 20:04:55

bean.package

Student.java

package bean;

public class Student {
    private int sid;
    private String sname;
    private int sage;
    Teacher teacher;
 
    public int getSid() {
        return sid;
    }

    public int getSage() {
        return sage;
    }

    public void setSage(int sage) {
        this.sage = sage;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    

    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + ", sage=" + sage
                + ", teacher=" + teacher + "]";
    }


    public Student(int sid, String sname, int sage, Teacher teacher) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.sage = sage;
        this.teacher = teacher;
    }

    public Student() {
    
    }

}

Teacher.java

package bean;

import java.util.HashSet;
import java.util.Set;

public class Teacher {
    private int tid;
    private String tname;
    private int tage;


    public int getTage() {
        return tage;
    }

    public void setTage(int tage) {
        this.tage = tage;
    }

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }



    @Override
    public String toString() {
        return "Teacher [tid=" + tid + ", tname=" + tname + ", tage=" + tage
                + "]"+"\n";
    }


    public Teacher(int tid, String tname, int tage) {
        super();
        this.tid = tid;
        this.tname = tname;
        this.tage = tage;
    }

    public Teacher() {

    }

}

teastu.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">
<!-- 配置表与实体对象的关系 -->
<!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
<hibernate-mapping package="bean">
    <!-- class元素: 配置实体与表的对应关系的 name: 完整类名 table:数据库表名 -->

    <class name="Student" table="test_student">

        <id name="sid">
            <generator class="native"></generator>
        </id>
        <property name="sname">
        </property>
    <property name="sage">
        </property>
        <!--3.1name:一的一方对象的名字 class: 一的一方类的全限定名 column:外键的名字 -->
        <many-to-one name="teacher" class="bean.Teacher" column="tid"
            lazy="false" />
    </class>

    <class name="Teacher" table="test_teacher">

        <id name="tid">
            <generator class="native"></generator>
        </id>
        <property name="tname">
        </property>
            <property name="tage">
        </property>
        <!--3.1 set标签的name属性:多的一方的集合的名字 -->
    <!--     <set name="stus">
            3.2 key的 column表示多的一方外键名
            <key column="tid" />
            3.3 one-to-many的class属性表示多的一方类的全限定名
            <one-to-many class="bean.Student"  />
        </set> -->
    </class>
</hibernate-mapping>

 

dao.package

StuDao.java

package dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import bean.Student;
import bean.Teacher;

@Repository("stuDao")
public class StuDao extends HibernateDaoSupport {
    @Autowired
    SessionFactory sessionFactory;

    @Resource(name = "sessionFactory")
    private void setMySessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public StuDao() {
        System.out.println("StuDao构造");
    }

    // =======增
    public void save(Student stu) {
        System.out.println("Studao的save方法接收到的stu=" + stu);
        getHibernateTemplate().setCheckWriteOperations(false);
        getHibernateTemplate().save(stu);
        System.out.println("增加成功!");
    }

    // =======删
        public void delete(int sid) {
            
            System.out.println("Studao的delete方法接收到的sid=" + sid);        
            Session session=sessionFactory.openSession();
            Transaction transaction=session.beginTransaction();
            String hql="delete from Student where sid=:sid";
            session.createQuery(hql).setParameter("sid", sid).executeUpdate();
            transaction.commit();
            System.out.println("删除成功!");
            
        }
    
        // =======改
        public void update(int sid,String sname,int sage,int tid) {
            System.out.println("Studao的update方法接收的sid=" + sid);
            getHibernateTemplate().setCheckWriteOperations(false);
            Session session=sessionFactory.openSession();
            Transaction transaction=session.beginTransaction();
            String hql="UPDATE Student SET sname = :sname,sage=:sage,tid=:tid WHERE sid = :sid ";
            session.createQuery(hql).setParameter("sid", sid).setParameter("sname",sname).setParameter("sage",sage).setParameter("tid",tid).executeUpdate();
            transaction.commit();
            System.out.println("修改成功!");
        }
        public void updateSage(int sid,int sage) {
            System.out.println("Studao的update方法接收到的sid=" + sid);
            getHibernateTemplate().setCheckWriteOperations(false);
            Session session=sessionFactory.openSession();
            Transaction transaction=session.beginTransaction();
            String hql="UPDATE Student SET sage = :sage WHERE sid = :sid ";
            session.createQuery(hql).setParameter("sid", sid).setParameter("sage",sage).executeUpdate();
            transaction.commit();
            System.out.println("修改成功!");
        }

    // ========查
    public List<Student> searchBySid(int sid) {
        System.out.println("Studao的searchBySid方法接收到的sid=" + sid);
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Student where sid=?";
        List<Student> list = (List<Student>) this.getHibernateTemplate().find(
                hql, sid);
        return list;
    }
    public List<Student> searchBySname(String sname) {
        System.out.println("Studao的searchBySname方法接收到的sname=" + sname);
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Student where sname like '%"+sname+"%'";
        List<Student> list = (List<Student>) this.getHibernateTemplate().find(
                hql);
        return list;
    }
    public List<Student> searchBySage(int bottom, int top) {
        System.out.println("Studao的searchBySage方法接收到的bottom=" + bottom
                + ",top=" + top);
        String hql = "from Student where sage> :bottom and sage< :top";
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        List<Student> list=(List<Student>) session.createQuery(hql).setParameter("bottom", bottom)
                .setParameter("top", top).list();
        transaction.commit();
        return list;
    }
    public List<Student> showAllStu() {
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Student";
        List<Student> list = (List<Student>) this.getHibernateTemplate().find(
                hql);
        return list;
    }

}

TeaDao.java

package dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import bean.Student;
import bean.Teacher;

@Repository("teaDao")
public class TeaDao extends HibernateDaoSupport {
    @Autowired
    SessionFactory sessionFactory;

    @Resource(name = "sessionFactory")
    private void setMySessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public TeaDao() {
        System.out.println("TeaDao构造");
    }

    // =======增
    public void save(Teacher tea) {
        System.out.println("Teadao的save方法接收到的tea=" + tea);
        getHibernateTemplate().setCheckWriteOperations(false);
        getHibernateTemplate().save(tea);
        System.out.println("增加成功!");
    }

    // =======删
    public void delete(int tid) {

        System.out.println("Teadao的delete方法接收到的tid=" + tid);

        // getHibernateTemplate().delete(tid);

        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        String hql = "delete from Teacher where tid=:tid";
        session.createQuery(hql).setParameter("tid", tid).executeUpdate();
        transaction.commit();
        System.out.println("删除成功!");

    }

    // =======改
    public void update(int tid, String tname,int tage) {
        System.out.println("Teadao的update方法接收的tid=" + tid);
        getHibernateTemplate().setCheckWriteOperations(false);
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        String hql = "UPDATE Teacher SET tname = :tname ,tage = :tage  WHERE tid = :tid ";
        session.createQuery(hql).setParameter("tid", tid)
                .setParameter("tname", tname).setParameter("tage", tage).executeUpdate();
        transaction.commit();
        System.out.println("修改成功!");
    }

    public void updateTage(int tid, int tage) {
        System.out.println("Teadao的update方法接收到的tid=" + tid);
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        String hql = "UPDATE Teacher SET tage = :tage WHERE tid = :tid ";
        session.createQuery(hql).setParameter("tid", tid)
                .setParameter("tage", tage).executeUpdate();
        transaction.commit();
        System.out.println("修改成功!");
    }

    // ========查()
    public List<Teacher> searchByTid(int tid) {
        System.out.println("Teadao的searchByTid方法接收到的tid=" + tid);
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Teacher where tid=?";
        List<Teacher> list = (List<Teacher>) this.getHibernateTemplate().find(
                hql, tid);
        return list;
    }

    public List<Teacher> searchByTname(String tname) {
        System.out.println("Teadao的searchByTname方法接收到的tname=" + tname);
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Teacher where tname like '%"+tname+"%'";
        List<Teacher> list = (List<Teacher>) this.getHibernateTemplate().find(
                hql);
        return list;
    }

    public List<Teacher> searchByTage(int bottom, int top) {
        System.out.println("Teadao的searchByTage方法接收到的bottom=" + bottom
                + ",top=" + top);
        String hql = "from Teacher where tage> :bottom and tage< :top";
    
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        List<Teacher> list=(List<Teacher>) session.createQuery(hql).setParameter("bottom", bottom)
                .setParameter("top", top).list();
        transaction.commit();
        return list;
    }
    
    public List<Teacher> showAllTea() {
        HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
        getHibernateTemplate().setCheckWriteOperations(false);
        String hql = "from Teacher";
        List<Teacher> list = (List<Teacher>) this.getHibernateTemplate().find(
                hql);
        return list;
    }
}

 

controller.package

TestController.java

package controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import bean.Student;
import bean.Teacher;
import dao.StuDao;
import dao.TeaDao;

@Controller
@RequestMapping("con")
public class TestController {
    @Autowired
    TeaDao teadao;
    @Autowired
    StuDao studao;

    public TestController() {
        System.out.println("TestController构造");
    }

    @RequestMapping("test1")
    public String test1() {
        System.out.println("页面跳转测试");
        return "/jsp/test.jsp";
    }

    @RequestMapping("test2")
    public String test2() {
        System.out.println("action跳转测试");
        return "test1.action";
    }

    @RequestMapping("showAllStu")
    @ResponseBody
    public ModelAndView showAllStu(HttpSession session) {
        System.out.println("进入showAllStu");
        List<Student> li = studao.showAllStu();
        System.out.println("所有学生:\n" + li);
        ModelAndView mv = new ModelAndView("/jsp/NewFile.jsp");
        mv.addObject("stus", li);
        return mv;
    }

    @RequestMapping("showAllTea")
    @ResponseBody
    public ModelAndView showAllTea(HttpSession session) {
        System.out.println("进入showAllTea");
        List<Teacher> te = teadao.showAllTea();
        System.out.println("所有教师:\n" + te);
        ModelAndView mv = new ModelAndView("/jsp/NewFile.jsp");
        mv.addObject("teas", te);
        return mv;
    }

    @RequestMapping("showAllStuRe")
    @ResponseBody
    public String showAllStuRe(HttpSession session) {
        System.out.println("进入showAllStu");
        List<Student> li = studao.showAllStu();
        System.out.println("所有学生Re:\n" + li);
        String Stustr = JSONObject.toJSONString(li,SerializerFeature.DisableCircularReferenceDetect);
        return Stustr;
    }

    @RequestMapping("showAllTeaRe")
    @ResponseBody
    public String showAllTeaRe(HttpSession session) {
        System.out.println("进入showAllTea");
        List<Teacher> te = teadao.showAllTea();
        System.out.println("所有教师Re:\n" + te);
        String Teastr = JSONObject.toJSONString(te);
        return Teastr;
    }

    @RequestMapping("searchByTName")
    @ResponseBody
    public String searchByTName(HttpSession session, String tname) {
        System.out.println("进入searchByTName");
        List<Teacher> te = teadao.searchByTname(tname);
        System.out.println("符合条件的教师:\n" + te);
        String Teastr = JSONObject.toJSONString(te);
        return Teastr;
    }

    @RequestMapping("searchBySName")
    @ResponseBody
    public String searchBySName(HttpSession session, String sname) {
        System.out.println("进入searchBySName");
        List<Student> li = studao.searchBySname(sname);
        System.out.println("符合条件的学生:\n" + li);
        String str = JSONObject.toJSONString(li);
        return str;
    }

    @RequestMapping("searchByTAge")
    @ResponseBody
    public String searchByTAge(HttpSession session, int bot, int top) {
        System.out.println("进入searchByTAge");
        List<Teacher> li = teadao.searchByTage(bot, top);
        System.out.println("符合条件的教师:\n" + li);
        String str = JSONObject.toJSONString(li);
        return str;
    }

    @RequestMapping("searchBySAge")
    @ResponseBody
    public String searchBySAge(HttpSession session, int bot, int top) {
        System.out.println("进入searchBySAge");
        List<Student> li = studao.searchBySage(bot, top);
        System.out.println("符合条件的学生:\n" + li);
        String str = JSONObject.toJSONString(li);
        return str;
    }

    @RequestMapping("searchByTid")
    @ResponseBody
    public String searchByTId(HttpSession session, int id) {
        System.out.println("进入searchByTid");
        List<Teacher> li = teadao.searchByTid(id);
        System.out.println("符合条件的教师:\n" + li);
        String str = JSONObject.toJSONString(li);
        return str;
    }

    @RequestMapping("searchBySid")
    @ResponseBody
    public String searchBySId(HttpSession session, int id) {
        System.out.println("进入searchBySid");
        List<Student> li = studao.searchBySid(id);
        System.out.println("符合条件的学生:\n" + li);
        String str = JSONObject.toJSONString(li);
        return str;
    }

    @RequestMapping("add")
    public String addTeacher(HttpSession session, String name, int age, int tid) {
        ModelAndView mv=new ModelAndView("/jsp/NewFile.jsp");
        System.out.println("进入add");
        if (tid == 0) {
            Teacher t=new Teacher(0,name,age);
             teadao.save(t);
            System.out.println("添加教师成功!");
        
        } else {
            Teacher t=new Teacher();
            t.setTid(tid);
            Student s=new Student(0,name,age,t);
             studao.save(s);
            System.out.println("添加学生成功!");
        }
          return "showAllStu.action";
    }
    
    @RequestMapping("deletestu")
    public String deletestu(HttpSession session, int sid) {
        System.out.println("进入deletestu");
        studao.delete(sid);
        System.out.println("删除成功!" );
        return "showAllStu.action";
    }
    
    @RequestMapping("deletetea")
    public String deletetea(HttpSession session, int tid) {
        System.out.println("进入deletetea");
        teadao.delete(tid);
        System.out.println("删除成功!" );
        return "showAllTea.action";
    }
    
    @RequestMapping("editTea")
    public String editTea(HttpSession session, int tid,String tname,int tage) {
        System.out.println("进入editTea");
        teadao.update(tid,tname,tage);
        System.out.println("修改成功!" );
        return "showAllTea.action";
    }
    
    @RequestMapping("editStu")
    public String editStu(HttpSession session, int sid,String sname,int sage,int tid) {
        System.out.println("进入editTea");
        studao.update(sid,sname,sage,tid);
        System.out.println("修改成功!" );
        return "showAllStu.action";
    }

    @RequestMapping("TransTea")
    public String aaa(HttpSession s,Model m,int tid,String tname,int tage) {
        System.out.println("进入TransTea");

        m.addAttribute("tid",tid); 
        m.addAttribute("tname",tname); 
        m.addAttribute("tage",tage); 

        return "/jsp/editTea.jsp";
    }
    
    @RequestMapping("TransStu")
    public String bbb(HttpSession s,Model m,int sid,String sname,int sage,int tid) {
        System.out.println("进入TransStu");
        m.addAttribute("sid",sid); 
        m.addAttribute("sname",sname); 
        m.addAttribute("sage",sage); 
        m.addAttribute("tid",tid); 
        return "/jsp/editStu.jsp";
    }
}

 

resources

applicationContext.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>

<context:component-scan base-package="dao"></context:component-scan>
<!-- <context:component-scan base-package="art_test"></context:component-scan> -->

<!--事务模块(不使用注解的事务) begin-->
    <!-- 核心事务管理器 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
        <property name="sessionFactory" ref="sessionFactory" ></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 配置通知 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager" >
        <tx:attributes>
            <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
            <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        </tx:attributes>
    </tx:advice> 
    <!-- 配置将通知织入目标对象
    配置切点
    配置切面 -->

    
    <!--事务模块(不使用注解的事务) end -->
    <!-- ========================================================================================= -->
    <!-- 开启注解事务
    <tx:annotation-driven transaction-manager="transactionManager" />
     -->
    <!-- 将SessionFactory配置到spring容器中 -->
    <!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
    <!-- <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
        <property name="configLocation" value="classpath:hibernate.cfg.xml" ></property>
    </bean> -->

<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

        <property name="hibernateProperties">
            <props>
                <!--  必选配置 -->
                <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.url" >jdbc:mysql:///test</prop>
                <prop key="hibernate.connection.username" >root</prop>
                <prop key="hibernate.connection.password" >root</prop> 
                
                <!--  可选配置 -->
                <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql" >true</prop>
                <prop key="hibernate.format_sql" >true</prop>
                <prop key="hibernate.hbm2ddl.auto" >update</prop>
            </props>
        </property>
        <!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
        <property name="mappingDirectoryLocations" value="classpath:bean" ></property> 
        
    </bean>
    
    
</beans>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    
        <!-- 
        #hibernate.dialect org.hibernate.dialect.MySQLDialect
        #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
        #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
        #hibernate.connection.driver_class com.mysql.jdbc.Driver
        #hibernate.connection.url jdbc:mysql:///test
        #hibernate.connection.username 
        #hibernate.connection.password
         -->
         <!-- 数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <!-- 数据库url -->
        <property name="hibernate.connection.url">jdbc:mysql:///test</property>
         <!-- 数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
         <!-- 数据库连接密码 -->
        <property name="hibernate.connection.password">root</property>
        <!-- 数据库方言
            不同的数据库中,sql语法略有区别. 指定方言可以让hibernate框架在生成sql语句时.针对数据库的方言生成.
            sql99标准: DDL 定义语言  库表的增删改查
                      DCL 控制语言  事务 权限
                      DML 操纵语言  增删改查
            注意: MYSQL在选择方言时,请选择最短的方言.
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        
        <!-- #hibernate.show_sql true 
             #hibernate.format_sql true
        -->
        <!-- 将hibernate生成的sql语句打印到控制台 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
        <property name="hibernate.format_sql">true</property>
        <!-- 
        ## auto schema export  自动导出表结构. 自动建表
        #hibernate.hbm2ddl.auto create        自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
        #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
        #hibernate.hbm2ddl.auto validate    校验.不自动生成表.每次启动会校验数据库中表是否正确.校验失败.
         -->
        <property name="hibernate.hbm2ddl.auto">update</property>
    
    <property name="hibernate.current_session_context_class">thread</property>
        
        <mapping resource="teastu.hbm.xml"></mapping>
        
    </session-factory>
</hibernate-configuration>

springmvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配置Controller扫描 -->
    
    <context:component-scan base-package="controller"/>

    <!-- 配置注解驱动 -->
    <mvc:annotation-driven />

     <!-- 配置视图解析器 -->
    <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        前缀
        <property name="prefix" value="/WEB-INF/jsp/" />
        后缀
        <property name="suffix" value=".jsp" />
    </bean>   -->
    
        <mvc:resources mapping="/js/**" location="/resources/js/" />

    <mvc:resources mapping="/css/**" location="/resources/css/" />

    <mvc:resources mapping="/img/**" location="/resources/img/" />
    
    
</beans>

 

(两个test包下的测试类)

StuTest.java

package com;

import java.util.List;

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

import bean.Student;
import bean.Teacher;
import dao.StuDao;
import dao.TeaDao;

public class StuTest {
    // =========增加学生
    public void fun01() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        StuDao dao = (StuDao) ac.getBean("stuDao");
        Teacher t = new Teacher();
        t.setTid(2);
        Student stu = new Student(1, "Patrick",10, t);
        dao.save(stu);
        System.out.println("保存成功");
    }
    
    // =========删除学生
    public void fun02() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        StuDao dao = (StuDao) ac.getBean("stuDao");
        dao.delete(8);
        System.out.println("删除成功");
    }
    
    // =========修改学生
    public void fun03() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        StuDao dao = (StuDao) ac.getBean("stuDao");
     //  dao.updateSname(7, "Patrick");
       dao.updateSage(7, 10);
        System.out.println("修改成功");
    }
    
    // ===========查询学生
    public void fun04() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        StuDao dao = (StuDao) ac.getBean("stuDao");
        List<Student> stus = dao.searchBySname("P");
        //List<Student> stus = dao.searchBySage(18,30);
        System.out.println(stus);
        System.out.println("查询成功");
    }
    public void fun05() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        StuDao dao = (StuDao) ac.getBean("stuDao");
        List<Student> stus = dao.showAllStu();
        System.out.println(stus);

    }
    
    
    public static void main(String[] args) {
        StuTest s = new StuTest();
        s.fun05();
    }
}

TeaTest.java

package com;

import java.util.List;

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

import bean.Student;
import bean.Teacher;
import dao.StuDao;
import dao.TeaDao;

public class TeaTest {
    
    // =========增加老师
    public void fun01() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        TeaDao dao = (TeaDao) ac.getBean("teaDao");
        Teacher t = new Teacher(1,"Bilbo",24);
        dao.save(t);
        System.out.println("保存成功");
    }

    // =========删除老师
    public void fun02() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        TeaDao dao = (TeaDao) ac.getBean("teaDao");
        dao.delete(4);
        System.out.println("删除成功");
    }

    // =========修改老师
    public void fun03() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        TeaDao dao = (TeaDao) ac.getBean("teaDao");
       String name="bilbo";
       dao.updateTage(7, 111);
        System.out.println("修改成功");
    }

    // ===========查询老师
    public void fun04() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        TeaDao dao = (TeaDao) ac.getBean("teaDao");
        List<Teacher> teas = dao.searchByTname("o");
        System.out.println(teas);
        System.out.println("查询成功");
    }

    public static void main(String[] args) {
        TeaTest t = new TeaTest();
        t.fun04();
    }

}

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>191115_test</groupId>
  <artifactId>com</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
      <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- spring start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- spring end -->

        <!-- springmvc start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
        <!-- springmvc end -->

        <!-- loging start -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.6</version>
        </dependency>
        <!-- loging end -->

        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.8.7</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!-- hibernate start -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.3.Final</version>
        </dependency>
        <!-- hibernate end -->

        <!--c3p0 start -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!-- c3p0 end -->

        <!-- mysql start -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
        <!-- mysql end -->

  
  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.5.4</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.4</version>
    </dependency>
    
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.62</version>
  </dependency>
    
    </dependencies>
</project>

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" version="2.5">
  <display-name>art_test</display-name>
  <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>
    <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 配置监听器加载spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置过滤器,解决post的乱码问题 -->
    <!-- <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
     -->
    <!-- <filter>
      <filter-name>openSessionInView</filter-name>
      <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
    <filter-mapping>
      <filter-name>openSessionInView</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
 -->
    <!-- 配置SpringMVC -->
    <servlet>
        <servlet-name>boot-crm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- 配置springmvc什么时候启动,参数必须为整数 -->
        <!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
        <!-- 如果小于0,则在第一次请求进来的时候启动 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>boot-crm</servlet-name>
        <!-- 所有的请求都进入springMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
  


</web-app>

 

jsp.package

NewFile.jsp(信息显示首页) 通过http://localhost:8080/com/con/showAllStu.action进入

 

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ 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>Insert title here</title>
</head>
<body>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
        
    </script>
    <script>
        /*     $(document).ready(function() {
                $("p").click(function() {
                    $(this).hide();
                });
                
            }); */

        function showAll() {
            var value = $("#Choice").val();
            if (value == '1') {

                $
                        .ajax({
                            type : "POST",
                            url : "showAllStuRe.action",
                            contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                            /* dataType : "json", */
                            success : function(data) {
                                console.log(data);
                                var dat = JSON.parse(data);
                                $("#teastu").empty();
                                console
                                        .log(".................."
                                                + dat[0].sname);

                                var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                        + "<td style='width: 100px;'>学生id</td>"
                                        + "<td style='width: 100px;'>学生姓名</td>"
                                        + "<td style='width: 100px;'>学生年龄</td>"
                                        + "<td style='width: 100px;'>教师id</td>"
                                        + "<td style='width: 100px;'> </td>"
                                        + "</tr>";
                                $("#teastu").html(html);
                                if (dat != null) {
                                    for (var i = 0; i < dat.length; i++) {
                                        var stu = dat[i];

                                        $("#teastu")
                                                .append(
                                                        "<tr><td>"
                                                                + stu.sid
                                                                + "</td><td>"
                                                                + stu.sname
                                                                + "</td> <td>"
                                                                + stu.sage
                                                                + "</td><td>"
                                                                + stu.teacher.tid
                                                                + "</td> <td>"
                                                                + "<a href='/com/con/deletestu.action?sid="
                                                                + stu.sid
                                                                + "'>删除</a>&nbsp;"
                                                                + "<a href='/com/con/TransStu.action?sid="
                                                                + stu.sid
                                                                + "&sname="
                                                                + stu.sname
                                                                + "&sage="
                                                                + stu.sage
                                                                + "&tid="
                                                                + stu.teacher.tid
                                                                + "'>修改</a></td>");
                                    }
                                } else {
                                    $("#temp").html("暂无学生信息!");
                                }

                            }
                        });
            } else {

                $
                        .ajax({
                            type : "POST",
                            url : "showAllTeaRe.action",
                            contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                            /*     dataType : "json", */
                            success : function(data) {
                                console.log(data);
                                var dat = JSON.parse(data);
                                $("#teastu").empty();
                                var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                        + "<td style='width: 100px;'>教师id</td>"
                                        + "<td style='width: 100px;'>教师姓名</td>"
                                        + "<td style='width: 100px;'>教师年龄</td>"
                                        + "<td style='width: 100px;'> </td>"
                                        + "</tr>";
                                $("#teastu").html(html);

                                if (dat != null) {
                                    for (var i = 0; i < dat.length; i++) {
                                        var tea = dat[i];

                                        $("#teastu")
                                                .append(
                                                        "<tr><td>"
                                                                + tea.tid
                                                                + "</td><td>"
                                                                + tea.tname
                                                                + "</td> <td>"
                                                                + tea.tage
                                                                + "</td><td>"
                                                                + "<a href='/com/con/deletetea.action?tid="
                                                                + tea.tid
                                                                + "'>删除</a>&nbsp;"
                                                                + "<a href='/com/con/TransTea.action?tid="
                                                                + tea.tid
                                                                + "&tname="
                                                                + tea.tname
                                                                + "&tage="
                                                                + tea.tage
                                                                + "'>修改</a></td>");
                                    }
                                } else {
                                    $("#temp").html("暂无教师信息!");
                                }
                            }
                        });

            }
        }

        function button() {
            var value = $("#choose").val();
            var condition = $("#condition").val();
            var condition2 = $("#condition2").val();
            //alert("condition:"+condition+",condition2:"+condition2);
            if (value == '0') {
                //    alert("姓名");
                var value = $("#Choice").val();
                if (value == '0') {
                    //    alert("根据姓名查找教师");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchByTName.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    tname : condition
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'>教师姓名</td>"
                                            + "<td style='width: 100px;'>教师年龄</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的教师信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var tea = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                                    .append(
                                                            "<tr><td>"
                                                                    + tea.tid
                                                                    + "</td><td>"
                                                                    + tea.tname
                                                                    + "</td> <td>"
                                                                    + tea.tage
                                                                    + "</td><td>"
                                                                    + "<a href='/com/con/deletetea.action?tid="
                                                                    + tea.tid
                                                                    + "'>删除</a>&nbsp;"
                                                                    + "<a href='/com/con/TransTea.action?tid="
                                                                    + tea.tid
                                                                    + "&tname="
                                                                    + tea.tname
                                                                    + "&tage="
                                                                    + tea.tage
                                                                    + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                } else {
                    //    alert("根据姓名查找学生");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchBySName.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    sname : condition
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>学生id</td>"
                                            + "<td style='width: 100px;'>学生姓名</td>"
                                            + "<td style='width: 100px;'>学生年龄</td>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的学生信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var stu = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                            .append(
                                                    "<tr><td>"
                                                            + stu.sid
                                                            + "</td><td>"
                                                            + stu.sname
                                                            + "</td> <td>"
                                                            + stu.sage
                                                            + "</td><td>"
                                                            + stu.teacher.tid
                                                            + "</td> <td>"
                                                            + "<a href='/com/con/deletestu.action?sid="
                                                            + stu.sid
                                                            + "'>删除</a>&nbsp;"
                                                            + "<a href='/com/con/TransStu.action?sid="
                                                            + stu.sid
                                                            + "&sname="
                                                            + stu.sname
                                                            + "&sage="
                                                            + stu.sage
                                                            + "&tid="
                                                            + stu.teacher.tid
                                                            + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                }

            } else if (value == '1') {
                //    alert("年龄");
                var value = $("#Choice").val();
                if (value == '0') {
                    //    alert("根据年龄查找教师");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchByTAge.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    bot : condition,
                                    top : condition2
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'>教师姓名</td>"
                                            + "<td style='width: 100px;'>教师年龄</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的教师信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var tea = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                                    .append(
                                                            "<tr><td>"
                                                                    + tea.tid
                                                                    + "</td><td>"
                                                                    + tea.tname
                                                                    + "</td> <td>"
                                                                    + tea.tage
                                                                    + "</td><td>"
                                                                    + "<a href='/com/con/deletetea.action?tid="
                                                                    + tea.tid
                                                                    + "'>删除</a>&nbsp;"
                                                                    + "<a href='/com/con/TransTea.action?tid="
                                                                    + tea.tid
                                                                    + "&tname="
                                                                    + tea.tname
                                                                    + "&tage="
                                                                    + tea.tage
                                                                    + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                } else {
                    //    alert("根据年龄查找学生");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchBySAge.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    bot : condition,
                                    top : condition2
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>学生id</td>"
                                            + "<td style='width: 100px;'>学生姓名</td>"
                                            + "<td style='width: 100px;'>学生年龄</td>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的学生信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var stu = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                            .append(
                                                    "<tr><td>"
                                                            + stu.sid
                                                            + "</td><td>"
                                                            + stu.sname
                                                            + "</td> <td>"
                                                            + stu.sage
                                                            + "</td><td>"
                                                            + stu.teacher.tid
                                                            + "</td> <td>"
                                                            + "<a href='/com/con/deletestu.action?sid="
                                                            + stu.sid
                                                            + "'>删除</a>&nbsp;"
                                                            + "<a href='/com/con/TransStu.action?sid="
                                                            + stu.sid
                                                            + "&sname="
                                                            + stu.sname
                                                            + "&sage="
                                                            + stu.sage
                                                            + "&tid="
                                                            + stu.teacher.tid
                                                            + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                }
            } else if (value == '2') {
                //    alert("id");
                var value = $("#Choice").val();
                if (value == '0') {
                    //    alert("根据id查找教师");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchByTid.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    id : condition
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'>教师姓名</td>"
                                            + "<td style='width: 100px;'>教师年龄</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的教师信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var tea = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                                    .append(
                                                            "<tr><td>"
                                                                    + tea.tid
                                                                    + "</td><td>"
                                                                    + tea.tname
                                                                    + "</td> <td>"
                                                                    + tea.tage
                                                                    + "</td><td>"
                                                                    + "<a href='/com/con/deletetea.action?tid="
                                                                    + tea.tid
                                                                    + "'>删除</a>&nbsp;"
                                                                    + "<a href='/com/con/TransTea.action?tid="
                                                                    + tea.tid
                                                                    + "&tname="
                                                                    + tea.tname
                                                                    + "&tage="
                                                                    + tea.tage
                                                                    + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                } else {
                    //    alert("根据id查找学生");
                    $
                            .ajax({
                                type : "POST",
                                url : "searchBySid.action",
                                contentType : 'application/x-www-form-urlencoded;charset=utf-8',
                                data : {
                                    id : condition
                                },
                                success : function(data) {
                                    console.log(data);
                                    var dat = JSON.parse(data);
                                    $("#teastu").empty();
                                    var html = "    <tr style='background: #D5DBE6; font-weight: bold'>"
                                            + "<td style='width: 100px;'>学生id</td>"
                                            + "<td style='width: 100px;'>学生姓名</td>"
                                            + "<td style='width: 100px;'>学生年龄</td>"
                                            + "<td style='width: 100px;'>教师id</td>"
                                            + "<td style='width: 100px;'> </td>"
                                            + "</tr>";
                                    $("#teastu").html(html);

                                    if (dat.length == 0 || data == '') {//alert("data为空");
                                        $("#temp").html("暂无符合条件的学生信息!");
                                    } else {
                                        $("#temp").empty();
                                        for (var i = 0; i < dat.length; i++) {
                                            var stu = dat[i];
                                            //    alert("data有值");
                                            $("#teastu")
                                            .append(
                                                    "<tr><td>"
                                                            + stu.sid
                                                            + "</td><td>"
                                                            + stu.sname
                                                            + "</td> <td>"
                                                            + stu.sage
                                                            + "</td><td>"
                                                            + stu.teacher.tid
                                                            + "</td> <td>"
                                                            + "<a href='/com/con/deletestu.action?sid="
                                                            + stu.sid
                                                            + "'>删除</a>&nbsp;"
                                                            + "<a href='/com/con/TransStu.action?sid="
                                                            + stu.sid
                                                            + "&sname="
                                                            + stu.sname
                                                            + "&sage="
                                                            + stu.sage
                                                            + "&tid="
                                                            + stu.teacher.tid
                                                            + "'>修改</a></td>");
                                        }
                                    }
                                }
                            });
                }
            }
        }

        function search() {
            var value = $("#choose").val();
            if (value == '0') {
                //    alert("0");
                $("#condition2").hide();
                $("#bot").hide();//显示
                $("#top").hide();//显示
            } else if (value == '1') {
                //    alert("1");
                $("#condition2").show();//显示
                $("#bot").show();//显示
                $("#top").show();//显示
            } else if (value == '2') {
                //    alert("2");
                $("#condition2").hide();
                $("#bot").hide();//显示
                $("#top").hide();//显示
            }
        }
    </script>
    <!-- ==================================================== -->
    <!--     <p>列表</p> -->

    <select id="Choice" name="Choice" onchange="showAll()">
        <option value="100">情选择</option>
        <option value="1">学生信息</option>
        <option value="0">教师信息</option>
    </select> &nbsp;&nbsp; 根据
    <select id="choose" name="choose" onchange="search()">
        <option value="0">姓名</option>
        <option value="1">年龄</option>
        <option value="2">id</option>
    </select>
    <span id="bot" style="display: none;">最小年龄</span>
    <input type="text" id="condition" style="width: 50px" />
    <span id="top" style="display: none;">最大年龄</span>
    <input type="text" id="condition2" style="display: none; width: 50px" />
    <button id="go" onclick="button()">查询</button>
    <a href="/com/jsp/add.jsp">添加</a>

    <table id="teastu" name="teastu">


        <c:if test="${stus != null}">
            <tr style="background: #D5DBE6; font-weight: bold">
                <td style="width: 100px;">学生id</td>
                <td style="width: 100px;">学生姓名</td>
                <td style="width: 100px;">学生年龄</td>
                <td style="width: 100px;">教师id</td>
                <td style="width: 100px;"></td>
            </tr>

            <c:forEach items="${stus}" var="temp">
                <tr>
                    <td>${temp.sid}</td>
                    <td>${temp.sname}</td>
                    <td>${temp.sage}</td>
                    <td>${temp.teacher.tid}</td>
                    <td><a href="/com/con/deletestu.action?sid=${temp.sid}">删除</a>&nbsp;
                    <a href="/com/con/TransStu.action?sid=${temp.sid}&sage=${temp.sage}&sname=${temp.sname}&tid=${temp.teacher.tid}">修改</a></td>
                </tr>
            </c:forEach>
        </c:if>
        <c:if test="${teas != null}">
            <tr style="background: #D5DBE6; font-weight: bold">
                <td style="width: 100px;">教师id</td>
                <td style="width: 100px;">教师姓名</td>
                <td style="width: 100px;">教师年龄</td>
                <td style="width: 100px;"></td>
            </tr>
            <c:forEach items="${teas}" var="temp">
                <tr>
                    <td>${temp.tid}</td>
                    <td>${temp.tname}</td>
                    <td>${temp.tage}</td>
                    <td><a href="/com/con/deletetea.action?tid=${temp.tid}">删除</a>&nbsp;
                    <a href="/com/con/TransTea.action?tid=${temp.tid}&tage=${temp.tage}&tname=${temp.tname}">修改</a></td>
                </tr>
            </c:forEach>
        </c:if>
    </table>
    <p id="temp" name="temp"></p>
</body>
</html>

add.jsp

 

 

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ 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>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">        
    </script>
    <script type="text/javascript">
    function show() {
        var value = $("#add").val();
        if (value == '1') {
            $("#belong").show();
            $("#tid").show();
        }
        else{
            $("#belong").hide();
            $("#tid").hide();
        }
        }
    </script>
<form action="/com/con/add.action" method="post">
<select id=add name="add" onchange="show()">
        <option value="0">教师</option>
        <option value="1">学生</option>
</select>
</br>
姓名:<input type="text" name="name"/>
</br>
年龄:<input type="text" name="age"/>
</br>
<span id="belong" style="display:none;">所属教师编号:</span><input type="text" name="tid" id="tid" value="0" style="display:none;"/>
</br>
<input type="submit"/>
</form>
</body>
</html>

editStu.jsp

 

 

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ 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>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">        
    </script>
    <script type="text/javascript">
    </script>
<form action="/com/con/editStu.action" method="post">
</br>
id:
<input type="text" name="sid" value="${sid}"/>
姓名:<input type="text" name="sname" value="${sname}"/>
</br>
年龄:<input type="text" name="sage" value="${sage}"/>
</br>
所属教师编号:<input type="text" name="tid" id="tid" value="${tid}"/>
</br>
<input type="submit"/>
</form>
</body>
</html>

editTea.jsp

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ 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>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">        
    </script>
    <script type="text/javascript">
    </script>
<form action="/com/con/editTea.action" method="post">
</br>
id:
<input type="text" name="tid" value="${tid}"/>
姓名:<input type="text" name="tname" value="${tname}"/>
</br>
年龄:<input type="text" name="tage" value="${tage}"/>
</br>
<input type="submit"/>
</form>
</body>
</html>

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!