学生选课系统项目介绍及需求

学生选课系统项目介绍及需求

第一天 笔记:
数据库基础知识
主键:Primary Key ,在表中唯一确定该条记录的字段
外键:Foreign Key ,引用(参照)另外一个表中的主键字段

图书表

id     图书名称           类别     价格
1      Java编程思想       1        50
2      Hibernate入门      1        60
3      成功有方法         2        30

id是主键,类别是外键,
主表(在关联关系中,包含主键字段的表叫主表),从表(在关联关系中,包含外键字段的表叫从表)


图书表是从表(因为它包含类别的外键)
图书类别表是主表(因为它包含了类别的主键)

图书类别表
id  名称
1   计算机
2   励志
3   地理
4   历史

表设计不合理,会产生的问题
1.重复问题,2.删除问题 3.修改的问题

满足三范式

多表关联查询

select 图书名称,名称,价格 from 图书表,图书类别表 where 图书表.类别=图书类别表.id

select a.图书名称,b.名称 as 图书类别,a.价格 from 图书表 a,图书类别表 b where a.类别=b.id

curricula 数据库
=========================================
为了降低复杂性,不考虑上课时间问题
   1.学生在同一时间不能同时上两门课程
   2.教师在同一时间不能讲授两门课程
   3.同一个教室在同一时间不可能开两门课程

不考虑学生班级的问题,认为一个年级只有一个班级。
任何一个学生,可以选任何一个老师的课。
========================================
实体(entity)= 模型(model) = 对象(object)

学生
Student(id,name,sex,pwd,phone,grade,photo)

紧急联系人
Contact(id,name,sex,relation,phone)

教室
room(id,name,address)

课程
class(id,name,type,hours)

教师
teacher(id,name,sex,phone)

双向关系和单向关系  联系人和学生 

1.学生-紧急联系人(一对一)

  站在学生角度:getContact(),站在联系人角度:getStudent()

2.学生-课程(多对多):一个学生可以选择多个课程,一个课程,可以被多个学生选择。
  站在学生角度:getClasses(),站在课程角度:getStudents()
 
  =======================================================================
3.老师-课程(一对多):一个老师,可以上多门课程,一门课程只能一个老师上。
  站在老师角度:getClasses() 站在课程角度:getTeacher()  
 
4.教室-课程(一对多):一个教室,可以上多门课程,一门课程只能在一个教室上。
  站在教室角度:getClasses(),站在课程角度:getRoom()

 学生和老师不直接产生关系
 学生和教室不直接产生关系

 教室和教师不直接产生关系

第二天 笔记:
注册功能:
 通过注册增加学生
 学生注册时,只需要输入用户名和密码,其他信息在修改页面上输入。


管理员可以增加课程,增加教师,为课程指定教师。


学生可以选课。

Student(id,name,sex,pwd,phone,grade,photo)

1. 主页面 - main.jsp
  注册(register.jsp)
  登录(login.jsp)  (修改信息-modify.jsp)
  选课(choose.jsp)
  进入后台管理(admin.jsp)
main.jsp

<body>
主页面
<br/>
<br/>
<a href="${pageContext.request.contextPath}/admin.jsp">进入后台管理</a>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/register.jsp">注册</a>  <a href="${pageContext.request.contextPath}/login.jsp">登录</a>  <a href="${pageContext.request.contextPath}/choose.jsp">选课</a>
</body>

register.jsp

<body>
注册
<br/>
<br/>
<form method="post" action="">
<table>
<tr><td>用户名:</td><td><input type="text"/></td></tr>
<tr><td>密码:</td><td><input type="password"/></td></tr>
<tr>
  <td>重复密码:</td>
  <td><input type="password"/></td>
</tr>
<tr>
  <td>性别</td>
  <td><input type="radio" value="男" checked>
    男
    <input type="radio"  value="女">
    女</td>
</tr>
<tr>
  <td>年级:</td>
  <td>
    <select >
      <option value="一年级">一年级</option>
      <option value="二年级">二年级</option>
      <option value="三年级">三年级</option>
      <option value="四年级">四年级</option>
      </select></td>
</tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>

login.jsp

<body>
登录
<br/>
<br/>
<form action="" method="post">
<table>
<tr><td>用户名:</td><td><input type="text"/></td></tr>
<tr><td>密码:</td><td><input type="password" /></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>

admin.jsp

<body>
后台管理
<br/>
<br/>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>

choose.jsp

<body>
选课
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
 
重复密码不提交,在表单变量中,就不能指定其name属性。
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Struts Blank</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

======================================================================

HibernateUtil.java

package common;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

		private static SessionFactory sessionFactory;

		private static SessionFactory buildSessionFactory() {
			try {
				Configuration configuration = new Configuration();
				configuration.configure("hibernate.cfg.xml");

				ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
						.applySettings(configuration.getProperties()).build();

				SessionFactory sessionFactory = configuration
						.buildSessionFactory(serviceRegistry);

				return sessionFactory;
			} catch (Throwable ex) {
				throw new ExceptionInInitializerError(ex);
			}
		}

		public static SessionFactory getSessionFactory() {
			if (sessionFactory == null)
				sessionFactory = buildSessionFactory();
			return sessionFactory;
		}

		public static Session openSession() {
			return getSessionFactory().openSession();
		}

}

Student.java

package model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {
	private int id;
	private String name;
	private String pwd;
	private String phone;
	private String grade;
	private String photo;
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	
}

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="model">
<class name="Student" table="student">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"></property>
        <property name="pwd" column="pwd" type="string" length="50"></property>
        <property name="phone" length="50"></property>
        <property name="photo" length="150"></property>
    </class>
</hibernate-mapping>

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-configuration>
	<session-factory>
			<!-- Database connection settings -->
		       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/curricula</property> 
				
		<property name="connection.username">root</property> 
				
		<property name="connection.password">12345678</property>  
				
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 		
		<property name="show_sql">true</property>
 
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
		<mapping class="model.Student"/>
	</session-factory>
</hibernate-configuration>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />                                  
</struts>
==================================================================

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-configuration>
	<session-factory>
			<!-- Database connection settings -->
		       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/curricula</property> 
				
		<property name="connection.username">root</property> 
				
		<property name="connection.password">12345678</property>  
				
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 		
		<property name="show_sql">true</property>
 
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
		<mapping class="model.Student"/>   //配置数据库
	</session-factory>
</hibernate-configuration>
第三天 笔记:

HQL语法

select count(*) from users

SQL:查找数据库记录
HQL=Hibernate Query Language

查找对象 

http://blog.csdn.net/xinyu0100/article/details/5385989

http://www.360doc.com/content/11/0419/15/1861654_110769193.shtm

java.lang.NoSuchMethodException: action.StudentAction.check() 

没有这个方法

<s:radio/> 标签

http://www.itzhai.com/struts2-radio-button-label-s-radio-use-and-set-the-default-value.html

<s:select/> 标签
http://blog.csdn.net/q3498233/article/details/7057230

上传文件的表单设置

enctype="multipart/from-data" method="post"

<img id="image" name="image" src="" />

<input type="file" name="file" οnchange="setImage(this)"/>

</body>

<script language="javascript">

function setImage(obj){
    image.src = obj.value;
}

</script>

设置图片宽度

只设置宽度,将会按比例缩放

<style type="text/css">
#pic
{
width:300px;
}
</style>

添加错误信息显示的div id="msg"

1.判断旧密码是否正确

   action:checkpwd

   http://blog.sina.com.cn/s/blog_4f925fc30100la36.html

   $.get,$.post,$.ajax

  同步和异步
  同步:命令发出以后,等待命令执行完毕,再继续执行后面的命令。
  默认是异步。

2.上传文件保存的问题

  File image;
  String imageContentType
  String imageFileName

 快捷键 Alt+Shift+S r


修改信息的action为modify

1.为上传的图片生成唯一的名字
  根据日期,上传文件的名字(扩展名),来计算目录名

  Calendar cal=Calendar.getInstance();
  int hour=cal.get(Calendar.HOUR_OF_DAY); 24小时制,12小时用HOUR

  上传文件存放格式

  uploadfiles/2015/03/15122018005.jpg

 getRealPath的说明
 http://blog.csdn.net/jxst051665/article/details/4350994

 创建目录和生成文件名的代码
 =============================================================
//如果保存上传文件的根目录不存在,创建根目录

//如果保存上传文件的根目录不存在,创建根目录
String fileName="uploadfiles";
HttpServletRequest req=ServletActionContext.getRequest();
fileName=req.getServletContext().getRealPath("")+fileName;
File file=new File(fileName);
if(!file.exists())
{
file.mkdir();
}
Calendar cal=Calendar.getInstance();

