structs实验

实验一 熟悉Struts2框架

实验任务:

1)实现基于Struts2的登录系统(需要访问数据库)

参考代码:

登录页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

    <form method="post" action="login">

            用户名:<input name="userName" type="text" size="24">

            <br>

            密 码:<input name="passWord" type="password" size="26">

            <br>

            <input type="submit" value="登录">

       </form>

</body>

</html>

登录成功页面success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<hr>

 <h1>你登录成功,欢迎你!</h1>

</hr>

</body>

</html>

LoginAction类代码如下:

package loginAction;

import loginBean.LoginBean;

public class LoginAction {

    private String userName;

    private String passWord;

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getPassWord() {

        return passWord;

    }

    public void setPassWord(String passWord) {

        this.passWord = passWord;

    }

    public String execute() throws Exception{

        LoginBean lb=new LoginBean();

        if(lb.login(userName, passWord))

                {

            return "success";

                }

                else{

            return "error";

                }

    }

}

实现数据库登录功能的LoginBean类代码如下:

package loginBean;

import java.sql.*;

public class LoginBean {

    private String userName;

    private String passWord;

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getPassWord() {

        return passWord;

    }

    public void setPassWord(String passWord) {

        this.passWord = passWord;

    }

    //处理用户登录的方法

    public boolean login(String userName,String passWord){

        boolean b=false;

        Connection con=null;

Statement st=null;

ResultSet rs=null;

try{

       Class.forName("com.mysql.cj.jdbc.Driver");           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shiyan1?useSSL=false&serverTimezone=UTC","root","123456");

       st=con.createStatement();

       String sql="select * from user where username='"+userName+"'";

       rs=st.executeQuery(sql);

       if(rs.next()){

               String pass=rs.getString("password");

               if(pass.equals(passWord)){

                       b=true;

           }

        }     

        return b;

}catch(Exception e){  return b;     }  

}

}

配置文件struts.xml代码如下:

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

    <package name="login" extends="struts-default">

        <action name="login" class="loginAction.LoginAction">

            <result name="error">login.jsp</result>

            <result name="success">success.jsp</result>

        </action>

     </package>

</struts>

实验二 Struts2核心组件的应用

实验任务:

(1)修改实验一登录系统代码,页面使用Struts2标签,登录成功页面使用OGNL表达式显示登录用户名称,并显示是系统第几位登录成功的用户。

参考代码:

登录页面login1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>   

<%@taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<s:form action="login1" method="post">

            <s:textfield name="userName" label="用户名称" size="16"/>

            <br>

            <s:password name="passWord" label="用户密码" size="18"/>

            <br>

            <s:submit value="登录"/>

</s:form>

</body>

</html>

登录成功页面success1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>   

<%@taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title><s:text name="登录成功页面"/></title>

</head>

<body>

<s:property value="#userName"/>,您好!欢迎访问本站,您是第<s:property value="#application.counter"/>位成功登录的客人!

</body>

</html>

LoginAction1类代码如下:

package loginAction1;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction1 extends ActionSupport{

    private String userName;

    private String passWord;

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getPassWord() {

        return passWord;

    }

    public void setPassWord(String passWord) {

        this.passWord = passWord;

    }

    public String execute() throws Exception{

        LoginBean lb=new LoginBean();

        if(lb.login(userName, passWord))

                {

                ServletContext application= ServletActionContext.getServletContext();

                 Integer count= (Integer)application.getAttribute("counter");

                if(count==null)

                   count=new Integer(0);

                count=new Integer(count.intValue()+1);

                application.setAttribute("counter",count); 

                return SUCCESS;

            }

            else{

                         return ERROR;

            }

    }

}

实现数据库登录功能的LoginBean类代码如下:

package loginBean;

import java.sql.*;

public class LoginBean {

    private String userName;

    private String passWord;

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getPassWord() {

        return passWord;

    }

    public void setPassWord(String passWord) {

        this.passWord = passWord;

    }

    //处理用户登录的方法

    public boolean login(String userName,String passWord){

        boolean b=false;

        Connection con=null;

Statement st=null;

ResultSet rs=null;

try{

       Class.forName("com.mysql.cj.jdbc.Driver");           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shiyan1?useSSL=false&serverTimezone=UTC","root","123456");

       st=con.createStatement();

       String sql="select * from user where username='"+userName+"'";

       rs=st.executeQuery(sql);

       if(rs.next()){

               String pass=rs.getString("password");

               if(pass.equals(passWord)){

                       b=true;

           }

        }     

        return b;

}catch(Exception e){  return b;     }  

 }

}

配置文件struts.xml代码如下:

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

    <package name="login" extends="struts-default">

        <action name="login1" class="loginAction1.LoginAction1">

            <result name="error">login1.jsp</result>

            <result name="success">success1.jsp</result>

        </action>

     </package>

</struts>

实验三 Struts2高级组件的应用

实验任务:

(1)使用自定义拦截器实现网站页面登录权限控制,登录页面实现国际化

自定义拦截器LoginInterceptor.java的代码:

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class LoginInterceptor extends AbstractInterceptor {

        public String intercept(ActionInvocation ai) throws Exception {

        //获取session,判断session中是否有用户

        HttpSession session=ServletActionContext.getRequest().getSession();

        //没用户返回到input页面

        Object obj=session.getAttribute("user");

        if(obj==null){

            return "input";

        }        

        String result=ai.invoke();

        return result;

    }

}

DemoAction类的代码:

package action;

import com.opensymphony.xwork2.ActionSupport;

import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;

public class DemoAction extends ActionSupport {

    //登陆方法,向session中设置

    public String login(){

        HttpSession session=ServletActionContext.getRequest().getSession();

        session.setAttribute("user", "user");

        return SUCCESS;

    }   

    public String execute() throws Exception {

        return SUCCESS;

}

 }

struts.xml代码如下:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

        "http://struts.apache.org/dtds/struts-2.5.dtd">

<!--根元素 -->

<struts>

<constant name="struts.custom.i18n.resources" value="globalMessages" />

        <constant name="struts.i18n.encoding" value="utf-8" />

   <package name="login" extends="struts-default">

                    <!--定义拦截器-->

                    <interceptors>

                        <interceptor name="logininterceptor" class="interceptor.LoginInterceptor"></interceptor>

                    </interceptors>

                    <action name="login" class="action.DemoAction" method="login">

                        <!--登陆成功,直接跳转到main页面-->

                        <result type="redirectAction">main</result>

                    </action>

                    <!--执行main动作时,需要拦截器拦截-->

                    <action name="main" class="action.DemoAction">

                        <result>/main.jsp</result>

                        <result name="input">/login.jsp</result>

                        <!--使用默认拦截器和我们的拦截器-->

                        <interceptor-ref name="defaultStack"></interceptor-ref>

                        <interceptor-ref name="logininterceptor"></interceptor-ref>

                    </action>

    </package>   

</struts>

登录页面login.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

    <head>

        <!-- 使用text标签输出国际化消息 -->

        <title><s:text name="loginTitle"/></title>

    </head>

    <body>

        <s:form action="login" method="post">

            <!--表单元素的key值与资源文件的key对应-->

            <s:textfield name="userName" size="20" key="loginName"/>

            <s:password name="userPassWord" size="20" key="loginPassword"/>

            <s:submit key="loginSubmit"/>           

            </s:form>

    </body>

</html>

主页面main.jsp:

<%@ page contentType="text/html; charset=UTF-8" %>

