SSM整合基础知识

1 ssm整合概念

spring+springmvc+mybatis
spring提供ioc+aop
springmvc提供controller
mybatis提供持久层
ssm
ssm2:struts2
ssh
ssh2

2 创建web项目 更改编码集

3 导入jar包

springioc
springaop
springmvc
mybatis
json
log4j
jstl
mybatis-spring
upload

4 分包

action
service
dao
interceptor
exception
util
entity
js
css
imgs

5 WEB-INF下引入核心标签库的tld文件

6 创建springmvc的核心配置文件

springmvc_conf.xml

  • 通过context标签扫描创建bean的包
  • 通过mvc标签自动注册注解形式的映射器和适配器
  • 配置视图解析器
  • 配置多部件表单解析器
  • 配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
<beans 	xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-3.0.xsd
                           http://www.springframework.org/schema/mvc 
                           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--    * 通过context标签扫描创建bean的包 -->
    <context:component-scan base-package="com.zhiyou100"/>

    <!-- 	* 通过mvc标签自动注册注解形式的映射器和适配器 -->
    <mvc:annotation-driven/>

    <!-- 	* 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 	* 配置多部件表单解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="99999999"/>
    </bean>


    <!-- 	* 配置拦截器 -->
</beans>

7 创建spring核心配置文件

spring_config.xml

  • 配置datasource的bean
  • 配置sqlsessionfactory的bean
  • 配置事物管理bean
  • 配置动态获取mapper接口实现类对象的bean
<!--1 创建数据源datasource的bean -->
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="url" value="jdbc:mysql://localhost:3306/db_37" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>

<!-- 2 创建sqlsessionfactory的bean -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 指定数据源 -->
    <property name="dataSource"  ref="ds"/>
    <!-- 指定mapper映射文件的路径 -->
    <property name="mapperLocations"    value="classpath:com/zhiyou100/dao/*.xml"/>	
</bean>

<!-- 3创建事物管理bean -->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 指定数据源 -->
    <property name="dataSource"  ref="ds"/>
</bean>

<!-- 4 创建 MapperScannerConfigurer的bean 自动扫描dao包 为mapper接口创建实现类对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.zhiyou100.dao"/>
</bean>

8 配置web的核心配置文件

web.xml

  • 配置欢迎页面

  • 配置servletcontext的初始化参数contextCondfigLocation指定spring核心配置文件的位置

  • 配置spring的上下文监听器

  • 配置springmvc的中央控制器

  • 配置springmvc的全站编码过滤器

  • 配置自己的过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>java37_frame_ssm_01</display-name>
    <welcome-file-list>
        <welcome-file>student.jsp</welcome-file>
    </welcome-file-list>
    <!--     * 配置欢迎页面 -->
    <!-- 	 * 配置servletcontext的初始化参数contextCondfigLocation指定spring核心配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring_config.xml</param-value>
    </context-param>

    <!-- 	 * 配置spring的上下文监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 	 * 配置springmvc的中央控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc_conf.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <!-- 	 * 配置springmvc的全站编码过滤器 -->
    <filter>
        <filter-name>filterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>filterEncoding</filter-name>
        <url-pattern>*.action</url-pattern>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <!--     * 配置自己的过滤器 -->
</web-app>

9 创建数据库 并启动项目

10 创建数据库和表

USE db_37;
CREATE TABLE student(
   sid INT PRIMARY KEY AUTO_INCREMENT,
   sname VARCHAR(11) UNIQUE,
   sage INT,
   sdy BOOLEAN,
   sbirthday DATE,
   score FLOAT(4,1),
   tid INT,
   CONSTRAINT fk_1111 FOREIGN KEY(tid) REFERENCES teacher(tid)
);
CREATE TABLE teacher(
   tid INT PRIMARY KEY AUTO_INCREMENT,
   tname VARCHAR(11) UNIQUE,
   tpwd  VARCHAR(6)
);
INSERT INTO teacher VALUES(NULL,"张三","123456");
INSERT INTO teacher VALUES(NULL,"李四","123456");
INSERT INTO teacher VALUES(NULL,"王五","123456");
INSERT INTO teacher VALUES(NULL,"赵六","123456");

INSERT INTO student VALUES(
     NULL,
     SUBSTRING(UUID(),1,4),
     TRUNCATE(RAND()*10+15,0),
     RAND()>0.5,
     CONCAT(TRUNCATE(RAND()*10+2000,0),"-",TRUNCATE(RAND()*12+1,0),"-",TRUNCATE(RAND()*30+1,0)),
     TRUNCATE(RAND()*100+0,1),
     TRUNCATE(RAND()*4+1,0)
);