//如果年的目录不存在,创建年的目录
int year=cal.get(Calendar.YEAR);
fileName=fileName + "\\" + year;
file=new File(fileName);
if(!file.exists())
{
file.mkdir();
}
//如果月份不存在,创建月份的目录
int month=cal.get(Calendar.MONTH)+1;
fileName=fileName+"\\";
if(month<10)
{
fileName=fileName+"0";
}
fileName=fileName+month;
file=new File(fileName);
if(!file.exists())
{
file.mkdir();
}
//生成文件名的日部分
int day=cal.get(Calendar.DAY_OF_MONTH);
fileName=fileName+"\\";
if(day<10)
{
fileName=fileName+"0";
}
fileName=fileName+day;

//生成文件名的小时部分
int hour=cal.get(Calendar.HOUR_OF_DAY);
if(hour<10)
{
fileName=fileName+"0";
}
fileName=fileName+hour;

//生成文件名的分钟部分
int minute=cal.get(Calendar.MINUTE);
if(minute<10)
{
fileName=fileName+"0";
}
fileName=fileName+minute;

//生成文件名的秒部分
int second=cal.get(Calendar.SECOND);
if(second<10)
{
fileName=fileName+"0";
}
fileName=fileName+second;

//生成文件名的毫秒部分
int millisecond=cal.get(Calendar.MILLISECOND);
if(millisecond<10)
{
fileName=fileName+"0";
}
if(millisecond<100)
{
fileName=fileName+"0";
}
fileName=fileName+millisecond;

//生成文件的扩展名部分
fileName=fileName+ imageFileName.substring(imageFileName.indexOf(".")) ;
System.out.println(fileName);
 =============================================================

2.保存上传的文件

3.设置student的photo属性

4.保存student的信息

saveOrUpdate

5.返回主页面

两个问题自己去实现

1.修改的时候,不想修改图片。
2.修改图片时,应该先删除之前的图片。

进一步完善用户基本信息修改的问题

1.不想修改密码的问题。
2.不想修改图片的问题。

3.修改图片时,如果之前已经上传过图片,应该先删除之前的图片。

http://blog.csdn.net/xinyu0100/article/details/5385989

==========================================================================

第四天 笔记:


添加session为空的判断


Student(id,name,sex,pwd,phone,grade,photo)


紧急联系人
Contact(id,name,sex,relation,phone)




1.学生-紧急联系人(一对一)


  站在学生角度:getContact(),站在联系人角度:getStudent()








1.编写联系人的页面


<body>
<form action="" method="post">
<table>
<tr><td>姓名:</td><td><input type="text"/></td></tr>
<tr><td>性别:</td><td><input type="text"/></td></tr>
<tr><td>关系:</td><td><input type="text"/></td></tr>
<tr><td>电话:</td><td><input type="text"/></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>


2.添加超链接,指向联系人页面


3.分析一下数据库表的关系


在学生表中,增加一个外键cid,指向Contact 的 id


Student(id,cid,name,sex,pwd,phone,grade,photo) 从表


Contact(id,name,sex,relation,phone)            主表


4.实现3的功能,hibernate代码应该怎么写?


如果想在student表中增加指向contact表的一个字段,那么就在Student类中增加一个属性Contact


@OneToOne
@JoinColumn(name="cid") alt+/


单向关系


双相关系


@OneToOne(mappedBy="contact")

=================================功能已全部实现=================================

action 包

ContactAction.java

package action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import dao.ContactDAO;
import dao.StudentDAO;
import model.Contact;
import model.Student;

public class ContactAction extends ActionSupport {

	private Contact contact;
	private ContactDAO dao =new ContactDAO();
	private StudentDAO sdao =new StudentDAO();
	public Contact getContact() {
		return contact;
	}

	public void setContact(Contact contact) {
		this.contact = contact;
	}

	public String update() {
		//保存contact
		return updateit();
	}

	public String modify()
	{
		return updateit();
	}
	
	private String updateit() {
		dao.update(contact);
		HttpServletRequest request= ServletActionContext.getRequest();
		HttpSession session= request.getSession();
		Student student= (Student) session.getAttribute("STUDENT");
		student.setContact(contact);
//		contact.setStudent(student);//这种得不到uid(保存谁就要设置谁)
		//保存student
		sdao.update(student);
		return "main";
	}
}

CourseAction.java

package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import common.Pager;
import dao.CourseDAO;
import dao.RoomDAO;
import dao.StudentDAO;
import dao.TeacherDAO;
import model.Course;
import model.Room;
import model.Student;
import model.Teacher;


public class CourseAction {

	private RoomDAO rdao =new RoomDAO();
	private CourseDAO dao = new CourseDAO();
	private TeacherDAO tdao =new TeacherDAO();
	private Teacher teacher;
	private Course course;
	private Room room;
	public Room getRoom() {
		return room;
	}