<html>

    <head>

       <title>系统主页面</title>

    </head>

<body>

<h1>

         欢迎来到本网站主页面!

</h1>

    </body>

</html>

globalMessages_zh_CN.properties代码如下:

loginTitle=\u7528\u6237\u767b\u5f55

loginName=\u7528\u6237\u540d\u79f0

loginPassword=\u7528\u6237\u5bc6\u7801

loginSubmit=\u767b\u5f55

globalMessages_en_US.properties代码如下:

loginTitle=UserLogin

loginName=LoginName

loginPassword=LoginPassword

loginSubmit=Login

实验四 基于Struts2+Hibernate5的系统实现

实验任务:

基于Struts2+Hibernate5框架实现一个教师信息管理系统。

参考代码:

配置文件hibernate.cfg.xml代码如下:

<!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!--Hibernate配置文件的根元素,其它元素应在其中-->

<hibernate-configuration>

        <!-- 设置初始化Hibernate参数的元素,其中指定Hibernate初始化参数,表明以下的配置是针对session-factory配置,SessionFactoryHibernate中的一个接口,这个接口主要负责保存Hibernate的配置信息,以及对Session的操作 -->

    <session-factory>

        <!-- 设置连接数据库所用的驱动 ,本例中的com.mysql.jdbc.Driver MySQL的驱动名字-->

        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!--设置数据库连接使用的url“jdbc:mysql://localhost(IP):port/test”,其中,localhost(IP)表示MySQL服务器名称,即连接地址,此处为本机。port代表MySQL服务器的端口号,默认是3306test是数据库名,即要连接的数据库名-->

        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/teacher?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>

        <!-- 设置数据库的用户名(登录名) -->

        <property name="hibernate.connection.username">root</property>

        <!-- 设置数据库的连接密码 -->

        <property name="hibernate.connection.password">123456</property>

        <!-- 设置数据库的方言,每种数据库都有对应的方言 -->

        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

               

        <!-- 加入映射文件,可以加入多个映射文件 -->

        <mapping resource="PO/Teachinfo.hbm.xml"/>   

    </session-factory>

</hibernate-configuration>

类HibernateSessionFactory的代码如下:

package addHibernateFile;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

    private static SessionFactory sessionFactory;

    public static Session getSession() {

        return getSessionFactory().openSession();

    }

    public static SessionFactory getSessionFactory(){

        if (sessionFactory == null || sessionFactory.isClosed()) {

            sessionFactory = new Configuration().configure().buildSessionFactory();

        }

        return sessionFactory;

    }

}

持久化类Teachinfo的代码如下:

package PO;

public class Teachinfo {

        private String id;

        private String name;

        private String sex;

        private int age;

        private String department;

        public String getId() {

                return this.id;

        }

        public void setId(String id) {

                this.id = id;

        }

        public String getName() {

                 return name;

        }

        public void setName(String name) {

                 this.name = name;

        }

        public String getSex() {

                 return sex;

        }

        public void setSex(String sex) {

                 this.sex = sex;

        }

        public int getAge() {

                 return age;

        }

        public void setAge(int age) {

                 this.age = age;

        }

        public String getDepartment() {

                 return department;

        }

        public void setDepartment(String department) {

                 this.department = department;

        }      

}

映射文件Teachinfo.hbm.xml的代码如下:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="PO.Teachinfo" table="teachinfo" catalog="teacher">

        <id name="id" type="string">

            <column name="id" length="20" />

            <generator class="assigned" />

        </id>

        <property name="name" type="string">

            <column name="name" length="20" not-null="true" />

        </property>

        <property name="sex" type="string">

            <column name="sex" length="5" />

        </property>

        <property name="age" type="int">

            <column name="age"  />

        </property>

        <property name="department" type="string">

            <column name="department" />

        </property>

    </class>

</hibernate-mapping>

TeacherDao类的代码如下:

package Dao;

import addHibernateFile.HibernateSessionFactory;

import PO.Teachinfo;

import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

public class TeacherDao {

    private Transaction transaction;

    private Session session;

    private Query query;

    public TeacherDao(){

    }

    public boolean  saveInfo(Teachinfo info){

        try{

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            session.save(info);

            transaction.commit();

            session.close();

            return true;

        }catch(Exception e){

            message("saveInfo.error:"+e);

            e.printStackTrace();

            return false;

        }

    }

    public List findInfo(String type,Object value){

        session=HibernateSessionFactory.getSession();

        try{

            transaction=session.beginTransaction();

            String queryString="from Teachinfo as model where model."+type+"=?";

            query=session.createQuery(queryString);

            query.setParameter(0, value);

            List list=query.list();

            transaction.commit();

            session.close();

            return list;

        }catch(Exception e){

            message("findInfo.error:"+e);

            e.printStackTrace();

            return null;

        }

    }

    public List findAllInfo(){

        session=HibernateSessionFactory.getSession();

        try{

            transaction=session.beginTransaction();

            String queryString="from Teachinfo";

            query=session.createQuery(queryString);

            List list=query.list();

            transaction.commit();

            session.close();

            return list;

        }catch(Exception e){

            message("findInfo.error:"+e);

            e.printStackTrace();

            return null;

        }

    }

    public boolean deleteInfo(String id){

        try{

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            Teachinfo info=new Teachinfo();

            info=(Teachinfo)session.get(Teachinfo.class, id);

            session.delete(info);

            transaction.commit();

            session.close();

            return true;

        }catch(Exception e){

            message("deleteInfo.error:"+e);

            e.printStackTrace();

            return false;

        }

    }

    public boolean updateInfo(Teachinfo info){

        try{

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            session.update(info);

            transaction.commit();

            session.close();

            return true;

        }catch(Exception e){

            message("updateInfo.error:"+e);

            e.printStackTrace();

            return false;

        }

    }

    public void message(String mess){

        int type=JOptionPane.YES_NO_OPTION;

        String title="提示信息";

        JOptionPane.showMessageDialog(null, mess, title, type);

    }

}

主页面index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="基于SH教师信息管理-起始页"/></title>

    </head>

    <body bgcolor="#CCCCFF">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

            <br/><br/><br/><br/><br/>

            <font color="black" size="6">基于Struts2+Hibernate5的教师信息管理系统实例,可对教师信息进行增、删、改、查!</font>

            <br/><br/><br/>

            <s:a href="lookTeacherAction"><font color="blue" size="6">点此进入</font></s:a>

        <div>

    </body>

</html>

lookTeacher.jsp页面代码如下:

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.ArrayList,PO.Teachinfo"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="教师信息管理系统-查看"/></title>

    </head>

    <body bgcolor="pink">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

        <hr color="red"/>

        <br/>

        <table align="center" width="80%">

            <tr>

                <td width="25%">

                    查看教师信息

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/addTeacher.jsp">添加教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/findTeacher.jsp">修改教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/deleteTeacher.jsp">删除教师信息</s:a>

                </td>

            </tr>

        </table>

        <br/>

        <hr color="red"/>

        <br/><br/><br/>

        <span>你要查询的数据表中共有<%=request.getSession().getAttribute("count")%>人</span>

        </div>

        <table align="center" width="80%" border="5">

            <tr>

                <th>记录条数</th>

                <th>教师编号</th>

                <th>姓名</th>

                <th>性别</th>

                <th>年龄</th>

                <th>所在学院</th>

            </tr>

            <%

                ArrayList list=(ArrayList)session.getAttribute("allInfo");

                if(list.isEmpty()){

                    %>

                    <tr>

                        <td align="center">

                            <span>暂无教师信息!</span>

                        </td>

                    </tr>

                    <%

                }else{

                    for(int i=0;i<list.size();i++){

                        Teachinfo info=(Teachinfo)list.get(i);

                        %>

                        <tr>

                            <td align="center"><%=i+1%></td>

                            <td><%=info.getId()%></td>

                            <td><%=info.getName()%></td>

                            <td><%=info.getSex()%></td>

                            <td><%=info.getAge()%></td>

                            <td><%=info.getDepartment()%></td>

                        </tr>

                        <%

                    }

                }

            %>

        </table>

    </body>