SELECT * FROM student;

11 根据表创建实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable{
//	  sid INT PRIMARY KEY AUTO_INCREMENT,
//	   sname VARCHAR(11) UNIQUE,
//	   sage INT,
//	   sdy BOOLEAN,
//	   sbirthday DATE,
//	   score FLOAT(4,1),
//	   tid INT,
	private Integer sid;
	private String sname;
	private Integer sage;
	private Boolean sdy;
	private Date sbirthday;
	private Float score;
	private Integer tid;
	private Teacher teacher;

}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher implements Serializable{
//	  tid INT PRIMARY KEY AUTO_INCREMENT,
//	   tname VARCHAR(11) UNIQUE,
//	   tpwd  VARCHAR(6)
	private Integer tid;
	private String tname;
	private String tpwd;

}

12 创建dao接口

public interface StudentMapper {
	List<Student> getAll();
	List<Student> getAllByTid(int tid);
	Student getOneBySid(int sid);
	Student getOneBySname(String sname);
	int deleteOneBySid(int sid);
	int addOne(Student s);
	int updateOne(Student s);
}

public interface TeacherMapper {
    Teacher getOneByTname(String tname);
    Teacher getOneByTid(int tid);
}

13 根据dao接口创建sql映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhiyou100.dao.StudentMapper">
    <!--     List<Student> getAll(); -->
    <select id="getAll" resultType="com.zhiyou100.entity.Student">
        select * from student
    </select>
    <!-- 	List<Student> getAllByTid(int tid); -->
    <select id="getAllByTid" resultType="com.zhiyou100.entity.Student" parameterType="int">
        select * from student  where tid=#{tid}
    </select>
    <!-- 	Student getOneBySname(String sname); -->
    <select id="getOneBySname" resultType="com.zhiyou100.entity.Student" parameterType="string">
        select * from student  where sname=#{sname}
    </select>
    <!-- 	Student getOneBySid(int sid); -->
    <select id="getOneBySid" resultType="com.zhiyou100.entity.Student" parameterType="int">
        select * from student  where sid=#{sid}
    </select>
    <!-- 	int deleteOneBySid(int sid); -->
    <delete id="deleteOneBySid" parameterType="int">
        delete from student where sid=#{sid}
    </delete>
    <!--         	private Integer sid; -->
    <!-- 			private String sname; -->
    <!-- 			private Integer sage; -->
    <!-- 			private Boolean sdy; -->
    <!-- 			private Date sbirthday; -->
    <!-- 			private Float score; -->
    <!-- 			private Integer tid; -->
    <!-- 			private Teacher teacher; -->
    <!-- 	int addOne(Student s); -->
    <insert id="addOne" parameterType="com.zhiyou100.entity.Student">
        insert into student(sname,sage,sdy,sbirthday,score,tid) 
        values(#{sname},#{sage},#{sdy},#{sbirthday},#{score},#{tid})
    </insert>
    <!-- 	int updateOne(Student s); -->
    <update id="updateOne" parameterType="com.zhiyou100.entity.Student">
        update student 
        <set>
            <if test="sname != null">
                sname=#{sname},
            </if>
            <if test="sage != null">
                sage=#{sage},
            </if>
            <if test="sdy != null">
                sdy=#{sdy},
            </if>
            <if test="sbirthday != null">
                sbirthday=#{sbirthday},
            </if>
            <if test="score != null">
                score=#{score},
            </if>
            <if test="tid != null">
                tid=#{tid},
            </if>
        </set>
        <where>
            sid=#{sid}
        </where>
    </update>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhiyou100.dao.TeacherMapper">
<!--     Teacher getOneByTname(String tname); -->
         <select id="getOneByTname" parameterType="String" resultType="com.zhiyou100.entity.Teacher">
                select * from teacher where tname=#{tname}
         </select>
<!--     Teacher getOneByTid(int tid); -->
        <select id="getOneByTid" parameterType="int" resultType="com.zhiyou100.entity.Teacher">
                select * from teacher where tid=#{tid}
         </select>
</mapper>

14 创建service接口和其实现类

package com.zhiyou100.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiyou100.dao.StudentMapper;
import com.zhiyou100.entity.Student;
import com.zhiyou100.exception.StudentCrudException;
@Service
public class StudentServiceImp   implements StudentService{

    @Autowired
    private StudentMapper studentMapper;
    public List<Student> getAll() {
        return studentMapper.getAll();
    }

    @Override
    public List<Student> getAllByTid(int tid) {
        return studentMapper.getAllByTid(tid);
    }

    @Override
    public Student getOneBySid(int sid) {
        return studentMapper.getOneBySid(sid);
    }

    @Override
    public int deleteOneBySid(int sid) {
        return studentMapper.deleteOneBySid(sid);
    }

    public int addOne(Student s) {
        Student dbStudent=studentMapper.getOneBySname(s.getSname());
        if(dbStudent!=null){
            throw new StudentCrudException("学生名字已经存在,添加失败!");
        }
        return studentMapper.addOne(s);
    }

    @Override
    public int updateOne(Student s) {
        return studentMapper.updateOne(s);
    }
}
@Service
public class TeacherServiceImp   implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    
	public Teacher login(String tname, String tpwd) {
		Teacher teacher=teacherMapper.getOneByTname(tname);
		if(teacher==null){
			throw new TeacherLoginException("账号不存在!");
		}
		if(!teacher.getTpwd().equals(tpwd)){
			throw new TeacherLoginException("密码错误!");
		}
		return teacher;
	}
}