	public void setRoom(Room room) {
		this.room = room;
	}
	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	private int page;
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}
	public String main()
	{
		prepareDate();
		return "coursemain";
		
	}

	private void prepareDate() {
		HttpServletRequest request= ServletActionContext.getRequest();
		//显示所有教室信息
		if(page==0)//不传页码时,默认显示第0页
		{
			page=1;
		}
		
		Pager pager =new Pager();
		dao.initpage(pager);
		//若果当前页大于总页数,就让他等于总页数
		if(page>pager.getPageCount())
		{
			page=pager.getPageCount();
		}
		if(ServletActionContext.getContext().get("ADD")!=null)
		{
			page=pager.getPageCount();
		}
		pager.setPageNo(page);
		StringBuilder str =new StringBuilder();
		List<Course> list=dao.getcourse(pager);//用类调用时为了少定义变量
		//判断是否有教室
		if(list.size()>0)
		{
			
			ActionContext ax= ServletActionContext.getContext();
			ax.put("TEACHERS", tdao.getteacher());
			ax.put("ROOMS", rdao.getRooms(pager));
			ax.put("COURSE", list);
			
			//构建分页导航按钮
			int btns=pager.getBtnCount();
			btns=btns/2;
			int start =page-btns;
			int end =page+btns;
			if(start<1)
			{
				start=1;
				end =start +2*btns;
			}
			
			if(end>pager.getPageCount())
			{
				start =end -2*btns;
				end=pager.getPageCount();
				
			}
			if(start<1)
			{
				start =1;
			}
			for(int i=start;i<=end;i++)
			{
				str.append("<a href='"+request.getContextPath() +"/course/main?page=" +i+"'>");
				if(i==page)
				{
					str.append("<font color ='red'><b>");
					str.append(i);
					str.append("</b></font>");
				}
				else
				{
					str.append(i);
				}
				
				str.append("</a>");
				str.append("  ");
			}
			str.append("<br>");
			ax.put("NAVBAR", str.toString());//保存数据
			System.out.println(str.toString());
		}
	}
	
	public String imain()
	{
		prepareDate();
		return "initmain";
	}
	
	public String cmain() throws IOException
	{
		//如果没有登录跳转到login.jsp//办法一
//		Object object= ActionContext.getContext().getSession().get("STUDENT");
//		if(object==null)
//		{
//			HttpServletResponse response= ServletActionContext.getResponse();
//			HttpServletRequest request= ServletActionContext.getRequest();
//			response.sendRedirect(request.getContextPath()+"/login.jsp");
//			return null;
//		}
		//办法二
		HttpServletResponse response= ServletActionContext.getResponse();
		HttpServletRequest request= ServletActionContext.getRequest();
		Object object= request.getSession().getAttribute("STUDENT");
		if(object==null)
		{
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return null;
		}		
		prepareDate();
		return "choosemain";
	}
	public String update()
	{
		return updateIt();
		
	}

	private String updateIt() {
		if(course.getId()==0)
		{
			ServletActionContext.getContext().put("ADD", 1);
		}
		dao.update(course);
		return main();
	}
	
	public String modify()
	{
		return updateIt();
	}
	public String delet()
	{
		dao.deletcourse(course);
		return null;
		
	}
	
	public String get()
	{
		course= dao.get(course);
		HttpServletResponse response= ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		try {
			PrintWriter out =response.getWriter();
			out.print(course.getId()+"!"+course.getName()+"!"+course.getType()+"!"+course.getHours());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	public String updateTeacher()
	{
		teacher=tdao.get(teacher);
		course=dao.get(course);
		course.setTeacher(teacher);
		dao.update(course);
		return null;
	}
	
	public String updateRoom()
	{
		room =rdao.get(room);
		course=dao.get(course);
		course.setRoom(room);
		dao.update(course);
		return null;
	}

	public String checkesSelect()
	{
		Student student= (Student) ActionContext.getContext().getSession().get("STUDENT");
		Set<Course> courses= student.getCourses();
		Iterator<Course> it= courses.iterator();
		boolean flag=false;
		while(it.hasNext())
		{
			Course courseit= it.next();
			if(courseit.getId()==course.getId())
			{
				flag=true;
				break;
			}
		}	
		HttpServletResponse response= ServletActionContext.getResponse();
		try {
			PrintWriter out= response.getWriter();
			out.print(flag);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public String checkit()
	{
		//Student没有与数据库中的Student关联,要去关联
		Student student= (Student) ActionContext.getContext().getSession().get("STUDENT");
		StudentDAO sdao =new StudentDAO();
		student= sdao.check(student);//
		course=dao.get(course);//
		
		Set<Course> courses= student.getCourses();
		Iterator<Course> it= courses.iterator();
		boolean flag=false;
		Course courseit=null;
		while(it.hasNext())
		{
			courseit= it.next();
			if(courseit.getId()==course.getId())
			{
				flag=true;
				break;
			}
		}
			if(flag)//有选择这门课就删除
			{
				student.getCourses().remove(courseit);
			}
			else//没有这门课就添加
			{
				student.getCourses().add(course);
			}
			
			sdao.update(student);
			
		return null;
	}
}
RoomAction.java
package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import common.Pager;
import dao.RoomDAO;
import model.Room;

public class RoomAction extends ActionSupport{
	
	RoomDAO dao=new RoomDAO();
	private int page;
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	private Room room;
	public String main()
	{
		HttpServletRequest request=ServletActionContext.getRequest();
		//准备需要显示的数据
		if(page==0)
		{
			page=1;
		}
		Pager pager =new Pager();
		dao.initpage(pager);
		//如果当前页大于总页数,就让他等于总页数
		if(page>pager.getPageCount())
		{
			page=pager.getPageCount();
		}
		if(ServletActionContext.getContext().get("ADD")!=null)
		{
			page=pager.getPageCount();
		}
		pager.setPageNo(page);
		StringBuilder str=new StringBuilder();
		List<Room>list=dao.getRooms(pager);   //当前页数
		
		if(list.size()>0)
		{
			ActionContext ctx=ServletActionContext.getContext();
			ctx.put("ROOMS",list);
			//每页显示多少 分页导航按钮
			int btns=pager.getBtnCount();
			btns=btns/2;
			int start=page-btns;
			int end=page+btns;
			if(start<1)
			{
				start=1;
				end=start+2*btns;
			}
			if(end>pager.getPageCount())
			{	
				start=end-2*btns;
				end=pager.getPageCount();
			}
			if(start<1)
			{
				start=1;
			}
			for(int i=start;i<=end;i++)
			{
				
				str.append("<a href='" + request.getContextPath() + "/room/main?page=" + i + "'>");
				if(i==page)
				{
					str.append("<font color ='red'><b>");
					str.append(i);
					str.append("</b></font>");
				}
				else
				{
					str.append(i);
				}
				str.append("</a>");
				str.append("  ");
			}
			str.append("<br>");
		    ctx.put("NAVBAR", str.toString());//保存数据
			System.out.println(str.toString());
		}
		return "roommain";
	}
	public Room getRoom() {
		return room;
	}
	public void setRoom(Room room) {
		this.room = room;
	}
	public String update()
	{
		//添加room为零   修改大于0
		return updateIt();
	}
	private String updateIt() {
		if(room.getId()==0)
		{
			ServletActionContext.getContext().put("ADD", 1);
		}
		dao.update(room);
		return main();
	}
	public String modify()
	{
		return updateIt();
		
	}
	public String delet()
	{
		dao.delet(room);
		return null;
	}
	public String get()
	{
		room=dao.get(room);
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		try {
			PrintWriter out=response.getWriter();
			out.print(room.getId() + "!" + room.getName() + "!" + room.getAddress());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;	
	}
}

StudentAction.java

package action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import dao.StudentDAO;
import model.Student;

public class StudentAction {
	private Student student;
	private File image;
	private String imageFileName;
	private String imageContentType;
	StudentDAO dao=new StudentDAO();
	public Student getStudent() {
		return student;
	}

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
	//处理方法
	public String add()
	{
		dao.update(student);
		return "main";
    }
	public String check()
	{
		Student stud=dao.check(student); //表单上的传进去
		if(stud==null) //如果为空就转 login
		{
			return "login";
		}
		/*HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		session.setAttribute("STUDENT", stud);*/
		ActionContext.getContext().getSession().put("STUDENT", stud);  //把信息存到 session
		return "main";
	}
	public String checkpwd() throws IOException
	{
		String result="0";
		if(dao.checkpwd(student))
		{
			result="1";
		}
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter out=response.getWriter();
		out.print(result);
		return null;
	}
	public String update() throws IOException
	{
		return updateit();
		
	}
	public String modify() throws IOException{
		return updateit();
	}

	private String updateit() throws IOException {
		HttpServletRequest req=ServletActionContext.getRequest();
		if(image!=null)
		{
		//如果保存上传文件的根目录不存在,创建根目录
		String fileName="uploadfiles";
		String url=fileName;
		fileName=req.getServletContext().getRealPath("")+fileName;  //得到网站根目录
		File file=new File(fileName);  //包装文件夹
		if(!file.exists())
		{
			file.mkdir();
		}
		Calendar cal=Calendar.getInstance();

		//如果年的目录不存在,创建年的目录
		int year=cal.get(Calendar.YEAR);
		fileName=fileName + "\\" + year;
		url=url+"\\"+year;
		file=new File(fileName);
		if(!file.exists())
		{
			file.mkdir();
		}
		//如果月份不存在,创建月份的目录
		int month=cal.get(Calendar.MONTH)+1;
		fileName=fileName+"\\";
		url=url+"\\";
		if(month<10)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+month;
		url=url+month;
		file=new File(fileName);
		if(!file.exists())
		{
			file.mkdir();
		}

		//生成文件名的日部分
		int day=cal.get(Calendar.DAY_OF_MONTH);
		fileName=fileName+"\\";
		url=url+"\\";
		if(day<10)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+day;
		url=url+day;
		//生成文件名的小时部分
		int hour=cal.get(Calendar.HOUR_OF_DAY);
		if(hour<10)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+hour;	
		url=url+hour;
		//生成文件名的分钟部分
		int minute=cal.get(Calendar.MINUTE);
		if(minute<10)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+minute;		
		url=url+minute;
		//生成文件名的秒部分
		int second=cal.get(Calendar.SECOND);
		if(second<10)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+second;		
		url=url+second;
		//生成文件名的毫秒部分
		int millisecond=cal.get(Calendar.MILLISECOND);
		if(millisecond<10)
		{
			fileName=fileName+"0";
		}
		if(millisecond<100)
		{
			fileName=fileName+"0";
		}
		fileName=fileName+millisecond;
		url=url+millisecond;
		//生成文件的扩展名部分
		String extension=imageFileName.substring(imageFileName.indexOf(".")) ;	 //计算.的位置
		fileName=fileName+extension;
		url=url+extension;
		file=new File(fileName);
		FileUtils.copyFile(image, file);
		//获取之前照片图片路径,如果不为空,将文件删除
		String oldurl=dao.getUrl(student);
		if(oldurl!=null)
		{
			String oldfile=req.getServletContext().getRealPath("")+oldurl;
			File myfile=new File(oldfile);
			if(myfile.exists())
			{
				myfile.delete();
			}
		}
		System.out.println(fileName);
		student.setPhoto(url);  //没有照片无法执行
		}
		
		dao.update(student);
		HttpSession session=req.getSession();
		session.setAttribute("STUDENT", student);
		return "main";
	}
}

TeacherAction.java

package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import common.Pager;
import dao.TeacherDAO;
import model.Teacher;


public class TeacherAction  {
	private Teacher teacher;
	private int page;
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	private TeacherDAO dao = new TeacherDAO();
	
	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	public String main()
	{
		HttpServletRequest request= ServletActionContext.getRequest();
		//显示所有教室信息
		if(page==0)//不传页码时,默认显示第0页
		{
			page=1;
		}
		
		Pager pager =new Pager();
		dao.initpage(pager);
		//若果当前页大于总页数,就让他等于总页数
		if(page>pager.getPageCount())
		{
			page=pager.getPageCount();
		}
		if(ServletActionContext.getContext().get("ADD")!=null)
		{
			page=pager.getPageCount();
		}
		pager.setPageNo(page);
		StringBuilder str =new StringBuilder();
		List<Teacher> list=dao.getteacher(pager);//用类调用时为了少定义变量
		//判断是否有教室
		if(list.size()>0)
		{
			ActionContext ax= ServletActionContext.getContext();
			ax.put("TEACHERS", list);
			
			//构建分页导航按钮
			int btns=pager.getBtnCount();
			btns=btns/2;
			int start =page-btns;
			int end =page+btns;
			if(start<1)
			{
				start=1;
				end =start +2*btns;
			}
			
			if(end>pager.getPageCount())
			{
				start =end -2*btns;
				end=pager.getPageCount();
				
			}
			if(start<1)
			{
				start =1;
			}
			for(int i=start;i<=end;i++)
			{
				str.append("<a href='"+request.getContextPath() +"/teacher/main?page=" +i+"'>");
				if(i==page)
				{
					str.append("<font color ='red'><b>");
					str.append(i);
					str.append("</b></font>");
				}
				else
				{
					str.append(i);
				}
				
				str.append("</a>");
				str.append("  ");
			}
			str.append("<br>");
			ax.put("NAVBAR", str.toString());//保存数据
			System.out.println(str.toString());
		}
		return "teachermain";
		
	}
	
	public String update()
	{
		return updateIt();
		
	}

	private String updateIt() {
		if(teacher.getId()==0)
		{
			ServletActionContext.getContext().put("ADD", 1);
		}
		dao.update(teacher);
		return main();
	}
	
	public String modify()
	{
		return updateIt();
	}
	public String delet()
	{
		dao.deletteacher(teacher);
		return null;
		
	}
	
	public String get()
	{
		teacher= dao.get(teacher);
		HttpServletResponse response= ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		try {
			PrintWriter out =response.getWriter();
			out.print(teacher.getId()+"!"+teacher.getName()+"!"+teacher.getSex()+"!"+teacher.getPhone());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}

}

common包

HibernateUtil.java

package common;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

		private static SessionFactory sessionFactory;

		private static SessionFactory buildSessionFactory() {
			try {
				Configuration configuration = new Configuration();
				configuration.configure("hibernate.cfg.xml");

				ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
						.applySettings(configuration.getProperties()).build();

				SessionFactory sessionFactory = configuration
						.buildSessionFactory(serviceRegistry);

				return sessionFactory;
			} catch (Throwable ex) {
				throw new ExceptionInInitializerError(ex);
			}
		}

		public static SessionFactory getSessionFactory() {
			if (sessionFactory == null)
				sessionFactory = buildSessionFactory();
			return sessionFactory;
		}

		public static Session openSession() {
			return getSessionFactory().openSession();
		}

}

Pager.java

package common;

public class Pager {

	//当前页
	private int pageNo;
	//总页数
	private int pageCount;
	//每页的记录条数
	private int pageSize=3;
	//分页按钮个数
	private int btnCount=4;
	public int getPageNo() {
		return pageNo;
	}
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	public int getPageCount() {
		return pageCount;
	}
package dao;
import org.hibernate.Session;

import common.HibernateUtil;
import model.Contact;

public class ContactDAO {

	Session session;
		public void update(Contact contact)
		{
			session =HibernateUtil.openSession();
			session.beginTransaction();
			session.saveOrUpdate(contact);    //修改添加同时存在
			session.getTransaction().commit();
			session.close();
		}
	
}

public void setPageCount(int pageCount) {this.pageCount = pageCount;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) {this.pageSize = pageSize;}public int getBtnCount() {return btnCount;}public void setBtnCount(int btnCount) {this.btnCount = btnCount;}}

dao包

ContactDAO.java

package dao;
import org.hibernate.Session;

import common.HibernateUtil;
import model.Contact;

public class ContactDAO {

	Session session;
		public void update(Contact contact)
		{
			session =HibernateUtil.openSession();
			session.beginTransaction();
			session.saveOrUpdate(contact);    //修改添加同时存在
			session.getTransaction().commit();
			session.close();
		}
	
}

CourseDAO.java

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import common.HibernateUtil;
import common.Pager;
import model.Course;

public class CourseDAO {

	Session session;
	public void update(Course course)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();
		session.saveOrUpdate(course);
		session.getTransaction().commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Course> getcourse(Pager pager)//修改为pager
	{
		//所有教室的信息
		String hql=" from Course";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		//返回当前页记录(pager.getpageNo()-1当前页,pager.getPageSize()记录数)
		//意思是从第几条记录开始显示
		query.setFirstResult((pager.getPageNo()-1)*pager.getPageSize());
		//最多显示多少条
		query.setMaxResults(pager.getPageSize());
		//当前页的数据
		List<Course> list=query.list();
		
		session.close();//关闭session;
		return list;
		
	}
	
	@SuppressWarnings("unchecked")
	public void initpage(Pager pager)
	{
		String hql=" from Course";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		List<Course> list =query.list();
		//计算总页数
		pager.setPageCount(list.size()/pager.getPageSize());
		if(list.size()%pager.getPageSize()>0)
		{
			pager.setPageCount(pager.getPageCount()+1);
		}
		
		session.beginTransaction().commit();
		session.close();
	}
	
	public void deletcourse(Course course)
	{
		
		session = HibernateUtil.openSession();
		session.beginTransaction();
		session.delete(course);
		session.getTransaction().commit();
		session.close();
	}
	
	public Course get( Course course)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();
		String hql="from Course where id=:id";
		Query query =session.createQuery(hql).setProperties(course);
		Course r =(Course) query.uniqueResult();
		session.getTransaction().commit();
		session.close();
		return r;
		
	}
}
RoomDAO.java
package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import common.HibernateUtil;
import common.Pager;
import model.Course;
import model.Room;

public class RoomDAO {

	Session session;
	public void update(Room room)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();
		session.saveOrUpdate(room);
		session.getTransaction().commit();
		session.close();
	}
	//返回值 教室
	@SuppressWarnings("unchecked")
	public List<Room> getRooms(Pager pager)//修改为pager
	{
		//所有教室的信息
		String hql=" from Room";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		//返回当前页记录(pager.getpageNo()-1当前页,pager.getPageSize()记录数)
		//意思是从第几条记录开始显示
		query.setFirstResult((pager.getPageNo()-1)*pager.getPageSize());
		//最多显示多少条
		query.setMaxResults(pager.getPageSize());
		//当前页的数据
		List<Room> list=query.list();
		
		session.close();//关闭session;
		return list;
		
	}
	
	@SuppressWarnings("unchecked")
	public void initpage(Pager pager)
	{
		String hql=" from Room";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		List<Room> list =query.list();
		//计算总页数
		pager.setPageCount(list.size()/pager.getPageSize());
		if(list.size()%pager.getPageSize()>0)
		{
			pager.setPageCount(pager.getPageCount()+1);
		}
		
		session.beginTransaction().commit();
		session.close();
	}
	public void delet(Room room)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();  //开启事物
		session.delete(room);
		session.getTransaction().commit();  //提交
		//关闭session;
		session.close();
	}
	@SuppressWarnings("unchecked")
	public List<Room> getroom()
	{
		//所有教室的信息
		String hql=" from Room";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		//当前页的数据
		List<Room> list=query.list();
		//关闭session;
		session.close(); 
		return list;
		
	}
	
	public Room get(Room room)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();  //开启事物
		String hql="from Room where id=:id";
		Query query =session.createQuery(hql)
				.setProperties(room);
		Room r=(Room) query.uniqueResult();
		session.getTransaction().commit();  //提交
		session.close();
		return r;
	}
}

