自己做了一个基于SSM框架的小项目,跟大家分享一下..
首先,你需要开发工具netbeans或者eclipse一枚,我习惯用netbeans,这个随意,mysql数据库,
此为前提条件,因为是小项目,所以需求分析和用例图暂免了吧,有兴趣可以画。下面正式开始
先看一下大概的项目分层
看一眼jar包及JSP页面
我习惯先于数据库下手,然后映射数据库和pojo类,然后配置文件,然后dao->service层,控制器和jsp页面看需求
1)创建一个 student_clazz表,也就是学生-教室-老师表,涉及表与表之间的关系,老师与学生之间为多对多的关系,即一个学生有多个老师,化学啦生物啦,一个老师也有很多学生;教室与学生之间为一对多的关系,即一间教室有多位学生(假定在这个教室的这些学生只在这一个教室上课),人物关系介绍完毕~
至于主外键,为数据库基础不再赘述
CREATE DATABASE student_clazz
USE student_clazz
CREATE TABLE Clazz(
C_Id INT PRIMARY KEY NOT NULL,
C_Address VARCHAR(20)
);
INSERT INTO Clazz VALUES(1,'博知');
INSERT INTO Clazz VALUES(2,'静思');
INSERT INTO Clazz VALUES(3,'博文');
INSERT INTO Clazz VALUES(4,'博学');
CREATE TABLE Student(
S_Id INT PRIMARY KEY NOT NULL,
S_Name VARCHAR(20),
S_Gender VARCHAR(20),
S_Age VARCHAR(20),
clazz_id INT,
FOREIGN KEY (clazz_id) REFERENCES Clazz(C_Id)
);
INSERT INTO Student VALUES(10111,'anna','女','18',2);
INSERT INTO Student VALUES(10222,'juin','男','12',1);
INSERT INTO Student VALUES(10333,'edwina','女','11',1);
INSERT INTO Student VALUES(10444,'david','男','14',2);
CREATE TABLE Teacher(
T_Id INT PRIMARY KEY NOT NULL,
T_Name VARCHAR(20) NOT NULL,
T_Type VARCHAR(20) NOT NULL,
T_Gender VARCHAR(20) NOT NULL,
T_Age VARCHAR(20) NOT NULL,
T_Mobile INT
);
INSERT INTO Teacher VALUES(2201,'里番番','数学','女','21',279376);
INSERT INTO Teacher VALUES(22002,'大卫','语文','男','22',279326);
INSERT INTO Teacher VALUES(22003,'卡瑟琳','英语','女','23',279326);
INSERT INTO Teacher VALUES(22004,'鲁迅','NIIT','男','24',279326);
CREATE TABLE ItemOne(
student_id INT,
teacher_id INT,
PRIMARY KEY(student_id,teacher_id),
FOREIGN KEY(student_id) REFERENCES Student(S_Id),
FOREIGN KEY(teacher_id) REFERENCES Teacher(T_Id)
);
INSERT INTO ItemOne VALUES(20111,22003);
INSERT INTO ItemOne VALUES(20111,2201);
INSERT INTO ItemOne VALUES(20111,22002);
INSERT INTO ItemOne VALUES(30332,22004);
INSERT INTO ItemOne VALUES(30332,22002);
INSERT INTO ItemOne VALUES(20221,22003);
INSERT INTO ItemOne VALUES(20221,22004);
2)再做pojo类和数据库的映射
先建三个pojo类,有人问为什么要继承Serializable,其实我们在自己电脑上做程序的时候可以不用写,
它可以把对象转换成字节流在网络上传输,如果你不写自然没法传输,那程序也就没法使用
然后挨个写映射文件,这个对数据库的熟练还是有点要求的,增删改查相关操作都写在映射文件里,
association是用来映射一对一的关系及多对一的关系,collection用来映射一对多和多对多的关系,具体
方法如下
(和hibernate的区别参考上一篇博文。这些增删改查的语句的引用都在dao包的实现类里,通过sqlSession
提供的方法具体操作。)
1>Clazz
public class Clazz implements Serializable {
private int clazzId;
private String clazzAddress;
private List students;
public int getClazzId() {
return clazzId;
}
public void setClazzId(int clazzId) {
this.clazzId = clazzId;
}
public String getClazzAddress() {
return clazzAddress;
}
public void setClazzAddress(String clazzAddress) {
this.clazzAddress = clazzAddress;
}
public List getStudents() {
return students;
}
public void setStudents(List students) {
this.students = students;
}
@Override
public String toString() {
return "Clazz{" + "clazzId=" + clazzId + ", clazzAddress=" + clazzAddress + ", students=" + students + '}';
}
}
,与它匹配的映射文件
public class Student implements Serializable{
private int stuId;
private String stuName;
private String stuGender;
private String stuAge;
private Clazz clazz;
private List teachers;
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuGender() {
return stuGender;
}
public void setStuGender(String stuGender) {
this.stuGender = stuGender;
}
public String getStuAge() {
return stuAge;
}
public void setStuAge(String stuAge) {
this.stuAge = stuAge;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
public List getTeachers() {
return teachers;
}
public void setTeachers(List teachers) {
this.teachers = teachers;
}
@Override
public String toString() {
return "Student{" + "stuId=" + stuId + ", stuName=" + stuName + ", stuGender=" + stuGender + ", stuAge=" + stuAge + ", clazz=" + clazz + ", teachers=" + teachers + '}';
}
}
,Student的映射文件为
INSERT INTO Student(S_Id,S_Name,S_Gender,S_Age,clazz_id) VALUES (#{stuId},#{stuName},#{stuGender},#{stuAge},#{clazz.clazzId});
update Student set
S_Name=#{stuName},
S_Gender=#{stuGender},
S_Age=#{stuAge},
clazz_id=#{clazz.clazzId}
where S_Id = #{stuId}
delete from Student where S_Id = #{stuId}
3>Teacher
public class Teacher implements Serializable {
private int teacherId;
private String teacherName;
private String teacherType;
private String teacherGender;
private String teacherAge;
private int teacherMobile;
private List students;
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getTeacherType() {
return teacherType;
}
public void setTeacherType(String teacherType) {
this.teacherType = teacherType;
}
public String getTeacherGender() {
return teacherGender;
}
public void setTeacherGender(String teacherGender) {
this.teacherGender = teacherGender;
}
public String getTeacherAge() {
return teacherAge;
}
public void setTeacherAge(String teacherAge) {
this.teacherAge = teacherAge;
}
public int getTeacherMobile() {
return teacherMobile;
}
public void setTeacherMobile(int teacherMobile) {
this.teacherMobile = teacherMobile;
}
public List getStudents() {
return students;
}
public void setStudents(List students) {
this.students = students;
}
}
,映射文件为
INSERT INTO Student(S_Id,S_Name,S_Gender,S_Age,clazz_id) VALUES (#{stuId},#{stuName},#{stuGender},#{stuAge},#{clazz.clazzId});
update Student set
S_Name=#{stuName},
S_Gender=#{stuGender},
S_Age=#{stuAge},
clazz_id=#{clazz.clazzId}
where S_Id = #{stuId}
delete from Student where S_Id = #{stuId}
配置文件分为Spring-mybatis配置文件和Spring MVC配置文件
Spring-mybatis配置文件的作用就是作为持久层框架起一个水渠的作用。
Spring MVC配置文件作为请求分发器用来分发请求到制定的控制器
contextConfigLocation
/WEB-INF/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
1
dispatcher
*.do
30
index.jsp
可以自己补上。
@Repository用于标注数据访问组件,即DAO组件
statement为mapper文件中的具体的sql语句
@Repository
public class StudentDao {
@Autowired
private SqlSessionFactory sqlSessionFactory;
public List studentList(int clazzId){
String statement="com.qdu.mapping.StudentMapper.selectStudentByClazzId";
return sqlSessionFactory.openSession().selectList(statement, clazzId);
}
public List selectTeacherByStudentId(int stuId){
String statement = "com.qdu.mapping.TeacherMapper.selectTeacherByStudentId";
return sqlSessionFactory.openSession().selectList(statement, stuId);
}
public Student selectStudentById(int stuId) {
String statement = "com.qdu.mapping.StudentMapper.selectStudentById";
System.out.println(sqlSessionFactory);
return sqlSessionFactory.openSession().selectOne(statement, stuId);
}
public Clazz selectClazzById(int clazzId) {
String statement = "com.qdu.mapping.ClazzMapper.selectClazzById";
return sqlSessionFactory.openSession().selectOne(statement, clazzId);
}
public void insertStudent(Student student){
String statement="com.qdu.mapping.StudentMapper.insertStudent";
sqlSessionFactory.openSession().insert(statement, student);
}
public void updateStudent(Student student){
String statement="com.qdu.mapping.StudentMapper.updateStudent";
sqlSessionFactory.openSession().update(statement, student);
}
public void deleteStudent(int stuId){
String statement="com.qdu.mapping.StudentMapper.deleteStudentById";
sqlSessionFactory.openSession().delete(statement, stuId);
}
public Teacher selectTeacherById(int teacherId){
String statement="com.qdu.mapping.TeacherMapper.selectTeacherById";
return sqlSessionFactory.openSession().selectOne(statement,teacherId);
}
}
Service接口:
public interface StudentService {
public Student getStudentById(int stuId);
public List selectTeacherByStudentId(int stuId);
public Clazz getClazzById(int clazzId);
public void insertStudent(Student student);
public void updateStudent(Student student);
public void deleteStudent(int stuId);
public List studentList(int clazzId);
public Teacher selectTeacherById(int teacherId);
}
@Transactional为Spring的事务注解,表示该类里面的所有方法或者这个方法的事务由spring处理,
来保证事务的原子性, 每一个业务方法开始时都会打开一个事务,这样的好处,可以省去一些XML
配置文件的繁琐编写
@Transactional 注解应该只被应用到 public 方法上,这是由 Spring AOP 的本质决定的。如果你在 protected、private 或者默认可见性的方法上使用 @Transactional 注解,这将被忽略,也不会抛出任何异常。
默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使用@Transactional注解进行修饰。
事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性
@Service为Spring的service注解,标注服务类
//为什么要用接口?!
//第一种方式:建立个接口
//第二种方式:直接实例化
//第一种:比如你用Spring框架,可以在用到UserServiceImpl的时候定义接口,最后使用XML方式实例化,这样以后需要修改,只要改xml(所谓的低耦合)
//第二种:假设你直接在java文件中直接实例化,万一你不在用这个类了,要用另外的类来代替,需要改java文件,很麻烦(即所谓的低内聚高耦合)
//耦合度低的程序要好
@Transactional
@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public Student getStudentById(int stuId) {
// System.out.println(studentDao.selectStudentById(10111));
return studentDao.selectStudentById(stuId);
}
@Override
public Clazz getClazzById(int clazzId) {
System.out.println(studentDao.selectClazzById(1));
return studentDao.selectClazzById(clazzId);
}
@Override
public void insertStudent(Student student) {
studentDao.insertStudent(student);
}
@Override
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
@Override
public void deleteStudent(int stuId) {
studentDao.deleteStudent(stuId);
}
@Override
public List studentList(int clazzId) {
return studentDao.studentList(clazzId);
}
@Override
public List selectTeacherByStudentId(int stuId) {
return studentDao.selectTeacherByStudentId(stuId);
}
@Override
public Teacher selectTeacherById(int teacherId) {
return studentDao.selectTeacherById(teacherId);
}
}
@Controller控制器注解,用于处理多个URL请求@RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;还可以标注在方法签名处,以便进一步对请求进行分流
@Controller
@RequestMapping(value = "/anna")
public class TestController {
@Autowired
private StudentService studentServiceImpl;//调用父类的方法,再调用子类中的方法
@RequestMapping(value = "/student.do")
public String studentLogin(ModelMap map) {
return "student";
}
@RequestMapping(value = "/admin.do")
public String teacherLogin(ModelMap map) {
return "admin";
}
@RequestMapping(value = "/juin.do")
public String queryStudent(HttpServletRequest request, ModelMap map) {
int id = Integer.parseInt(request.getParameter("stuId"));
int password = Integer.parseInt(request.getParameter("password"));
Student student = studentServiceImpl.getStudentById(id);
System.out.println(student);
// int转String验证可以+""啊
if (student != null && (id + "") != null && (password + "") != null && id == student.getStuId() && password == 123) {
map.addAttribute("student", student);
return "success";
} else {
return "fail";
}
}
@RequestMapping(value = "/adminLogin.do")
public String teacherLoginDo(HttpServletRequest request, ModelMap map) {
int id = Integer.parseInt(request.getParameter("id"));
int password = Integer.parseInt(request.getParameter("password"));
Clazz clazz = studentServiceImpl.getClazzById(id);
if (id == clazz.getClazzId() && password == 123) {
map.addAttribute("clazz", clazz);
return "adminSuccess";
} else {
return "fail";
}
}
@RequestMapping(value = "forInsertStudent.do")
public String forInsertStudent(ModelMap map, int clazzId, HttpServletRequest request) {
clazzId = Integer.parseInt(request.getParameter("clazzId"));
Clazz clazz = studentServiceImpl.getClazzById(clazzId);
Date time = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String current = sdf.format(time);
Random random = new Random();
int cc=Integer.parseInt(current);
int x = random.nextInt(900) + 100;
System.out.println(cc);
map.addAttribute("clazz", clazz);
map.addAttribute("date", cc);
map.addAttribute("random", x);
return "insertStudent";
}
@RequestMapping(value = "insertStudent.do")
public String insertStudent(HttpServletRequest request, ModelMap map, Student student) {
studentServiceImpl.insertStudent(student);
int id = Integer.parseInt(request.getParameter("clazz.clazzId"));
Clazz clazz = studentServiceImpl.getClazzById(id);
map.addAttribute("clazz", clazz);
return "adminSuccess";
}
@RequestMapping(value = "forUpdateStudent.do")
public String forUpdateStudent(HttpServletRequest request, ModelMap map) {
int id = Integer.parseInt(request.getParameter("stuId"));
Student student = studentServiceImpl.getStudentById(id);
map.addAttribute("student", student);
return "updateStudent";
}
@RequestMapping(value = "updateStudent.do")
public String updateStudent(ModelMap map, Student student, int stuId) {
studentServiceImpl.updateStudent(student);
student = studentServiceImpl.getStudentById(stuId);
Clazz clazz = studentServiceImpl.getClazzById(student.getClazz().getClazzId());
map.addAttribute("clazz", clazz);
return "adminSuccess";
}
@RequestMapping(value = "forDeleteStudent.do")
public String forDeleteStudent(HttpServletRequest request, ModelMap map) {
int id = Integer.parseInt(request.getParameter("stuId"));
Student student = studentServiceImpl.getStudentById(id);
map.addAttribute("student", student);
return "deleteStudent";
}
// clazzId来源于前端的传值,免去request,是不是很有趣?另外,逻辑语句要有先有后,第n次逻辑颠倒
@RequestMapping(value = "deleteStudent.do")
public String deleteStudent(ModelMap map, int clazzId, int stuId, Student student, Clazz clazz) {
studentServiceImpl.deleteStudent(stuId);
clazz = studentServiceImpl.getClazzById(clazzId);
map.addAttribute("clazz", clazz);
return "adminSuccess";
}
@RequestMapping(value = "teacher.do")
public String teacher() {
return "teacher";
}
@RequestMapping(value = "teacherLogin.do")
public String teacherLogin(ModelMap map, HttpServletRequest request) {
int teacherId = Integer.parseInt(request.getParameter("teacherId"));
int password = Integer.parseInt(request.getParameter("password"));
Teacher teacher = studentServiceImpl.selectTeacherById(teacherId);
if (teacherId == teacher.getTeacherId() && password == 123) {
// for (int i = 0; i < teacher.getStudents().size(); i++) {
// Student student = studentServiceImpl.getStudentById(teacher.getStudents().get(i).getStuId());
map.addAttribute("teacher", teacher);
// map.addAttribute("sss", student);
// }
return "teacherSuccess";
} else {
return "fail";
}
}
@RequestMapping(value = "firstPage.do")
public String firstPage() {
return "translate";
}
}
最后就是页面了,JSP页面与JSTL以及EL表达式相结合,足够满足一般需求
页面很多,贴出最主要的一两个
首页
不同身份登录
<%@page contentType="text/html" pageEncoding="UTF-8"%>
首页
<%--
Document : teacher
Created on : 2017-4-27, 16:50:03
Author : ACER
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
教师登录
<%--
Document : teacherSuccess
Created on : 2017-4-27, 17:59:20
Author : ACER
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
教师登录成功
登录成功-${teacher.teacherName}
老师
学生列表
学生Id
学生姓名
学生性别
学生年龄
${s.stuId}
${s.stuName}
${s.stuGender}
${s.stuAge}
运行结果
此为结束,欢迎大家提出问题,共同探讨
____Juin