</html>

addTeacher.jsp的代码如下:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="教师信息管理系统-增加"/></title>

    </head>

    <body bgcolor="pink">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

            <hr color="red"/>

        <br/>

        <table align="center" width="80%">

            <tr>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/lookTeacher.jsp">查看教师信息</s:a>

                </td>

                <td width="25%">

                    添加教师信息

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/findTeacher.jsp">修改教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/deleteTeacher.jsp">删除教师信息</s:a>

                </td>

            </tr>

        </table>

         <br/>

        <hr color="red"/>      

        <center><font color="red" size="6">添加教师信息</font></center>

        </div>

        <s:form action="addTeacherAction" method="post">

            <table align="center" width="30%" bgcolor="gray" border="5">

                <tr>

                    <td>

                        <s:textfield name="id" label="教师编号" size="16"></s:textfield>

                    </td>

                    <td>

                        <s:textfield name="name" label="姓名" size="16"/>

                    </td>

                    <td>

                        <s:select name="sex" label="性别" list="{'男','女'}"/>

                    </td>

                    <td>

                        <s:textfield name="age" label="年龄"/>

                    </td>

                    <td>

                        <s:select name="department" label="所属学院" list="{'软件学院','计算机与通信工程学院','经济与管理学院','政法学院','外语学院','艺术与设计学院','机电学院'}"/>

                    </td>

                    <td colspan="2">

                        <s:submit value="提交"/>

                        <s:reset value="清除"/>

                    </td>

                </tr>

            </table>

        </s:form>

    </body>

</html>

findTeacher.jsp页面代码如下:

<%@page import="java.util.ArrayList"%>

<%@page import="PO.Teachinfo"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="教师信息管理系统-查找"/></title>

    </head>

    <body bgcolor="pink">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

            <hr color="red"/>

        <br/>

        <table align="center" width="80%">

            <tr>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/lookTeacher.jsp">查看教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/addTeacher.jsp">添加教师信息</s:a>

                </td>

                <td width="25%">

                    修改教师信息

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/deleteTeacher.jsp">删除教师信息</s:a>

                </td>

            </tr>

        </table>

        <br/>

        <hr color="red"/>

        <br/><br/><br/>

        <font size="5">修改教师信息</font>

        </div>

        <s:form action="findTeacherAction" method="post">

        <table align="center" width="40%" border="5">

            <tr>

                <td>

                    请选择要修改教师的学号:

                </td>

                <td>

                    <select name="id">

                         <%

                            ArrayList list=(ArrayList)session.getAttribute("allInfo");

                            if(list.isEmpty()){

                                %>

                                <option value="null">null</option>

                                <%

                            }else{

                                for(int i=0;i<list.size();i++){

                                       Teachinfo info=(Teachinfo)list.get(i);

                                    %>

                                        <option value="<%=info.getId()%>"><%=info.getId()%></option>

                                    <%

                                    }

                                }

                            %>

                    </select>

                </td>

                <td>

                    <s:submit value="确定"></s:submit>

                </td>

            </tr>

        </table>

        </s:form>

    </body>

</html>

updateTeacher.jsp页面代码如下:

<%@page import="PO.Teachinfo"%>

<%@page import="java.util.ArrayList"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="教师信息管理系统-修改"/></title>

    </head>

    <body bgcolor="pink">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

            <hr color="red"/>

        <br/>

        <table align="center" width="80%">

            <tr>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/lookTeacher.jsp">查看教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/addTeacher.jsp">添加教师信息</s:a>

                </td>

                <td width="25%">

                    修改教师信息

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/deleteTeacher.jsp">删除教师信息</s:a>

                </td>

            </tr>

        </table>

        <br/>

        <hr color="red"/>

        <br/><br/><br/>

        <font size="5">修改教师信息</font>

        </div>

        <s:form action="updateTeacherAction" method="post">

            <table align="center" width="30%" bgcolor="gray" border="5">

                <%

                ArrayList list=(ArrayList)session.getAttribute("oneInfo");

                Teachinfo info=(Teachinfo)list.get(0);

                %>

                    <tr>

                        <td>

                            学号

                        </td>

                        <td>

                            <input name="id" value="<%=info.getId()%>" readonly="readonly"/>

                        </td>

                    </tr>

                    <tr>

                        <td>

                            姓名

                        </td>

                        <td>

                            <input name="name" value="<%=info.getName()%>"/>

                        </td>

                    </tr>

                    <tr>

                        <td>

                            性别

                        </td>

                        <td>

                            <input name="sex" value="<%=info.getSex()%>"/>

                        </td>

                    </tr>

                    <tr>

                        <td>

                            年龄

                        </td>

                        <td>

                            <input name="age" value="<%=info.getAge()%>"/>

                        </td>

                    </tr>

                    <tr>

                        <td>

                           所在学院

                        </td>

                        <td>

                            <input name="department" value="<%=info.getDepartment()%>"/>

                        </td>

                    </tr>

                    <tr>

                        <td colspan="2">

                            <s:submit value="提交"></s:submit>

                        </td>

                    </tr>

                    <tr>

                        <td align="center" colspan="2">

                            <s:a href="http://localhost:8080/shiyan4/teacher/findTeacher.jsp">返回</s:a>

                        </td>

                    </tr>

            </table>

        </s:form>

    </body>

</html>

deleteTeacher.jsp页面代码如下:

<%@page import="PO.Teachinfo"%>

<%@page import="java.util.ArrayList"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><s:text name="教师信息管理系统-删除"/></title>

    </head>

    <body bgcolor="pink">

        <%response.setCharacterEncoding("UTF-8");%>

        <div align="center">

            <hr color="red"/>

        <br/>

        <table align="center" width="80%">

            <tr>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/lookTeacher.jsp">查看教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/addTeacher.jsp">添加教师信息</s:a>

                </td>

                <td width="25%">

                    <s:a href="http://localhost:8080/shiyan4/teacher/findTeacher.jsp">修改教师信息</s:a>

                </td>

                <td width="25%">

                    删除教师信息

                </td>

            </tr>

        </table>

        <br/>

        <hr color="red"/>

        <br/><br/><br/>

        <font size="5">删除教师信息</font>

        </div>

        <s:form action="deleteTeacherAction" method="post">

        <table align="center" width="40%" border="5">

            <tr>

                <td>

                    请选择要删除教师的编号:

                </td>

                <td>

                    <select name="id">

                         <%

                            ArrayList list=(ArrayList)session.getAttribute("allInfo");

                            if(list.isEmpty()){

                                %>

                                <option value="null">null</option>

                                <%

                            }else{

                                for(int i=0;i<list.size();i++){

                                       Teachinfo info=(Teachinfo)list.get(i);

                                    %>

                                        <option value="<%=info.getId()%>"><%=info.getId()%></option>

                                    <%

                                    }

                                }

                            %>

                    </select>

                </td>

                <td>

                    <s:submit value="确定"></s:submit>

                </td>

            </tr>

        </table>

        </s:form>

    </body>