StudentDAO.java

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import common.HibernateUtil;
import model.Student;

public class StudentDAO {
	Session session;
	public void update(Student student)
	{
		session=HibernateUtil.openSession();  //打开session
		Transaction ts=session.beginTransaction();			  //把事物存起来
		session.saveOrUpdate(student);                  //把student 存一下 或者修改
		ts.commit();                             //提交一下
		session.close();
	}
	public Student check(Student student)  //查询  写到数据库中需要
	{
		session=HibernateUtil.openSession();  //打开session
		String hql="from Student where name=:name and pwd=:pwd";
		//Query query=session.createQuery(hql);
		//第一种办法
		/*query.setString("name",student.getName());
		query.setString("pwd",student.getPwd());*/
		//第二种办法
		//query.setProperties(student);
		Query query=session.createQuery(hql)
				.setProperties(student);
		@SuppressWarnings("unchecked")
		List<Student>list=query.list();  //获取执行完的列表
		student=null;//存到session
		if(list.size()>0)  
		{
			student=list.get(0);
		}
		return student;
	}
	
	public boolean checkpwd(Student student)
	{
		String hql="from Student where id=:id and pwd=:pwd";
		session=HibernateUtil.openSession();
		Query query=session.createQuery(hql)
				.setProperties(student);
		@SuppressWarnings("unchecked")
		List<Student>list=query.list();  //获取执行完的列表
		session.close();
		return list.size()>0?true:false;  //大于0代表找到
	}
	public String getUrl(Student student)
	{
		String hql="select photo from Student where id=:id"; //得到名字是多个
		Session session=HibernateUtil.openSession();
		Query query=session.createQuery(hql)
				.setProperties(student);
		@SuppressWarnings("unchecked")
		List<String>list=query.list();  //获取执行完的列表
		session.close();
		return list.get(0);
	}
	@SuppressWarnings("unchecked")
	public Student get(Student student)
	{
		session =HibernateUtil.openSession();
		String hql="from Student where id=:id";
		Query query=session.createQuery(hql)
				.setProperties(student);
		List<Student>list=query.list();
		student=null;
		if (list.size()>0) {
			student=list.get(0);
		}
		return student;
	}
	
}