15 实现登录和查询所有功能

15.1 创建页面

  • 老师登录页面:teacher_login.jsp
<h1>老师登录页面</h1>
<c:if test="${not empty message }">
    <font color="red">提示信息:${message}</font><br/>
</c:if>
<form  action="<c:url value='/teacher/login.action'/>" method="post">
    <table>
        <tr>
            <th>老师名字:</th>
            <td><input type="text" name="tname" value="${teacher.tname}"/></td>
        </tr>
        <tr>
            <th>老师密码:</th>
            <td><input type="password" name="tpwd"  value="${teacher.tpwd}"/></td>
        </tr>
        <tr>
            <th colspan="2">
                <input  type="submit" value="老师登录"/>
            </th>
        </tr>
    </table>
</form>
  • 学生管理页面:student_manager.jsp
<h1>学生管理页面:${title}</h1>
<c:if test="${not empty message }">
    <font color="red">提示信息:${message}</font><br/>
</c:if>
<table>
    <tr>
        <th>顺序</th>
        <th>学号</th>
        <th>名字</th>
        <th>年龄</th>
        <th>党员</th>
        <th>生日</th>
        <th>分数</th>
        <th>老师</th>
        <th>操作</th>
    </tr>
    <c:if test="${not empty list}">
        <c:forEach items="${list}"  varStatus="vs" var="stu">
            <tr>
                <td>${vs.index+1}</td>
                <td>${stu.sid}</td>
                <td>${stu.sname}</td>
                <td>${stu.sage}</td>
                <td>${stu.sdy}</td>
                <td>${stu.sbirthday}</td>
                <td>${stu.score}</td>
                <td>${stu.teacher.tname}</td>
                <td><a href="">删除</a><a href="">修改</a></td>
            </tr>
        </c:forEach>
    </c:if>
</table>

15.2 创建action

  • teacheraction
@Controller
@RequestMapping("/teacher")
public class TeacherAction {
	@Autowired
	private TeacherService teacherService;
	
	@RequestMapping(value="/login.action",method=RequestMethod.POST)
	public String loginMethod(Teacher teacher,HttpSession session,Model model){
		try {
			Teacher dbTeacher=teacherService.login(teacher.getTname(), teacher.getTpwd());
			session.setAttribute("teacher", dbTeacher);
			return "forward:/student/getAll.action";
		} catch (TeacherLoginException e) {
			model.addAttribute("message", e.getMessage());
			return "teacher_login";
		}
	}
}
  • studentaction
@Controller
@RequestMapping("/student")
public class StudentAction {
	@Autowired
	private StudentService studentService;
	
	@RequestMapping("/getAll.action")
	public String getAllMethod(Model model){
		model.addAttribute("list", studentService.getAll());
		model.addAttribute("title", "查询所有学生信息");
		return "student_manager";
	}

}

15.3 测试

15.4 细节更改1

  • 党员显示是/否
<c:choose>
    <c:when test="${stu.sdy}"> 是</c:when>
    <c:otherwise>否</c:otherwise>
</c:choose>
  • 日期显示
public String getSbirthdayStr(){
		return new SimpleDateFormat("yyyy年MM月dd日").format(sbirthday);
}
 ${stu.sbirthdayStr}|<fmt:formatDate value="${stu.sbirthday}" pattern="yyyy年MM月dd日"/>