</html>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

        "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

   

    <package name="default" extends="struts-default">    

        <action name="lookTeacherAction" class="teacherAction.LookTeacherAction">

            <result name="success">/teacher/lookTeacher.jsp</result>

            <result name="input">/teacher/index.jsp</result>

        </action>

        <action name="addTeacherAction" class="teacherAction.AddTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/addTeacher.jsp</result>

        </action>

        <action name="findTeacherAction" class="teacherAction.FindTeacherAction">

            <result name="success">/teacher/updateTeacher.jsp</result>

            <result name="input">/teacher/findTeacher.jsp</result>

        </action>

        <action name="updateTeacherAction" class="teacherAction.UpdateTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/updateTeacher.jsp</result>

        </action>

        <action name="deleteTeacherAction" class="teacherAction.DeleteTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/deleteTeacher.jsp</result>

        </action>   

     

    </package>

    </struts>

实验五 Hibernate5利用关联关系操纵对象的应用

实验任务:

使用Hibernate5利用宠物主人和宠物的一对多关联关系实现级联操作。

参考代码如下:

持久化类Pet.java代码如下:

package PO;

import java.io.Serializable;

public class Pet  implements Serializable{

       

        private Integer id;

        private String name;

        private Integer age;

        private String type;

        private Petowner petowner;

       

        public Integer getId() {

                 return id;

        }

        public void setId(Integer id) {

                 this.id = id;

        }

        public String getName() {

                 return name;

        }

        public void setName(String name) {

                 this.name = name;

        }      

        public Integer getAge() {

                 return age;

        }

        public void setAge(Integer age) {

                 this.age = age;

        }

        public String getType() {

                 return type;

        }

        public void setType(String type) {

                 this.type = type;

        }

        public Petowner getPetowner() {

                 return petowner;

        }

        public void setPetowner(Petowner petowner) {

                 this.petowner = petowner;

        }

}

映射文件Pet.hbm.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="PO">

  <class name="Pet" table="pet">

    <id column="id" name="id" type="integer">

      <generator class="identity"/>

    </id>

    <property column="name" name="name" type="string"/>

    <property column="age" name="age" type="integer"/>

    <property column="type" name="type" type="string"/>

   

    <!--一对多双向关联映射的多的一方配置-->

    <many-to-one class="PO.Petowner" column="petownerid" lazy="false" name="petowner" not-null="true"/>

  </class>

</hibernate-mapping>

持久化类Petowner.java代码如下:

package PO;

import java.io.Serializable;

import java.util.*;

public class Petowner implements Serializable{

   

        private Integer id;

        private String name;

        private String telephone;

        private String address;

        private Set pets = new HashSet();

       

        public Integer getId() {

                 return id;

        }

        public void setId(Integer id) {

                 this.id = id;

        }

        public String getName() {

                 return name;

        }

        public void setName(String name) {

                 this.name = name;

        }

        public String getTelephone() {

                 return telephone;

        }

        public void setTelephone(String telephone) {

                 this.telephone = telephone;

        }

        public String getAddress() {

                 return address;

        }

        public void setAddress(String address) {

                 this.address = address;

        }

        public Set getPets() {

                 return pets;

        }

        public void setPets(Set pets) {

                 this.pets = pets;

        }

}

映射文件Petowner.hbm.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="PO">

  <class name="Petowner" table="petowner">

    <id column="id" name="id" type="integer">

      <generator class="identity"/>

    </id>

    <property column="name" name="name" type="string"/>

    <property column="telephone" name="telephone" type="string"/>

    <property column="address" name="address" type="string"/>  

    <set cascade="all" inverse="true" lazy="false" name="pets">

      <key column="petownerid"/>

      <one-to-many class="PO.Pet"/>

    </set>

  </class>

</hibernate-mapping>

Hibernate5配置文件hibernate.cfg.xml代码如下:

<!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!--Hibernate配置文件的根元素,其它元素应在其中-->

<hibernate-configuration>

        <!-- 设置初始化Hibernate参数的元素,其中指定Hibernate初始化参数,表明以下的配置是针对session-factory配置,SessionFactory是Hibernate中的一个接口,这个接口主要负责保存Hibernate的配置信息,以及对Session的操作 -->

        <session-factory>

        <!-- 设置连接数据库所用的驱动 ,本例中的com.mysql.jdbc.Driver 是MySQL的驱动名字-->

                 <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!--设置数据库连接使用的url,“jdbc:mysql://localhost(IP):port/test”,其中,localhost(IP)表示MySQL服务器名称,即连接地址,此处为本机。port代表MySQL服务器的端口号,默认是3306。test是数据库名,即要连接的数据库名-->

                 <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/shiyan5?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>

                 <!-- 设置数据库的用户名(登录名) -->

                 <property name="hibernate.connection.username">root</property>

                 <!-- 设置数据库的连接密码 -->

                 <property name="hibernate.connection.password">123456</property>

                 <!-- 设置数据库的方言,每种数据库都有对应的方言 -->

                 <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

               

                 <!-- 加入映射文件,可以加入多个映射文件 -->

                 <mapping resource="PO/Petowner.hbm.xml"/>

                 <mapping resource="PO/Pet.hbm.xml"/>

        </session-factory>

</hibernate-configuration>

加载配置文件的HibernateSessionFactory.java类代码如下:

package addHibFile;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

     private HibernateSessionFactory() {

    }

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; 

    private static final ThreadLocal threadLocal = new ThreadLocal();  

    private static final Configuration cfg = new Configuration();

    private static SessionFactory sessionFactory;

    public static Session currentSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        if (session == null) {

            if (sessionFactory == null) {

                try {

                    cfg.configure(CONFIG_FILE_LOCATION);

                    sessionFactory = cfg.buildSessionFactory();

                }

                catch (Exception e) {

                    System.err.println("%%%% Error Creating SessionFactory %%%%");

                    e.printStackTrace();

                }

            }

            session = sessionFactory.openSession();

            threadLocal.set(session);

        }

        return session;

    }

    public static void closeSession() throws HibernateException {

        Session session = (Session) threadLocal.get();

        threadLocal.set(null);

        if (session != null) {

            session.close();

        }

    }

}

对数据表操作的类OneManyDAO.java代码如下:

package DAO;

import addHibFile.HibernateSessionFactory;

import java.util.List;

import org.hibernate.*;

import PO.*;

public class OneManyDAO {

         private Transaction transaction;

         private Session session;

         private Query query;

        public void addPetowner(Petowner petowner) {

                 Session session = HibernateSessionFactory.currentSession();

                 Transaction ts = null;

                 try{

                         ts = session.beginTransaction();

                         session.save(petowner);

                         ts.commit();

                 }catch(Exception ex){

                         ts.rollback();

                         System.out.println("添加客户失败!");

                         ex.printStackTrace();                       

                 }finally{

                         HibernateSessionFactory.closeSession();

                 }

        }

       

          public List findPetownerInfo(){

                session=HibernateSessionFactory.currentSession();

                try{

                    transaction=session.beginTransaction();

                    String queryString="from Petowner";

                    query=session.createQuery(queryString);

                    List list=query.list();

                    transaction.commit();               

                    return list;

                }catch(Exception e){                  

                    e.printStackTrace();

                    return null;

                }

            } 

         