TeacherDAO.java

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import common.HibernateUtil;
import common.Pager;
import model.Teacher;

public class TeacherDAO {

	Session session;
	public void update(Teacher teacher)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();
		session.saveOrUpdate(teacher);
		session.getTransaction().commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Teacher> getteacher(Pager pager)//修改为pager
	{
		//所有教室的信息
		String hql=" from Teacher";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		//返回当前页记录(pager.getpageNo()-1当前页,pager.getPageSize()记录数)
		//意思是从第几条记录开始显示
		query.setFirstResult((pager.getPageNo()-1)*pager.getPageSize());
		//最多显示多少条
		query.setMaxResults(pager.getPageSize());
		//当前页的数据
		List<Teacher> list=query.list();
		
		session.close();//关闭session;
		return list;
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Teacher> getteacher()//修改为pager
	{
		//所有教室的信息
		String hql=" from Teacher";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		List<Teacher> list=query.list();
		
		session.close();//关闭session;
		return list;
		
	}
	
	@SuppressWarnings("unchecked")
	public void initpage(Pager pager)
	{
		String hql=" from Teacher";
		session = HibernateUtil.openSession();
		Query query =session.createQuery(hql);
		
		List<Teacher> list =query.list();
		//计算总页数
		pager.setPageCount(list.size()/pager.getPageSize());
		if(list.size()%pager.getPageSize()>0)
		{
			pager.setPageCount(pager.getPageCount()+1);
		}
		
		session.beginTransaction().commit();
		session.close();
	}
	
	public void deletteacher(Teacher teacher)
	{
		
		session = HibernateUtil.openSession();
		session.beginTransaction();
		session.delete(teacher);
		session.getTransaction().commit();
		session.close();
	}
	
	public Teacher get( Teacher teacher)
	{
		session = HibernateUtil.openSession();
		session.beginTransaction();
		String hql="from Teacher where id=:id";
		Query query =session.createQuery(hql).setProperties(teacher);
		Teacher r =(Teacher) query.uniqueResult();
		session.getTransaction().commit();
		session.close();
		return r;
		
	}
}
package model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Contact {

	private int id;
	private String name;
	private String sex;
	private String relation;
	private String phone;
	private Student student; 
	@Id
	@GeneratedValue
	public int 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 getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getRelation() {
		return relation;
	}
	public void setRelation(String relation) {
		this.relation = relation;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	@OneToOne(mappedBy="contact")//
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
	
	
}
package model;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;

/**
 * 
 * @author Administrator
 *
 */
@Entity
public class Course {

	private int id;
	private String name;
	private String type;
	private String hours;
	private Teacher teacher;
	private Room room;
	private Set<Student> students=new HashSet<Student>();   //中间表 初始化
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getHours() {
		return hours;
	}
	public void setHours(String hours) {
		this.hours = hours;
	}
	
	@ManyToOne
	@JoinColumn(name="tid" )
	public Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	
	@ManyToOne
	@JoinColumn(name="rid" )
	public Room getRoom() {
		return room;
	}
	public void setRoom(Room room) {
		this.room = room;
	}
	
	@ManyToMany(mappedBy="courses") //多对多
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
}
Room.java
Course.java


package model;

import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Room {

	private int id;
	private String name;
	private String address;
	private Set<Course> courses;
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	@OneToMany(mappedBy="room")
	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
}
Student.java
package model;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;

@Entity
public class Student {

	
	private int id;
	private String name;
	private String pwd;
	private String phone;
	private String grade;
	private String photo;
	private String sex;
	private Contact contact;
	private Set<Course> courses =new HashSet<Course>();   //中间表
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	@OneToOne
	@JoinColumn(name="cid",unique=true)  //unique=true 保证唯一 一对一
	public Contact getContact() {
		return contact;
	}
	public void setContact(Contact contact) {
		this.contact = contact;
	}
	@ManyToMany
	@JoinTable(
		    name="student_course",    //中间表
		    joinColumns=@JoinColumn(name="sid"),    //字段名
		    inverseJoinColumns=@JoinColumn(name="cid")	//字段名	
	) 

	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
	
}
Teacher.java
package model;

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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;

@Entity
public class Student {

	
	private int id;
	private String name;
	private String pwd;
	private String phone;
	private String grade;
	private String photo;
	private String sex;
	private Contact contact;
	private Set<Course> courses =new HashSet<Course>();   //中间表
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	@OneToOne
	@JoinColumn(name="cid",unique=true)  //unique=true 保证唯一 一对一
	public Contact getContact() {
		return contact;
	}
	public void setContact(Contact contact) {
		this.contact = contact;
	}
	@ManyToMany
	@JoinTable(
		    name="student_course",    //中间表
		    joinColumns=@JoinColumn(name="sid"),    //字段名
		    inverseJoinColumns=@JoinColumn(name="cid")	//字段名	
	) 

	public Set<Course> getCourses() {
		return courses;
	}
	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}
	
}

test包

MyApp.java

package test;

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

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import common.HibernateUtil;
import model.Course;
import model.Room;
import model.Student;
import model.Teacher;

public class MyApp {
     @Test
     public void Mytest()
 	{
 		Course cou =new Course();
 		cou.setName("数333学");
 		cou.setType("代33数");
 		cou.setHours("3330");
 		
 		Teacher tea =new Teacher();
 		tea.setName("张3");
 		tea.setPhone("13234567890");
 		tea.setSex("男3");
 		
 		Room room=new Room();
 		room.setName("第3一教室");
 		room.setAddress("3a205");
 		
 		cou.setTeacher(tea);
 		cou.setRoom(room);
 		
 		Session session= HibernateUtil.openSession();
 		session.beginTransaction();
 		session.save(room);
 		session.save(tea);
 		session.save(cou);
 		
 		session.getTransaction().commit();
 		session.close();
 	}
     @Test
 	public void teatManyToMany()
 	{
    	Session session=HibernateUtil.openSession();
  		session.beginTransaction();
 		Student student =new Student();
 		student.setId(39);  //39号学生
 		
 		Course course1=new Course();
 		course1.setId(2);   //2号课程
 		Course course2 =new Course();
 		course2.setId(3);   //3号课程
 		
// 		Set<Course> courses=new HashSet<Course>();
// 		courses.add(course1);
// 		courses.add(course2);
// 		方法一
// 		student.setCourses(courses);
 		
 		student.getCourses().add(course1);  //在student 必须初始化 才可以 	
 		//private Set<Course> courses =new HashSet<Course>();   //中间表
 		student.getCourses().add(course2);
 		
 		
 		session.saveOrUpdate(student);
 		session.getTransaction().commit();
 		session.close();
 		
 	}
}
TestMapping.java
package test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import common.HibernateUtil;
import model.Student;

public class TestMapping {

	  @Test
	     public void myTest()
	     {
	    	 Session session = HibernateUtil.openSession();
	    	 Student s=new Student();
	    	 s.setName("Mike");
	    	 s.setPhone("18724737098");
	    	 s.setPwd("12345678");
	    	 s.setGrade("Grade Two");
	    	 Transaction tx=session.beginTransaction();
	    	 session.save(s);
	    	 tx.commit();
	     }
}

===============================上面是后端代码=========================

contact.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="contact" namespace="/contact" extends="all">
    <action name="*" class="action.ContactAction" method="{1}">
    </action>
    </package>
</struts>

course.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="course" namespace="/course" extends="all">
    <action name="*" class="action.CourseAction" method="{1}">
    <result name="coursemain">/course.jsp</result>
    <result name="initmain">/init.jsp</result>
     <result name="choosemain">/choose.jsp</result>
    </action>
    </package>
</struts>

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-configuration>
	<session-factory>
			<!-- Database connection settings -->
		       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/curricula</property> 
				
