SSM整合模拟

SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式

1.界面层(视图层)—— SpringMvc:主要功能是是接受用户的数据,显示请求的处理结果。使用 web 页面和用户交互,手机 app 也就是表示层的,用户在 app 中操作,业务逻辑在服务器端处理。
2.业务逻辑层 —— Spring:接收表示传递过来的数据,检查数据,计算业务逻辑,调用数据访问层获取数据。
3.数据访问层 —— MyBatis:与数据库打交道。主要实现对数据的增、删、改、查。将存储在数据库中的数据提交给业务层,同时将业务层处理的数据保存到数据库。

在这里插入图片描述

为什么要使用三层?
1,结构清晰、耦合度低, 各层分工明确
2,可维护性高,可扩展性高
3,有利于标准化
4,开发人员可以只关注整个结构中的其中某一层的功能实现
5,有利于各层逻辑的复用

1.建立表和Web工程,导入maven依赖和插件

2.配置web.xml

注册中央调度器

  <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:conf/dispatcherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

注册监听器

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

注册字符集过滤器

  <filter>
    <filter-name>characterEncodingFilter</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>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

3.定义包,组织程序的结构

在这里插入图片描述
在这里插入图片描述
4.编写配置文件

  • Spring 配置文件(用到属性配置文件)
<!--spring的配置文件,声明service,dao,工具类等对象-->

<context:property-placeholder location="classpath:conf/jdbc.properties" />

<!--声明数据源,连接数据库-->
<bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"
      init-method="init" destroy-method="clone">
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!--声明SqlSessionFactoryBean创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dateSource" />
    <property name="configLocation" value="classpath:conf/mybatis.xml" />
</bean>

<!--声明mybatis的扫描器,创建dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    <property name="basePackage" value="com.bjpowernode.dao" />
 </bean>

<!--声明service的注解@Service所在的包名-->
<context:component-scan base-package="com.bjpowernode.service" />

<!--事务配置:注解的配置,aspectj(切面编程)的配置-->
  • SpringMvc 配置文件
<!--springmvc的配置文件,声明controller和其他web相关对象-->
<context:component-scan base-package="com.bjpowernode.controller"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

<!--
    1.响应ajax请求,返回json
    2.解决静态资源访问问题
-->
<mvc:annotation-driven />
  • MyBatis配置文件
<configuration>
    <!--设置别名-->
    <typeAliases>
        <!--name:实体类所在包名-->
        <package name="com.bjpowernode.domain"/>
    </typeAliases>

    <mappers>
        <!--告诉 mybatis 要执行的 sql 语句的位置-->
        <!--name是mapper文件所在包名,包中所有的mapper.xml一次都能加载-->
        <!--使用package的要求:
            1.mapper文件名称和dao接口名必须完全一样,包括大小写
            2.mapper文件和dao接口必须在同一目录
        -->
        <package name="com.bjpowernode.dao"/>
    </mappers>
</configuration>

5.写实体类

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

6.写Dao 接口和 sql 映射文件(mapper文件,编写SQL语句)

public interface StudentDao {

    int insertStudent(Student student);
    List<Student> selectStudents();
}
<mapper namespace="com.bjpowernode.dao.StudentDao">
    <select id="selectStudents" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student order by id desc
    </select>

    <insert id="insertStudent" >
        insert into student(name,email,age) values(#{name},#{email},#{age})
    </insert>
</mapper>

7.写Service 接口和实现类

public interface StudentService {

    int addStudent(Student student);
    List<Student> findStudents();
}
@Service
public class StudentServiceImpl implements StudentService {
    //引用类型自动注入:@Resource,@Autowired
    @Resource
    private StudentDao studentDao;
    @Override
    public int addStudent(Student student) {
        int nums = studentDao.insertStudent(student);
        return nums;
    }

    @Override
    public List<Student> findStudents() {
        return studentDao.selectStudents();
    }
}

8.处理器定义

@Controller
@RequestMapping("/student")
public class StudentController {

    @Resource
    private StudentService studentService;

    //注册学生
    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv = new ModelAndView();
        String tips = "注册失败";
        //调用service处理student
        int nums = studentService.addStudent(student);
        if(nums > 0){
            tips = "学生【" + student.getName() + "】注册成功";
        }
        mv.addObject("tips",tips);
        mv.setViewName("result");
        return mv;
    }

    //处理查询,响应ajax
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){
        List<Student> students = studentService.findStudents();
        return  students;
    }
}

9.定义视图-首页文件 —— index.jsp

指定路径

<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>

指定 base 标签

<head>
    <title>功能入口</title>
    <base href="<%=basePath%>" />
</head>

页面内容

<body>
    <div align="center">
        <p>SSM整合的例子</p>
        <img src="images/3.jpg" />
        <table>
            <tr>
                <td><a href="addStudent.jsp">注册学生</a></td>
            </tr>
            <tr>
                <td><a href="listStudent.jsp">浏览学生</a></td>
            </tr>
        </table>
    </div>
</body>

10.定义其他视图文件

注册学生页面 —— addStudent.jsp
需要如上指定路径和base标签,以下是页面内容

<body>
    <div align="center">
        <form action="student/addStudent.do" method="post">
            <table>
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="name"></td>
                </tr>
                <tr>
                    <td>邮箱:</td>
                    <td><input type="text" name="email"></td>
                </tr>
                <tr>
                    <td>年龄:</td>
                    <td><input type="text" name="age"></td>
                </tr>
                <tr>
                    <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </div>
</body>

浏览学生页面 —— listStudent.jsp

  • 页面表格
<body>
    <div align="center">
        <table>
            <thead>
            <tr>
                <td>学号</td>
                <td>姓名</td>
                <td>邮箱</td>
                <td>年龄</td>
            </tr>
            </thead>
            <tbody id="info">

            </tbody>
        </table>
        <input type="button" id="btnLoader" value="查询数据">
    </div>
</body>
  • js 内容(引入 JQuery)
<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>查询学生ajax</title>
    <base href="<%=basePath%>" />
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
  • js 发起 ajax
    <script type="text/javascript">
        $(function () {
            //在当前页面dom对象加载后,执行loadStudentDate()
            loadStudentDate();
            $("#btnLoader").click(function () {
                loadStudentDate();
            })
        })
        
        function loadStudentDate() {
            $.ajax({
                url:"student/queryStudent.do",
                type:"get",
                dataType:"json",
                success:function (date) {
                    //清除旧数据
                    $("#info").html("");
                    //查询出数据
                    $.each(date,function (i,n) {
                        $("#info").append("<tr>")
                            .append("<td>"+n.id+"<td>")
                            .append("<td>"+n.name+"<td>")
                            .append("<td>"+n.email+"<td>")
                            .append("<td>"+n.age+"<td>")
                            .append("</tr>")
                    })
                }
            })
        }
    </script>
</head>

注册结果页面— result.jsp

<body>
    result.jsp结果页面,注册结果:${tips}
</body>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值