          public List findPetInfo(){

                session=HibernateSessionFactory.currentSession();

                try{

                    transaction=session.beginTransaction();

                    String queryString="from Pet";

                    query=session.createQuery(queryString);

                    List list=query.list();

                    transaction.commit();                

                    return list;

                }catch(Exception e){                  

                    e.printStackTrace();

                    return null;

                }

            }

         

                 public void deletePetowner(Petowner petowner) {

                         Session session = HibernateSessionFactory.currentSession();

                         Transaction ts = null;

                         try{

                                  ts = session.beginTransaction();

                                  session.clear();

                                  session.delete(petowner);

                                  ts.commit();

                         }catch(Exception ex){

                                  ts.rollback();

                                  System.out.println("删除客户失败!");

                                  ex.printStackTrace();                       

                         }finally{

                                  HibernateSessionFactory.closeSession();

                         }

                 }

}

页面index.jsp代码如下:

<%@ page language="java" pageEncoding="utf-8"%>

<%@ page import="DAO.OneManyDAO"%>

<%@ page import="PO.*"%>

<%@ page import="java.util.*"%>

<jsp:useBean id="dao" class="DAO.OneManyDAO" />

<html>

  <head>

    <title>Hibernate5的一对多双向关联关系映射</title>

  </head> 

  <body>

      <h2>Hibernate5的一对多双向关联关系映射</h2>

        <hr>

        <%

            out.println("创建一个新的客户张先生<br>");

            Petowner petowner = new Petowner();

            petowner.setName("张先生");

            petowner.setTelephone("13611111111");

            petowner.setAddress("郑州市金水区东风路");   

                        

            out.println("创建宠物1欢欢<br>");

                 Pet pet1 = new Pet();

                 pet1.setName("欢欢");

                 pet1.setAge(2);               

                 pet1.setType("泰迪");

                 pet1.setPetowner(petowner);

                

                 out.println("创建宠物2小白<br>");             

                 Pet pet2 = new Pet();

                 pet2.setName("小白");

                 pet2.setAge(3);               

                 pet2.setType("牧羊犬");

                 pet2.setPetowner(petowner);

                

                 out.println("将宠物1和宠物2添加到新客户的宠物集合中,并将新客户添加到数据库中<br>");

                 Set pets = new HashSet();

                 pets.add(pet1);

                 pets.add(pet2);

                 petowner.setPets(pets);          

                 dao.addPetowner(petowner);                

        %>

        客户信息保存后,客户表如下所示:

         <table align="center" width="80%" border="5">

            <tr>

                <th>客户id</th>

                <th>客户姓名</th>

                <th>电话</th>

                <th>地址</th>

            </tr>

            <%

               List list=dao.findPetownerInfo();

               if(list.isEmpty()){

             %>

                    <tr>

                        <td align="center">

                            <span>暂无客户信息!</span>

                        </td>

                    </tr>

              <%

                }else{

                    for(int i=0;i<list.size();i++){

                     Petowner pt=(Petowner)list.get(i);

                        %>

                        <tr>

                            <td><%=pt.getId()%></td>

                            <td><%=pt.getName()%></td>

                            <td><%=pt.getTelephone()%></td>

                            <td><%=pt.getAddress()%></td>                         

                        </tr>

                        <%

                    }

                }

            %>

        </table>

        宠物表如下所示:

    <table align="center" width="80%" border="5">

            <tr>

                <th>宠物id</th>

                <th>宠物姓名</th>

                <th>年龄</th>

                <th>类型</th>

                <th>所属客户id</th>

            </tr>

            <%

               list=dao.findPetInfo();

               if(list.isEmpty()){

             %>

                    <tr>

                        <td align="center">

                            <span>暂无宠物信息!</span>

                        </td>

                    </tr>

              <%

                }else{

                    for(int i=0;i<list.size();i++){

                     Pet p=(Pet)list.get(i);

                        %>

                        <tr>

                            <td><%=p.getId()%></td>

                            <td><%=p.getName()%></td>

                            <td><%=p.getAge()%></td>

                            <td><%=p.getType()%></td>

                            <td><%=p.getPetowner().getId()%></td>                         

                        </tr>

                        <%

                    }

                }

            %>

        </table>

    <%

       dao.deletePetowner(petowner);

    %> 

    删除客户后,客户表如下所示:

         <table align="center" width="80%" border="5">

            <tr>

                <th>客户id</th>

                <th>客户姓名</th>

                <th>电话</th>

                <th>地址</th>

            </tr>

            <%

               list=dao.findPetownerInfo();

               if(list.isEmpty()){

             %>

                    <tr>

                        <td align="center">

                            <span>暂无客户信息!</span>

                        </td>

                    </tr>

              <%

                }else{

                    for(int i=0;i<list.size();i++){

                     Petowner pt=(Petowner)list.get(i);

                        %>

                        <tr>

                            <td><%=pt.getId()%></td>

                            <td><%=pt.getName()%></td>

                            <td><%=pt.getTelephone()%></td>

                            <td><%=pt.getAddress()%></td>                         

                        </tr>

                        <%

                    }

                }

            %>

        </table>

        宠物表如下所示:

    <table align="center" width="80%" border="5">

            <tr>

                <th>宠物id</th>

                <th>宠物姓名</th>

                <th>年龄</th>

                <th>类型</th>

                <th>所属客户id</th>

            </tr>

            <%

               list=dao.findPetInfo();

               if(list.isEmpty()){

             %>

                    <tr>

                        <td align="center">

                            <span>暂无宠物信息!</span>

                        </td>

                    </tr>

              <%

                }else{

                    for(int i=0;i<list.size();i++){

                     Pet p=(Pet)list.get(i);

                        %>

                        <tr>

                            <td><%=p.getId()%></td>

                            <td><%=p.getName()%></td>

                            <td><%=p.getAge()%></td>

                            <td><%=p.getType()%></td>

                            <td><%=p.getPetowner().getId()%></td>                        

                        </tr>

                        <%

                    }

                }

            %>

        </table>

  </body>

</html>

实验六 基于Struts2+Hibernate5+Spring5的系统实现

实验任务:

修改实验四,实现基于Struts2+Hibernate5+Spring5框架整合的教师信息管理系统。

修改的参考代码如下:

配置文件applicationContext.xml如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       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-3.0.xsd

           http://www.springframework.org/schema/tx

           http://www.springframework.org/schema/tx/spring-tx.xsd

           ">

  <!-- 配置数据原 --> 

<!-- class="org.apache.commons.dbcp.BasicDataSource"  -->

<bean id="dataSource"  class="com.mchange.v2.c3p0.ComboPooledDataSource"

   <property name="driverClass"    value="com.mysql.cj.jdbc.Driver"></property> 

    <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/teacher?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"></property> 

   <property name="user" value="root"></property> 

   <property name="password" value="123456"></property> 

     <!-- 指定连接数据库连接池的最大连接数 -->

    <property name="maxPoolSize" value="40"/>

    <!-- 指定连接数据库连接池的最小连接数 -->

    <property name="minPoolSize" value="1"/>

    <!-- 指定连接数据库连接池的初始化连接数 -->

    <property name="initialPoolSize" value="1"/>

    <!-- 指定连接数据库连接池的连接的最大空闲时间 -->

    <property name="maxIdleTime" value="20"/>

</bean> 

<!-- 定义了Hibernate的SessionFactory--> 