		<property name="connection.username">root</property> 
				
		<property name="connection.password">12345678</property>  
				
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 		
		<property name="show_sql">true</property>
 
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
		<mapping class="model.Student"/>
		<mapping class="model.Contact"/>
		<mapping class="model.Room"/>
		<mapping class="model.Teacher"/>
		<mapping class="model.Course"/>
	</session-factory>
</hibernate-configuration>
room.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="room" namespace="/room" extends="all">
    <action name="*" class="action.RoomAction" method="{1}">
    <result name="roommain">/room.jsp</result>
    </action>
    </package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <include file="student.xml"></include>
    <include file="contact.xml"></include>
    <include file="room.xml"></include>
    <include file="teacher.xml"></include>
    <include file="course.xml"></include>
    <package name="all" namespace="/" extends="struts-default">
	  <interceptors>   
		      <interceptor-stack name="myStack">   
		       <interceptor-ref name="defaultStack"/>    
		      <interceptor-ref name="tokenSession">
		  <!--     token 转走  tokenSession 不转走 -->
		           <param name="includeMethods">update</param> 
		          <!--  只拦截   update方法 -->
		      </interceptor-ref>        
		      </interceptor-stack>   
		   <!--    上面是配置拦截器   -->
		  </interceptors>  
		    <default-interceptor-ref name="myStack"/>
    <global-results >
    <result name="main">/main.jsp</result>
   <result name="invalid.token">/error.jsp</result>
    <!-- 发生错误 转到 error -->
    </global-results>
    </package>
</struts>
Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="model">
<class name="Student" table="student">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name"></property>
        <property name="pwd" column="pwd" type="string" length="50"></property>
         <property name="phone" length="50"></property>
        <property name="photo" length="150"></property>
    </class>
</hibernate-mapping>
student.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>
    <constant name="struts.devMode" value="true" />
    <package name="student" namespace="/student" extends="all">
    <action name="*" class="action.StudentAction" method="{1}">
    	<result name="login" >/login.jsp</result>
    </action>
    </package>
</struts>
teacher.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="teacher" namespace="/teacher" extends="all">
    <action name="*" class="action.TeacherAction" method="{1}">
    <result name="teachermain">/teacher.jsp</result>
    </action>
    </package>
</struts>

================================以上为配置文件========================

admin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>后台管理</title>
</head>
<body>
后台管理
<br/>
<br/>
<a href="${pageContext.request.contextPath}/room/main">教室管理</a> | 
<a href="${pageContext.request.contextPath}/teacher/main">教师管理</a> |
<a href="${pageContext.request.contextPath}/course/main">课程管理</a> |
<a href="${pageContext.request.contextPath}/course/imain">课程初始化</a> |
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>


</html>
choose.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/demo/demo.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stytel.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function(){
	$(".selsetit").each(function(i, e) {
        $.post("${pageContext.request.contextPath}/course/checkesSelect"
		,{"course.id":e.lang},function(data){
			eval("e.checked=" +data);  //把一个字符串变成一个命令 
		});
    });
	$(".selsetit").click(function(){
		 $.post("${pageContext.request.contextPath}/course/checkit"
		,{"course.id":this.lang});
	});
});
</script>
</head>
<body>
<div id="showSelected" class="easyui-window" title="修改课程信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:300px;padding:10px;">
</div>
<br/>
<s:if test="#COURSE!=null">
<table class="bordered">
<tr><th>序号</th><th>课程名称</th><th>课程类型</th><th>课程学时</th><th>授课老师</th><th>上课教室</th><th>选择</th></tr>
<s:iterator value="#COURSE" id="mycourse" status="st">
<tr><td>${st.index+1 }</td><td>${mycourse.name }</td>
<td>${mycourse.type }</td><td>${mycourse.hours }</td>
<td >${mycourse.teacher.name }</td>
<td >${mycourse.room.name }</td>
<td ><input type="checkbox" class="selsetit" lang="${mycourse.id }"></td>
</tr>
</s:iterator>
</table>
${NAVBAR }
<br>
<br>
</s:if>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
contact.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s" %>
<!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>
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
	if($("[name='contact.sex']:checked").length==0)
	{
		$("[name='contact.sex']:eq(0)").attr("checked",true);
	}
});
</script>
</head>
<body>
<!-- session过期判断 -->
<s:if test="#session.STUDENT==null">
	<jsp:forward page="login.jsp"></jsp:forward>
</s:if>
<form action="${pageContext.request.contextPath}/contact/modify" method="post">
<input type="hidden" name="contact.id" value="${STUDENT.contact.id}" >
<table>
<tr><td>姓名:</td><td><input type="text" name="contact.name" value="${STUDENT.contact.name}"/></td></tr>
<tr><td>性别:</td>
<s:radio list="#{'男':'男','女':'女'}" name="contact.sex" value="#session.STUDENT.contact.sex"/>
</tr>
<tr><td>关系:</td><td><input type="text" name="contact.relation" value="${STUDENT.contact.relation }"/></td></tr>
<tr><td>电话:</td><td><input type="text" name="contact.phone" value="${STUDENT.contact.phone }"/></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>

</html>
course.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/demo/demo.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stytel.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function(){
	$("[type='submit']").click(function(){
		if($("[name='course.name']").val().length==0)
		{
			$("[name='course.name']").focus();
			$("#msg").html("请输入课程名称!");
			return false;
		}
		if($("[name='course.type']").val().length==0)
		{
			$("[name='course.type']").focus();
			$("#msg").html("请输入课程类型!");
			return false;
		}
		if($("[name='course.hours']").val().length==0)
		{
			$("[name='course.hours']").focus();
			$("#msg").html("请输入课程学时!");
			return false;
		}
		
	});
	
	$(".delet").click(function(){
		var flag=confirm("你真的要删除课程的信息吗?");
		if(!flag)
			{
				return;
			}
		$.post("${pageContext.request.contextPath}/course/delet",{"course.id":this.lang},function(data){
			location.href="${pageContext.request.contextPath}/course/main?page="+$("#page").val();
		});
	});
	$(".modify").click(function(){
		$.post("${pageContext.request.contextPath}/course/get",{"course.id":this.lang},function(data){
			var msg=data.split("!");
			$("#w [name='course.id']").val(msg[0]);
			$("#w [name='course.name']").val(msg[1]);
			$("#w [name='course.type']").val(msg[2]);
			$("#w [name='course.hours']").val(msg[3]);
		});
		$('#w').window('open');
	});
	$("#save").click(function(){
		$.post("${pageContext.request.contextPath}/course/modify",
		{"course.id":$("#w [name='course.id']").val(),
		"course.name":$("#w [name='course.name']").val(),
		"course.type":$("#w [name='course.type']").val(),
		"course.hours":$("#w [name='course.hours']").val(),
		},function(){
			$('#w').window('close');
			location.href="${pageContext.request.contextPath}/course/main?page="+$("#page").val();
		});
	});
});
</script>
</head>
<body>
<input type="hidden" id="page" value="${page }">
<div id="w" class="easyui-window" title="修改课程信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:200px;padding:10px;">
	<input type="hidden" name="course.id">
	课程名称:<input type="text" name="course.name"> <br/>
	课程类型:<input type="text" name="course.type"><br/>
	课程学时:<input type="text" name="course.hours"><br/>
	<input type="button" id="save" value="保存">
	</div>
<form method="post" action="${pageContext.request.contextPath}/course/update">
	课程名称:<input type="text" name="course.name"> <br/>
	课程类型:<input type="text" name="course.type"><br/>
	课程学时:<input type="text" name="course.hours"><br/>
	<s:token></s:token>
	<input type="submit"  value="提交">