15.5 显示老师

  • 更改studentMapper.xml 查询学生时获取学生的老师信息
<resultMap type="com.zhiyou100.entity.Student" id="studentMap1">
    <id column="sid" property="sid"/>
    <result column="sname" property="sname"/>
    <result column="sage" property="sage"/>
    <result column="sdy" property="sdy"/>
    <result column="sbirthday" property="sbirthday"/>
    <result column="score" property="score"/>
    <result column="tid" property="tid"/>
    <!-- 给属性teacher赋值 -->
    <association property="teacher" column="tid" select="com.zhiyou100.dao.TeacherMapper.getOneByTid" />
</resultMap>
<select id="getAll" resultMap="studentMap1">
    select * from student
</select>

15.6 当前老师只能删除和修改当前老师的学生

<c:if test="${sessionScope.teacher.tid eq stu.tid}">
    <a href="<c:url value='/student/deleteOne/${stu.sid}.action'/>">删除</a>
    <a href="<c:url value='/student/getOne.action?sid=${stu.sid}'/>">修改</a>
</c:if>

16 实现删除

16.1 jsp:student_manager.jsp

 <a href="<c:url value='/student/deleteOne/${stu.sid}.action'/>">删除</a>

16.2 action:

@RequestMapping(value="/deleteOne/{sid}.action",method=RequestMethod.GET)
public String deleteOneMethod(@PathVariable("sid") int sid,Model model){
    studentService.deleteOneBySid(sid);
    model.addAttribute("message", "删除"+sid+"成功!");
    return "forward:/student/getAll.action";
}

17 实现修改和添加

17.1 修改和添加使用同一个页面:student_update_add.jsp

<script type="text/javascript" src="<c:url value='/js/jquery-1.6.4.min.js'/>"></script>
<h1>${title}</h1>
<c:if test="${not empty message }">
    <font color="red">提示信息:${message}</font><br/>
</c:if>
<c:set var="actionName" value="${empty requestScope.student?'addOne.action':'updateOne.action'}"/>
${actionName}<br/>
<form action="<c:url value='/student/${actionName}'/>" method="post" id="form_1">
    <input type="hidden" name="sid" value="${requestScope.student.sid}">
    <table>
        <tr>
            <th>学生名字:</th>
            <td><input type="text" name="sname" value="${requestScope.student.sname}"/></td>
        </tr>
        <tr>
            <th>学生年龄:</th>
            <td><input type="text" name="sage" value="${requestScope.student.sage}"/></td>
        </tr>
        <tr>
            <th>学生分数:</th>
            <td><input type="text" name="score" value="${requestScope.student.score}"/></td>
        </tr>
        <tr>
            <th>学生生日:</th>
            <td><input type="text" name="sbirthday" value="${requestScope.student.sbirthdayStr}"/></td>
        </tr>
        <tr>
            <th>是否党员:</th>
            <td>是:<input type="radio" name="sdy" value="true"/> | 
                否:<input type="radio" name="sdy" value="false"/> 
            </td>
        </tr>
        <tr>
            <th colspan="2"><input type="submit" value="${empty requestScope.student?'添加学生':'修改学生'}"/></th>
        </tr>
    </table>

</form>
<script type="text/javascript">
    $(function(){
        var sdy='${student.sdy}';
        $.each($("#form_1 input[name='sdy']"),function(i,n){
            if($(n).val()==sdy){
                $(n).attr("checked","checked");
            }
        });
    });
</script>

17.2 修改action:

@RequestMapping(value="/updateOne.action",method=RequestMethod.POST)
public String updateOneMethod(Student stu,Model model){
    studentService.updateOne(stu);
    model.addAttribute("message", "修改"+stu.getSid()+"学生信息成功!");
    return "forward:/student/getAll.action";
}

17.3 添加action

@RequestMapping(value="/addOne.action",method=RequestMethod.POST)
public String addOneMethod(Student stu,Model model,HttpSession session){
    Teacher teacher=(Teacher)session.getAttribute("teacher");
    stu.setTid(teacher.getTid());
    studentService.addOne(stu);
    model.addAttribute("message", "添加"+stu.getSname()+"学生信息成功!");
    return "forward:/student/getAll.action";
}

17.4 注意事项:@DateTimeFormat not supported

导入jar包:joda-time-2.10.13.jar

posted @ 2021-12-02 22:23  RenVei  阅读(50)  评论(0编辑  收藏  举报