<bean id="sessionFactory" 

    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"

     <property name="dataSource"

       <ref bean="dataSource" /> 

     </property> 

     <property name="mappingResources"

        <list> 

        <value>PO/Teachinfo.hbm.xml</value>   

        </list> 

     </property> 

     <property name="hibernateProperties"

        <props> 

           <prop key="hibernate.dialect"

                 org.hibernate.dialect.MySQLDialect  

           </prop> 

           <prop key="connection.autocommit">true</prop>

        </props> 

     </property> 

     </bean> 

     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">

         <property name="sessionFactory" ref="sessionFactory"></property>

     </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

     <!-- HibernateTemplate类是简化Hibernate数据访问代码的辅助类,可以获取一个Session对象-->

     <bean id="hibernateTemplate"  class="org.springframework.orm.hibernate5.HibernateTemplate"

          <property name="sessionFactory"

             <ref bean="sessionFactory"/> 

          </property>         

          <property name="checkWriteOperations" value="false"/>

      </bean>

    <!-- 依赖注入-->

    <bean id="dao" class="Dao.TeacherDao" >           

         <property name="hibernateTemplate">  

                  <ref bean="hibernateTemplate"/> 

          </property> 

        </bean>

        <bean id="addTeacherAction" class="teacherAction.AddTeacherAction">

             <property name="dao">  

                  <ref bean="dao"/> 

          </property> 

        </bean>

        <bean id="deleteTeacherAction" class="teacherAction.DeleteTeacherAction">

             <property name="dao">  

                  <ref bean="dao"/> 

          </property> 

        </bean>  

        <bean id="findTeacherAction" class="teacherAction.FindTeacherAction">

             <property name="dao">  

                  <ref bean="dao"/> 

          </property> 

        </bean>

        <bean id="lookTeacherAction" class="teacherAction.LookTeacherAction">

             <property name="dao">  

                  <ref bean="dao"/> 

          </property> 

        </bean>

        <bean id="updateTeacherAction" class="teacherAction.UpdateTeacherAction">

             <property name="dao">  

                  <ref bean="dao"/> 

          </property> 

        </bean>  

</beans>

TeacherDao.java代码如下:

package Dao;

import PO.Teachinfo;

import java.util.List;

import org.springframework.orm.hibernate5.HibernateTemplate;

import org.springframework.transaction.annotation.Transactional;

public class TeacherDao {

  

        private HibernateTemplate hibernateTemplate;

       

    public HibernateTemplate getHibernateTemplate() {

                 return hibernateTemplate;

        }

        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

                 this.hibernateTemplate = hibernateTemplate;

        }      

       

        @Transactional

    public boolean  saveInfo(Teachinfo info){

     try{

             System.out.println("执行dao.saveInfo()");

          hibernateTemplate.save(info);

          hibernateTemplate.flush();

          return true;

     }catch(Exception e){

             System.out.println("saveInfo.error:"+e);

             e.printStackTrace();

         return false;

     }

    }

   

    public List findInfo(String type,Object value){       

        try{

                System.out.println("执行dao.findInfo()");

            String queryString="from Teachinfo as model where model."+type+"=?";

            List list=hibernateTemplate.find(queryString,value);          

            return list;

        }catch(Exception e){

                System.out.println("findInfo.error:"+e);

            e.printStackTrace();

            return null;

        }

    }

    public List findAllInfo(){

      

        try{

                System.out.println("执行dao.findAllInfo()");

                List list=hibernateTemplate.find("from Teachinfo");

            return list;

        }catch(Exception e){

                System.out.println("findInfo.error:"+e);

            e.printStackTrace();

            return null;

        }

    }

   

    @Transactional

    public boolean deleteInfo(String id){

        try{

                System.out.println("执行dao.deleteInfo()");

            Teachinfo info=hibernateTemplate.get(Teachinfo.class,id);

            hibernateTemplate.delete(info);

            hibernateTemplate.flush();

            return true;

        }catch(Exception e){

                System.out.println("deleteInfo.error:"+e);

            e.printStackTrace();

            return false;

        }

    }

   

    @Transactional

    public boolean updateInfo(Teachinfo info){

        try{

                System.out.println("执行dao.updateInfo()");

                hibernateTemplate.update(info);

                hibernateTemplate.flush();

            return true;

        }catch(Exception e){

                System.out.println("updateInfo.error:"+e);

            e.printStackTrace();

            return false;

        }

    }  

}

AddTeacherAction.java代码如下:

package teacherAction;

import Dao.TeacherDao;

import PO.Teachinfo;

import com.opensymphony.xwork2.ActionSupport;

import java.util.List;

import javax.swing.JOptionPane;

public class AddTeacherAction  extends ActionSupport{

        private String id;

        private String name;

        private String sex;

        private int age;

        private String department;

        private String message="input";

        private TeacherDao dao;

       

        public String getId() {

                 return id;

        }

        public void setId(String id) {

                 this.id = id;

        }

        public String getName() {

                 return name;

        }

        public void setName(String name) {

                 this.name = name;

        }

        public String getSex() {

                 return sex;

        }

        public void setSex(String sex) {

                 this.sex = sex;

        }

        public int getAge() {

                 return age;

        }

        public void setAge(int age) {

                 this.age = age;

        }

        public String getDepartment() {

                 return department;

        }

        public void setDepartment(String department) {

                 this.department = department;

        }      

         public TeacherDao getDao() {

                 return dao;

        }

        public void setDao(TeacherDao dao) {

                 this.dao = dao;

        }

       

        public void validate(){

                if(this.getId()==null||this.getId().length()==0){

                    addFieldError("id","教师编号不允许为空!");

                }else{

                        List list=dao.findInfo("id", this.getId());

                    if(!list.isEmpty()){

                        addFieldError("id","教师编号已存在!");

                    }

                }

                if(this.getName()==null||this.getName().length()==0){

                    addFieldError("name","姓名不允许为空!");

                }

                if(this.getAge()>130){

                    addFieldError("age","请认真核实年龄");

                }            

            }

            public String execute() throws Exception{

                    System.out.println("execute()+调用dao.saveInfo()");

                boolean save=dao.saveInfo(info());

                if(save){

                    message="success";

                }

                return message;

            }

            public Teachinfo info(){

                Teachinfo info=new Teachinfo();

                info.setId(this.getId());

                info.setName(this.getName());

                info.setSex(this.getSex());

                info.setAge(this.getAge());

                info.setDepartment(this.getDepartment());

                return info;

            }

            public void message(String mess){

                int type=JOptionPane.YES_NO_OPTION;

                String title="提示信息";

                JOptionPane.showMessageDialog(null, mess, title, type);

            }      

}

DeleteTeacherAction.java代码如下:

package teacherAction;

import Dao.TeacherDao;

import com.opensymphony.xwork2.ActionSupport;

import javax.swing.JOptionPane;

public class DeleteTeacherAction extends ActionSupport{

          private String id;

            private String message;

            private TeacherDao dao;  

           

            public String getId() {

                return id;

            }

            public void setId(String id) {

                this.id = id;

            }

            public TeacherDao getDao() {

                         return dao;

                 }

                 public void setDao(TeacherDao dao) {

                         this.dao = dao;

                 }

                

                 public void validate(){

                if(this.getId().equals("null")){

                    message("暂无教师信息!");

                    addFieldError("id","暂无教师信息!");

                }

            }