</form>
<div id="msg"></div>
<br/>
<s:if test="#COURSE!=null">
<table class="bordered">
<tr><th>序号</th><th>课程名称</th><th>课程类型</th><th>课程学时</th><th>删除</th><th>修改</th></tr>
<s:iterator value="#COURSE" id="mycourse" status="st">
<tr><td>${st.index+1 }</td><td>${mycourse.name }</td>
<td>${mycourse.type }</td><td>${mycourse.hours }</td>
<td><input type="button" class="delet" lang="${mycourse.id}" value="删除"></td>
<td><input type="button" class="modify" lang="${mycourse.id}" value="修改"></td></tr>
</s:iterator>
</table>
${NAVBAR }
<br>
<br>
</s:if>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
出错!!!
</body>
</html>
init.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/demo/demo.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stytel.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function(){
	
	//-------------------------老师设置---------------------//
	
	var cell="";
	//在点击老师单元格时触发此事件
	$(".teachercell").click(function(){
		cell=this;
		//把course id接受到,存到掩藏变量中
		
		$("#tw [name='course.id']").val(this.lang);   //把course id 设置进去了
		//根据course id得到course name,显示在窗口中
		$.post("${pageContext.request.contextPath}/course/get",
		{"course.id":this.lang}, function(data){
			
			$("#courseName").html(data.split("!")[1]);
		});
		$('#tw').window('open');
	});
	//在选择老师的时候触发
	$(".selectteacher").click(function(){
		
		$("#tw [name='teacher.id']").val(this.lang); //把teacher id 设置进去了
	});
	//保存设置的时候触发
	$("#saveteacher").click(function(){
		$.ajaxSetup({async:false}); //
		var teacherName="";
		//获得老师的名字
		$.post("${pageContext.request.contextPath}/teacher/get",
				{"teacher.id":$("#tw [name='teacher.id']").val()},
			function(data){
					
					teacherName=data.split("!")[1];
					
				});
		//为课程设置老师,把老师的姓名写到列表中老师单元格
		
		$.post("${pageContext.request.contextPath}/course/updateTeacher",
				{"course.id":$("#tw [name='course.id']").val(),"teacher.id":$("#tw [name='teacher.id']").val()},
			function(data){
					cell.innerHTML=teacherName;  //设置好的教师名字设置到课程列表中 
					$('#tw').window('close');
				});
	});
	
	//-------------------------教室设置------------------------------------------
	
	$(".roomcell").click(function(){
		cell=this;
		//把course id接受到,存到掩藏变量中
		
		$("#rw [name='course.id']").val(this.lang);
		//根据course id得到course name,显示在窗口中
		$.post("${pageContext.request.contextPath}/course/get",
		{"course.id":this.lang}, function(data){
			
			$("#courseNameroom").html(data.split("!")[1]);
		});
		$('#rw').window('open');
	});
	//在选择教室的时候触发
	$(".selectroom").click(function(){
		
		$("#rw [name='room.id']").val(this.lang);
	});
	//保存设置的时候触发
	$("#saveRoom").click(function(){
		$.ajaxSetup({async:false});//改为同步 
		var roomName="";
		//获得教室的名字
		$.post("${pageContext.request.contextPath}/room/get",
				{"room.id":$("#rw [name='room.id']").val()},
			function(data){
					
					roomName=data.split("!")[1];
					
				});
//为课程设置教室,把教室的名字写到列表中教室单元格
		
		$.post("${pageContext.request.contextPath}/course/updateRoom",
				{"course.id":$("#rw [name='course.id']").val(),"room.id":$("#rw [name='room.id']").val()},
			function(data){
					cell.innerHTML=roomName;
					$('#rw').window('close');
				});
	});
});
</script>
</head>
<body>
<input type="hidden" id="page" value="${page}">
<div id="tw" class="easyui-window" title="修改课程信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:300px;padding:10px;">
<input type="hidden" name="course.id">
<input type="hidden" name="teacher.id">
<input type="hidden" name="teacher.name">
<br>
你正在为课程[<span id="courseName"></span>]设置教师...
<br>	
<table class="bordered">
<tr><th>选择</th><th>序号</th><th>姓名</th><th>性别</th><th>电话号码</th></tr>
<s:iterator value="#TEACHERS" id="myteachers" status="st">
<tr><td><input type="radio" name="teacher" class="selectteacher" lang="${myteachers.id }"></td>
<td>${st.index+1 }</td>
<td>${myteachers.name }</td>
<td>${myteachers.sex }</td>
<td>${myteachers.phone }</td></tr>
</s:iterator>
</table>
<br>
<input type="button" id="saveteacher" value="保存教师信息">
</div>

<div id="rw" class="easyui-window" title="修改课程信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:300px;padding:10px;">
<input type="hidden" name="course.id">
<input type="hidden" name="room.id">
<br>
你正在为[<span id="courseNameroom"></span>]设置教室...
<br>
<table class="bordered">
<tr><th>选择</th><th>序号</th><th>名称</th><th>位置</th></tr>
<s:iterator value="#ROOMS" id="myroom" status="st">
<tr><td><input type="radio" name="room" class="selectroom" lang="${myroom.id }"></td>
<td>${st.index+1 }</td>
<td>${myroom.name }</td>
<td>${myroom.address }</td></tr>
</s:iterator>
</table>
<br>
<input type="button" id="saveRoom" value="保存教室信息">
</div>
<br/>
<s:if test="#COURSE!=null">
<table class="bordered">
<tr><th>序号</th><th>课程名称</th><th>课程类型</th><th>课程学时</th><th>授课老师</th><th>上课教室</th></tr>
<s:iterator value="#COURSE" id="mycourse" status="st">
<tr><td>${st.index+1 }</td><td>${mycourse.name }</td>
<td>${mycourse.type }</td><td>${mycourse.hours }</td>
<td class="teachercell" lang="${mycourse.id }">${mycourse.teacher.name }</td>
<td class="roomcell" lang="${mycourse.id }">${mycourse.room.name }</td></tr>
</s:iterator>
</table>
${NAVBAR }
<br>
<br>
</s:if>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
登录
<br/>
<br/>
<form action="${pageContext.request.contextPath}/student/check" method="post">
<table>
<tr><td>用户名:</td><td><input type="text" name="student.name"/></td></tr>
<tr><td>密码:</td><td><input type="password" name="student.pwd"/></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>

</html>
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
主页面
<br/>
<s:if test="#session.STUDENT==null">
未登录
</s:if>
<s:else>
当前登录用户名:${STUDENT.name},<a href="${pageContext.request.contextPath}/modify.jsp">修改个人信息</a>
<a href="${pageContext.request.contextPath}/contact.jsp">紧急联系人信息</a>
</s:else>
<br/>
<a href="${pageContext.request.contextPath}/admin.jsp">进入后台管理</a>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/register.jsp">注册</a>  
<a href="${pageContext.request.contextPath}/login.jsp">登录</a> 
<a href="${pageContext.request.contextPath}/course/cmain">选课</a>
</body>

</html>
modify.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
       <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<style type="text/css">
#pic
{
	width:300px;
}
</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/upload/uploadPreview.min.js"></script>
<script type="text/javascript">
$(function(){
	/* $("[name='image']").change(function(){
		$("#pic").attr("src", $(this).val());
	}); */
	 new uploadPreview({ UpBtn: "image", DivShow: "mypic", ImgShow: "pic",Width:"300",Height:"200"});
	$("[type='submit']").click(function(){
		//验证旧密码是否正确
		//提交方式
		var myurl="${pageContext.request.contextPath}/student/checkpwd";
		var flag=true;
		$.ajax({
			type:"POST",
			async:false,   //同步 默认异步
			url:myurl,
			data:{"student.id":"${STUDENT.id}","student.pwd":$("#oldPwd").val()},
			//请求完要做的事
			success: function(data)
			{
				if(data=="0")
				{   
					$("#msg").html("旧密码输入错误!");
					flag=false;	
				}
			}
		});
		if(!flag)
		{
	    	return flag;

		}
		//两次密码不一致 或者没有输入
		if($.trim($("[name='student.pwd']").val()).length==0)
		{
			$("#msg").html("请输入新密码!");
			return false;
		}
		var p1=$("[name='student.pwd']").val();   //旧密码
		var p2=$("#pwd1").val();
		if(p1!=p2)
		{
			$("#msg").html("两次密码输入不一致!");
			return false;
		}
		return true;
	});
});
</script>
</head>
<body>
修改
<br/>
<br/>
<s:if test="#session.STUDENT==null">
	<jsp:forward page="${pageContext.request.contextPath}/login.jsp"></jsp:forward>
</s:if>
<table width="1013"><tr><td width="351">
<form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/student/modify">
<table>
<tr><td>用户名:</td><td><input type="text" name="student.name" value="${STUDENT.name}"/>
<input type="hidden" name="student.id" value="${STUDENT.id}">
</td></tr>     
<tr><td>旧密码:</td><td><input type="password" id="oldPwd" /></td></tr>
<tr><td>新密码:</td><td><input type="password" name="student.pwd" value="${STUDENT.pwd}"/></td></tr>
<tr>
  <td>重复新密码:</td>
  <td><input type="password" id="pwd1" value="${STUDENT.pwd}"/></td>
</tr>
<tr>
  <td>性别</td>
  <td><s:radio list="#{'男':'男','女':'女'}" name="student.sex" value="#session.STUDENT.sex"/></td>