            public String execute() throws Exception{

                    System.out.println("execute()+调用dao.deleteInfo()");

                boolean del=dao.deleteInfo(this.getId());

                if(del){

                    message="success";

                }

                return message;

            }

            public void message(String mess){

                int type=JOptionPane.YES_NO_OPTION;

                String title="提示信息";

                JOptionPane.showMessageDialog(null, mess, title, type);

            }

}

FindTeacherAction.java代码如下:

package teacherAction;

import Dao.TeacherDao;

import com.opensymphony.xwork2.ActionSupport;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.swing.JOptionPane;

import org.apache.struts2.ServletActionContext;

public class FindTeacherAction  extends ActionSupport{

            private String id;

            private HttpServletRequest request;

            private TeacherDao dao;

            private String message="input";

           

            public String getId() {

                return id;

            }

            public void setId(String id) {

                this.id = id;

            }

            public TeacherDao getDao() {

                         return dao;

                 }

                 public void setDao(TeacherDao dao) {

                         this.dao = dao;

                 }

                

                 public void validate(){

                if(this.getId().equals("null")){

                    message("暂无教师信息!");

                    addFieldError("id","暂无教师信息!");

                }

            }

            public String execute() throws Exception{

                    System.out.println("execute()+调用dao.findInfo()");

                request=ServletActionContext.getRequest();

                List list=dao.findInfo("id", this.getId());

                request.getSession().setAttribute("oneInfo", list);

                message="success";

                return message;

            }

            public void message(String mess){

                int type=JOptionPane.YES_NO_OPTION;

                String title="提示信息";

                JOptionPane.showMessageDialog(null, mess, title, type);

            }

}

LookTeacherAction.java代码如下:

package teacherAction;

import Dao.TeacherDao;

import com.opensymphony.xwork2.ActionSupport;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class LookTeacherAction extends ActionSupport{

       

            private HttpServletRequest request;

            private TeacherDao dao;

            private String message="input";   

           

            public TeacherDao getDao() {

                         return dao;

                 }

                 public void setDao(TeacherDao dao) {

                         this.dao = dao;

                 }

                 public String execute() throws Exception{

                         System.out.println("execute()+调用dao.findAllInfo()");

                request=ServletActionContext.getRequest();

                List list=dao.findAllInfo();

                request.getSession().setAttribute("count", list.size());

                request.getSession().setAttribute("allInfo", list);

                message="success";

                return message;     

            }

       

}

UpdateTeacherAction.java代码如下:

package teacherAction;

import Dao.TeacherDao;

import PO.Teachinfo;

import com.opensymphony.xwork2.ActionSupport;

import javax.swing.JOptionPane;

public class UpdateTeacherAction   extends ActionSupport{

        private String id;

        private String name;

        private String sex;

        private int age;

        private String department;

        private TeacherDao dao;

        private String message="input";

       

        public String getId() {

                 return id;

        }

        public void setId(String id) {

                 this.id = id;

        }

        public String getName() {

                 return name;

        }

        public void setName(String name) {

                 this.name = name;

        }

        public String getSex() {

                 return sex;

        }

        public void setSex(String sex) {

                 this.sex = sex;

        }

        public int getAge() {

                 return age;

        }

        public void setAge(int age) {

                 this.age = age;

        }

        public String getDepartment() {

                 return department;

        }

        public void setDepartment(String department) {

                 this.department = department;

        }      

         public TeacherDao getDao() {

                 return dao;

        }

        public void setDao(TeacherDao dao) {

                 this.dao = dao;

        }

       

        public void validate(){           

                if(this.getName()==null||this.getName().length()==0){

                    addFieldError("name","姓名不允许为空!");

                }

                if(this.getAge()>130){

                    addFieldError("age","请认真核实年龄");

                }            

            }

         

         public String execute() throws Exception{

                  System.out.println("execute()+调用dao.updateInfo()");

                boolean update=dao.updateInfo(info());

                if(update){

                    message="success";

                }

                return message;

            }

         

         public Teachinfo info(){

                Teachinfo info=new Teachinfo();

                info.setId(this.getId());

                info.setName(this.getName());

                info.setSex(this.getSex());

                info.setAge(this.getAge());

                info.setDepartment(this.getDepartment());

                return info;

            }

         

            public void message(String mess){

                int type=JOptionPane.YES_NO_OPTION;

                String title="提示信息";

                JOptionPane.showMessageDialog(null, mess, title, type);

            }

       

}

配置文件struts.xml代码如下:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

    <package name="zzf" extends="struts-default" >

   

         <action name="lookTeacherAction" class="lookTeacherAction">

            <result name="success">/teacher/lookTeacher.jsp</result>

            <result name="input">/teacher/index.jsp</result>

        </action>

        <action name="addTeacherAction" class="addTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/addTeacher.jsp</result>

        </action>

        <action name="findTeacherAction" class="findTeacherAction">

            <result name="success">/teacher/updateTeacher.jsp</result>

            <result name="input">/teacher/findTeacher.jsp</result>

        </action>

        <action name="updateTeacherAction" class="updateTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/updateTeacher.jsp</result>

        </action>

        <action name="deleteTeacherAction" class="deleteTeacherAction">

            <result name="success" type="chain">lookTeacherAction</result>

            <result name="input">/teacher/deleteTeacher.jsp</result>

        </action>

   

    </package>

</struts>

实验七 Spring AOP的应用

实验任务:

1. 请用Spring5的切入点通知器为接口UserDao.java的实现类UserDaoImpl.java中的两个方法中添加前置通知,使得每个方法在开始运行前先输出“***方法开始执行……”。

UserDao.java代码如下:

package pointcutexample;

public interface UserDao {     

        void addUser();

        void deleteUser();

}

UserDaoImpl.java代码如下:

package pointcutexample;

public class UserDaoImpl implements UserDao { 

        public void addUser(){

                 System.out.println("添加用户成功!");

        }      

        public void deleteUser(){

                 System.out.println("删除用户成功!");

        }

}

参考代码如下所示:

LBeforeAdvice.java类代码如下:

package pointcutexample;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class LBeforeAdvice implements MethodBeforeAdvice{    

         public void before(Method method,Object[] args,Object target) throws Throwable{     

                  System.out.println(method.getName()+"方法开始执行......");         

            }

}

applicationContext.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [

<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">

]>

<beans>

    <bean id="lBeforeAdvice" class="pointcutexample.LBeforeAdvice"/>

    <!--定义切面-->

    <bean id="userDaoAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">

      

        <property name="mappedNames">

            <list>

                <!--通知要应用的目标上的方法名称-->

                <value>*User</value>

            </list>

         </property>

         <!--注入前置通知-->

          <property name="advice">

              <ref bean="lBeforeAdvice"/>

          </property>

   </bean>

    <bean id="userDaoImpl" class="pointcutexample.UserDaoImpl"/>

    <bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">

       <property name="proxyInterfaces" value="pointcutexample.UserDao"/>

       

         <!--指定目标对象-->

         <property name="target" >

              <ref bean="userDaoImpl"/>

         </property>

         <!--指定通知-->

         <property name="interceptorNames">

                <list>

                    <!--指定切面-->

                    <value>userDaoAdvisor</value>

                </list>

         </property>

    </bean>

</beans>

Test.java代码如下:

package pointcutexample;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Test {

    public static void main(String[] args) {

         ApplicationContext ac=new

FileSystemXmlApplicationContext("src/pointcutexample/applicationContext.xml");        

         UserDao userDaoImpl=(UserDao)ac.getBean("userDaoProxy");

         userDaoImpl.addUser();

         userDaoImpl.deleteUser(); 

    }

}

  • 32
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Web开发是为Internet(World Wide Web)或Intranet(私有网络)开发网站所涉及的工作。Web开发的范围可以从开发简单的纯文本单个静态页面到复杂的基于WEB,在英语中web即表示网页的意思,它用于表示Internet主机上供外界访问的资源。 Internet上供外界访问的Web资源分为: 静态web资源(如html 页面):指web页Web的Internet应用程序(Web应用程序)。 面中供人们浏览的数据始终是不变。 动态web资源:指web页面中供人们浏览的数据是由程序产生的,不同时间点访问web页面看到的内容各不相同。 静态web资源开发技术:Html 常用动态web资源开发技术:JSP/Servlet、ASP、PHP等 在Java中,动态web资源开发技术统称为Javaweb。+ WEB应用程序指供浏览器访问的程序,通常也简称为web应用。例如有a.html 、b.html…..多个web资源,这多个web资源用于对外提供服务,此时应把这多个web资源放在一个目录中,以组成一个web应用(或web应用程序) Spring框架一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。Spring可以单独应用于构筑应用程序,也可以和Struts、Webwork、Tapestry等众多Web框架组合使用,并且可以与 Swing等桌面应用程序AP组合。因此, Spring不仅仅能应用于J2EE应用程序之中,也可以应用于桌面应用程序以及小应用程序之中。Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC
好的,以下是实现教师信息管理系统的具体步骤: 1. 搭建开发环境:安装JDK、Tomcat、MySQL、Eclipse等开发工具和软件。 2. 创建数据库:创建一个名为teacher_db的数据库,其中包含teacher表,用于存储教师信息。表结构如下: ```sql CREATE TABLE teacher ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, gender VARCHAR(10) NOT NULL, age INT(11) NOT NULL, subject VARCHAR(20) NOT NULL, PRIMARY KEY (id) ) ENGINE=INNODB DEFAULT CHARSET=utf8; ``` 3. 创建项目:使用Eclipse创建一个基于Struts2+Hibernate5框架的Web项目。 4. 配置数据库连接:在项目的src/main/resources目录下创建hibernate.cfg.xml文件,配置数据库连接信息。 ```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> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/teacher_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.example.teacher.model.Teacher"/> </session-factory> </hibernate-configuration> ``` 5. 创建Model类:在src/main/java目录下创建Teacher类,用于映射teacher表。 ```java package com.example.teacher.model; public class Teacher { private int id; private String name; private String gender; private int age; private String subject; // getter and setter methods // toString method } ``` 6. 创建DAO类:在src/main/java目录下创建TeacherDAO类,用于操作数据库。 ```java package com.example.teacher.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import com.example.teacher.model.Teacher; import com.example.teacher.util.HibernateUtil; public class TeacherDAO { private SessionFactory sessionFactory; public TeacherDAO() { sessionFactory = HibernateUtil.getSessionFactory(); } public void addTeacher(Teacher teacher) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(teacher); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } } public void updateTeacher(Teacher teacher) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(teacher); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } } public void deleteTeacher(int id) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Teacher teacher = (Teacher) session.get(Teacher.class, id); session.delete(teacher); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } } public Teacher getTeacherById(int id) { Session session = sessionFactory.openSession(); Transaction tx = null; Teacher teacher = null; try { tx = session.beginTransaction(); teacher = (Teacher) session.get(Teacher.class, id); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } return teacher; } public List<Teacher> getAllTeachers() { Session session = sessionFactory.openSession(); Transaction tx = null; List<Teacher> teachers = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from Teacher"); teachers = query.list(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } return teachers; } } ``` 7. 创建Action类:在src/main/java目录下创建TeacherAction类,用于处理请求和返回响应。 ```java package com.example.teacher.action; import java.util.List; import com.example.teacher.dao.TeacherDAO; import com.example.teacher.model.Teacher; import com.opensymphony.xwork2.ActionSupport; public class TeacherAction extends ActionSupport { private static final long serialVersionUID = 1L; private Teacher teacher; private List<Teacher> teachers; private TeacherDAO teacherDAO; public TeacherAction() { teacherDAO = new TeacherDAO(); } public String addTeacher() { teacherDAO.addTeacher(teacher); return SUCCESS; } public String updateTeacher() { teacherDAO.updateTeacher(teacher); return SUCCESS; } public String deleteTeacher() { teacherDAO.deleteTeacher(teacher.getId()); return SUCCESS; } public String getTeacherById() { teacher = teacherDAO.getTeacherById(teacher.getId()); return SUCCESS; } public String getAllTeachers() { teachers = teacherDAO.getAllTeachers(); return SUCCESS; } // getter and setter methods } ``` 8. 创建视图:在WebContent目录下创建JSP文件,用于呈现数据和处理用户交互。 ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>教师信息管理系统</title> </head> <body> <h1>教师信息管理系统</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>科目</th> <th>操作</th> </tr> <s:iterator value="teachers"> <tr> <td><s:property value="id"/></td> <td><s:property value="name"/></td> <td><s:property value="gender"/></td> <td><s:property value="age"/></td> <td><s:property value="subject"/></td> <td> <a href="<s:url action='getTeacherById' namespace='/'><s:param name='teacher.id' value='%{id}'/></s:url>">编辑</a> <a href="<s:url action='deleteTeacher' namespace='/'><s:param name='teacher.id' value='%{id}'/></s:url>">删除</a> </td> </tr> </s:iterator> <tr> <td colspan="6"><a href="<s:url action='addTeacher' namespace='/'/>">添加教师</a></td> </tr> </table> <s:if test="teacher != null"> <h2>编辑教师信息</h2> <s:form action="updateTeacher" namespace="/" method="post"> <s:hidden name="teacher.id" value="%{teacher.id}"/> <s:textfield label="姓名" name="teacher.name" value="%{teacher.name}"/> <s:textfield label="性别" name="teacher.gender" value="%{teacher.gender}"/> <s:textfield label="年龄" name="teacher.age" value="%{teacher.age}"/> <s:textfield label="科目" name="teacher.subject" value="%{teacher.subject}"/> <s:submit value="保存"/> </s:form> </s:if> </body> </html> ``` 9. 配置Struts2:在src/main/resources目录下创建struts.xml文件,配置Struts2相关信息。 ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" extends="struts-default"> <action name="getAllTeachers" class="com.example.teacher.action.TeacherAction" method="getAllTeachers"> <result name="success">/teacher.jsp</result> </action> <action name="addTeacher" class="com.example.teacher.action.TeacherAction" method="addTeacher"> <result name="success">/teacher.jsp</result> </action> <action name="updateTeacher" class="com.example.teacher.action.TeacherAction" method="updateTeacher"> <result name="success">/teacher.jsp</result> </action> <action name="deleteTeacher" class="com.example.teacher.action.TeacherAction" method="deleteTeacher"> <result name="success">/teacher.jsp</result> </action> <action name="getTeacherById" class="com.example.teacher.action.TeacherAction" method="getTeacherById"> <result name="success">/teacher.jsp</result> </action> </package> </struts> ``` 10. 运行项目:将项目部署到Tomcat服务器上,并访问http://localhost:8080/teacher/getAllTeachers,即可查看教师信息列表。 以上就是基于Struts2+Hibernate5框架实现教师信息管理系统的全部内容,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值