</tr>
<tr>
  <td>年级:</td>
  <td><s:select name="student.grade" list="#{'一年级':'一年级','二年级':'二年级','三年级':'三年级','四年级':'四年级'}" value="#session.STUDENT.grade"></s:select></td>
</tr>
<tr><td>上传照片:</td><td><input type="file" name="image"  id="image"/>
<input type="hidden" name="student.photo" value="${STUDENT.photo}">
</td></tr>
<tr><td>电话号码:</td><td><input type="text" name="student.phone" value="${STUDENT.phone}"/></td></tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
</td><td width="725">
<div id="mypic">
<s:if test="#session.STUDENT.photo==null">
<img src="images/22.jpg" id="pic" />
</s:if>
<s:else>
<img src="${STUDENT.photo}" id="pic" />
</s:else>
</div>
</td></tr></table>
</body>
<br/>
<div id="msg">1</div>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</html>
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
       <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
注册
<br/>
<br/>
<form method="post" action="${pageContext.request.contextPath}/student/add">
<table>
<tr><td>用户名:</td><td><input type="text" name="student.name" value="${STUDENT.name}"/></td></tr>
<tr><td>密码:</td><td><input type="password" name="student.pwd" /></td></tr>
<tr>
  <td>重复密码:</td>
  <td><input type="password" id="pwd1"/></td>
</tr>
<tr>
  <td>性别</td>
  <td><input type="radio" value="男" checked name="student.sex">
    男
    <input type="radio"  value="女" name="student.sex">
    女</td>
</tr>
<tr>
  <td>年级:</td>
  <td><label for="select"></label>
    <select name="student.grade">
      <option value="一年级">一年级</option>
      <option value="二年级">二年级</option>
      <option value="三年级">三年级</option>
      <option value="四年级">四年级</option>
      </select></td>
</tr>
<tr><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
<br/>
<br/>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
room.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/demo/demo.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stytel.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function(){
	$("[type='submit']").click(function(){
		if($("[name='room.name']").val().length==0)
		{
			$("[name='room.name']").focus();
			$("#msg").html("请输入教室名称!");
			return false;
		}
		if($("[name='room.address']").val().length==0)
		{
			$("[name='room.address']").focus();
			$("#msg").html("请输入教室位置!");
			return false;
		}
		
	});
	
	$(".delet").click(function(){
		var flag=confirm("你真的要删除教室的信息吗?");
		if(!flag)
			{
				return;
			}
		$.post("${pageContext.request.contextPath}/room/delet",{"room.id":this.lang},function(data){
			location.href="${pageContext.request.contextPath}/room/main?page="+$("#page").val();
		});
	});
	$(".modify").click(function(){
		//修改教室信息 
		$.post("${pageContext.request.contextPath}/room/get",{"room.id":this.lang},function(data){
			var msg=data.split("!");
			$("#w [name='room.id']").val(msg[0]);
			$("#w [name='room.name']").val(msg[1]);
			$("#w [name='room.address']").val(msg[2]);
	
		});
		$('#w').window('open');
	});
	$("#save").click(function(){
		$.post("${pageContext.request.contextPath}/room/modify",
		{"room.id":$("#w [name='room.id']").val(),
		"room.name":$("#w [name='room.name']").val(),
		"room.address":$("#w [name='room.address']").val(),
		},function(){
			$('#w').window('close');
		//	location.href="${pageContext.request.contextPath}/room/main?page="+$("#page").val()";
			location.href="${pageContext.request.contextPath}/room/main?page="+$("#page").val();
		});
	}); 
});
</script>
</head>
<body>
<input type="hidden" id="page" value="${page }">
 <div id="w" class="easyui-window" title="修改教室信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:200px;padding:10px;">
	<input type="hidden" name="room.id">
	教室名称:<input type="text" name="room.name"> <br/>
	教室位置:<input type="text" name="room.address"><br/>
	<input type="button" id="save" value="保存">
	</div>
<form method="post" action="${pageContext.request.contextPath}/room/update">
	教室名称:<input type="text" name="room.name"> <br/>
	教室位置:<input type="text" name="room.address"><br/>
	<s:token></s:token>
	<input type="submit" value="提交">
</form>
<div id="msg"></div>
<br/>
<s:if test="#ROOMS!=null">
<table class="bordered">
<tr><th>序号</th><th>教室名称</th><th>教室位置</th><th>删除</th><th>修改</th></tr>
<s:iterator value="#ROOMS" id="myroom" status="st">
<tr><td>${st.index+1 }</td><td>${myroom.name }</td><td>${myroom.address }</td>
<td><input type="button" class="delet" lang="${myroom.id}" value="删除"></td>
<td><input type="button" class="modify" lang="${myroom.id}" value="修改"></td></tr>
</s:iterator>
</table>
${NAVBAR}
<br>
<br>
</s:if>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
teacher.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<!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>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.3/demo/demo.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stytel.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/jsilb/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(function(){
	$("[type='submit']").click(function(){
		if($("[name='teacher.name']").val().length==0)
		{
			$("[name='teacher.name']").focus();
			$("#msg").html("请输入教师名称!");
			return false;
		}
		if($("[name='teacher.sex']").val().length==0)
		{
			$("[name='teacher.sex']").focus();
			$("#msg").html("请输入教师性别!");
			return false;
		}
		if($("[name='teacher.phone']").val().length==0)
		{
			$("[name='teacher.phone']").focus();
			$("#msg").html("请输入教师电话!");
			return false;
		}
		
	});
	
	$(".delet").click(function(){
		var flag=confirm("你真的要删除教师的信息吗?");
		if(!flag)
			{
				return;
			}
		$.post("${pageContext.request.contextPath}/teacher/delet",{"teacher.id":this.lang},function(data){
			location.href="${pageContext.request.contextPath}/teacher/main?page="+$("#page").val();
		});
	});
	$(".modify").click(function(){
		$.post("${pageContext.request.contextPath}/teacher/get",{"teacher.id":this.lang},function(data){
			var msg=data.split("!");
			$("#w [name='teacher.id']").val(msg[0]);
			$("#w [name='teacher.name']").val(msg[1]);
			$("#w [name='teacher.sex']").val(msg[2]);
			$("#w [name='teacher.phone']").val(msg[3]);
		});
		$('#w').window('open');
	});
	$("#save").click(function(){
		$.post("${pageContext.request.contextPath}/teacher/modify",
		{"teacher.id":$("#w [name='teacher.id']").val(),
		"teacher.name":$("#w [name='teacher.name']").val(),
		"teacher.sex":$("#w [name='teacher.sex']").val(),
		"teacher.phone":$("#w [name='teacher.phone']").val(),
		},function(){
			$('#w').window('close');
			location.href="${pageContext.request.contextPath}/teacher/main?page="+$("#page").val();
		});
	});
});
</script>
</head>
<body>
<input type="hidden" id="page" value="${page }">
<div id="w" class="easyui-window" title="修改教师信息" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:200px;padding:10px;">
	<input type="hidden" name="teacher.id">
	教师姓名:<input type="text" name="teacher.name"> <br/>
	教师性别:<input type="text" name="teacher.sex"><br/>
	教师电话:<input type="text" name="teacher.phone"><br/>
	<input type="button" id="save" value="保存">
	</div>
<form method="post" action="${pageContext.request.contextPath}/teacher/update">
	教师姓名:<input type="text" name="teacher.name"> <br/>
	教师性别:<input type="text" name="teacher.sex"><br/>
	教师电话:<input type="text" name="teacher.phone"><br/>
	<s:token></s:token>
	<input type="submit" value="提交">
</form>
<div id="msg"></div>
<br/>
<s:if test="#TEACHERS!=null">
<table class="bordered">
<tr><th>序号</th><th>教师姓名</th><th>教师性别</th><th>教师电话</th><th>删除</th><th>修改</th></tr>
<s:iterator value="#TEACHERS" id="myteacher" status="st">
<tr><td>${st.index+1 }</td><td>${myteacher.name }</td>
<td>${myteacher.sex }</td><td>${myteacher.phone }</td>
<td><input type="button" class="delet" lang="${myteacher.id}" value="删除"></td>
<td><input type="button" class="modify" lang="${myteacher.id}" value="修改"></td></tr>
</s:iterator>
</table>
${NAVBAR }
<br>
<br>
</s:if>
<a href="${pageContext.request.contextPath}/main.jsp">返回主页</a>
</body>
</html>
test.jsp
<%@page import="common.HibernateUtil"%>
<%@ 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>
<%
	out.print(HibernateUtil.openSession());
%>
</body>
</html>
===============================以上为jsp页面=================================























评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值