ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ssm整合小项目(动力节点王老师的课程学的)

2021-11-02 20:32:34  阅读:180  来源: 互联网

标签:service 王老师 springframework public ssm bj student import 节点


(   项目中有两个容器 一个是springmvc 管理controller类的, 第二个是spring容器  管理service          dao    工具类的对象的  ,整合就是把这两个容器能够发生关系,,这两个容器本身是父                   子关系 spring是父,所以使用时在web.xml文件注册两个容器)

目标:

   对三个框架进行集合运用,了解整合步骤,对容器和对象加深理解

项目实现功能:

        1.添加学生

         2.查找学生

整合步骤

   1.在所需要的数据库中,建立使用的表 student

   2.新建Maven  web项目

   3.加入所需要的依赖

   4.配置web.xml文件

   5.新建包 目录 文件

    6.写ssm的三个主要配置文件

    7.在相应的包中添加实现功能的代码 


代码及思路

一:建立所需的表 

           注意这里设置的id是自增的

 二:新建Maven的model,

           从原型中选择webapp,修改自己想要的构建坐标

三: 加入依赖项

       包括 spring, mybatis ,spring和mybatis整合, springmvc ,mysql驱动 ,jsp  ,servlet ,            阿里的连接池        jackson (处理json数据用的)    

四:配置web.xml文件

      1.注册DispatcherServlet (这是框架提供的Servlet类 叫中央调度器)

                目的:1)创建Servlet 接受用户请求

                           2)创建springmvc的容器 ,后面才能创建Controller对象

      2.注册spring的监听器

               目的:能够创建spring的容器,才能存放service dao的对象

     3.注册字符集过滤器
                目的:解决post请求乱码问题

<!--1.注册中央调度器-->
   <servlet>
    <servlet-name>mywebServlet</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>
       <!--  这里表示tomcat启动时会创建servlet对象 即上面的中心调度器  -->
   </servlet>
       <servlet-mapping>
         <servlet-name>mywebServlet</servlet-name>
         <url-pattern>*.do</url-pattern>
      </servlet-mapping>

<!--2.注册spring的监听器-->
     <!--   先声明spring配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:conf/applicationContext.xml</param-value>
    </context-param>
 <listener>
     <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>
 </listener>


<!--3.注册字符集过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
           <!-- 过滤器有三个属性  1.encoding字符集 2.     -->
        <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>

五:新建所需的包  

      controller 控制类

      dao 持久层 访问数据库

      domain  实体类对应表中一行的数据

       service业务层

      

六:写ssm的三个主要配置文件

目录结构

   1)spring配置文件 (用来声明service dao 工具类的对象) 

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
<!--   spring的配置文件 用来声明service dao 工具类的对象-->
<!--    声明用到的配置文件信息-->
    <context:property-placeholder location="classpath:conf/jdbc.properties"/>
    <!--    声明数据源 DataSource 连接数据库的信息-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
        <!-- set注入给DruidDataSource提供连接信息   -->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--  声明mybatis使用的SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="dataSource"/>
        <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.bj.dao"/>
    </bean>
    <!--    声明service 从业务层访问,不要直接去访问-->
<!-- 声明service的注解@service所在的包名 可以直接创建他的对象了-->
    <context:component-scan base-package="com.bj.service"/>

<!--  事务的配置 选一个 1.注解的配置 2.aspectj的配置-->
</beans>

   2)springmvc配置文件  (声明controller和web相关的对象)

<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    springmvc的配置文件 用来声明controller和web相关的对象  -->
<!--     组件扫描器-->
    <context:component-scan base-package="com.bj.controller"/>
<!--    视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--1.静态资源和2.ajax用到的 注解驱动 mvc结尾-->
    <mvc:annotation-driven/>

</beans>

   3)连接数据库信息的配置文件

jdbc.url=这里的信息是自己的                   
jdbc.username=这里的信息是自己的
jdbc.password=这里的信息是自己的

   4)mybatis的配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    
    <typeAliases>
      <!--设置别名
        可以使用package 指可以是实体类所在的包名 也可以是别的
      -->
         <package name="com.bj.domain"/>
    </typeAliases>
    
    <mappers>
    <!--  如果使用package name 指的是包名
       使用时有两个要求 1.mapper文件名称和dao接口的名称是相同的
                      2.mapper文件位置和接口的位置在同一目录之下
    -->
        <package name="com.bj.dao"/>
        <!-- <mapper resource="mapping配置文件的路径 有/隔开"/>-->
<!--    <mapper resource="com/bj/dao/StudentDao.xml"/>-->
    </mappers>
</configuration>

  七.在相应的包中添加实现功能的代码 

目录结构

 StudentController类

package com.bj.controller;

import com.bj.domain.Student;
import com.bj.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/student") //表示这个类做的是student的模块
public class StudentController {
   @Resource //完成自动注入
   private StudentService service;
    public StudentController(StudentService service) {
        this.service = service;
    }
    //方法完成注册学生
    @RequestMapping(value = "/addStudent.do") //把这个请求地址和这个方法绑定
    public ModelAndView addStudent(Student student){
        //调用service 处理这个业务 所以这个类要有service属性
       int nums = service.addStudent(student);
        //int nums = studentDao.insertStudent(student);
        String tips ="抱歉 注册失败";
        if(nums>0){
             tips ="恭喜您"+student.getName()+" 注册成功";
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("tips", tips);//输出处理信息
        mv.setViewName("result");//返回处理页面
        return mv;
    }
    //处理查询,响应ajax
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){
     //参数检查,简单的处理
     List<Student> studentList = service.findStudent();

     return  studentList;
    }

StudentDao类

package com.bj.dao;

import com.bj.domain.Student;

import java.util.List;

public interface StudentDao {
    int insertStudent(Student student);
    List<Student> selectStudents();
}

StudentDao.xml  (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.bj.dao.StudentDao">
    <select id="selectStudents" resultType="com.bj.domain.Student">
      select id,name,age from student order by id desc
    </select>

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

</mapper>

Student  实体类

package com.bj.domain;

public class Student {

    private  Integer id;
    private String  name;
    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 Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentServiceImpl

package com.bj.service.impl;

import com.bj.dao.StudentDao;
import com.bj.domain.Student;
import com.bj.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    //使用引用类型的自动注入获得值  1.Autowire 2.Resource
    @Autowired
    @Qualifier("studentDao")
    private StudentDao studentDao;
     //配置文件使用自动注入要有set方法  注解不需要

   // public void setStudentDao(StudentDao studentDao) {
   //     this.studentDao = studentDao;
   // }

    @Override
    public int addStudent(Student student) {

         int nums = studentDao.insertStudent(student);
        return nums;
    }

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

StudentService

package com.bj.service;

import com.bj.domain.Student;

import java.util.List;

public interface StudentService {

    int addStudent(Student student);
    List<Student> findStudent();
}

八:网站页面

   

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ssm处理返回</title>
</head>
<body>
    result.jsp结果页面 注册结果为: ${tips}
</body>
</html>

 

addStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+"://"+
                      request.getServerName()+":"+
                      request.getServerPort()+
                       request.getContextPath()+"/";

%>

<html>

<head>
    <title>注册学生</title>
    <base href="<%=basePath%>"/>
</head>
<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="age"></td>
              </tr>
              <tr>
               <td>&nbsp;</td>
               <td><input type="submit" value="提交注册"></td>
               </tr>
          </table>
       </form>
   </div>

</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+"://"+
            request.getServerName()+":"+
            request.getServerPort()+
            request.getContextPath()+"/";

%>
<html>
<head>
    <title>ssm请求页面</title>
    <base href="<%=basePath%>"/>
</head>
<body>
   <div align="center">
       
       <p>ssm整合的页面功能</p>
       <img src="images/heisi.jpg"/>
       <table>
           <tr>
               <td><a href="addStudent.jsp" >注册学生</a></td>
           </tr>
           <tr>
               <td> <a href="listStudent.jsp">浏览学生</a> </td>
           </tr>
       </table>
   </div>

</body>
</html>

listStudent.jsp

   

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+"://"+
            request.getServerName()+":"+
            request.getServerPort()+
            request.getContextPath()+"/";

%>
<html>
<head>
    <title>查询学生的页面</title>
    <base href="<%=basePath%>"/>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">

        $(function () {
            $("#btnLoader").click(function () {
                  $.ajax({
                      url:"student/queryStudent.do",
                      type:"get",
                      dataType:"json",
                      success:function (resp) {
                          //先清除旧数据
                          $("#info").html("");
                           //对返回的信息数组进行遍历
                           $.each(resp ,function (i,n) {
                                 $("#info").append("<tr>")
                                      .append("<td>"+n.id+"</td>")
                                     .append("<td>"+n.name+"</td>")
                                     .append("<td>"+n.age+"</td>")
                                     .append("</tr>")

                           })

                      }
                  })
            })
        })
    </script>

</head>
<body>
      <div align="center">
          <table>
              <thead>
                <tr>
                    <td>学号</td>
                    <td>姓名</td>
                    <td>年龄</td>
                </tr>
              </thead>
              <tbody id="info">

              </tbody>

              <input type="button" id="btnLoader" value="查询数据">

          </table>


      </div>
</body>
</html>

标签:service,王老师,springframework,public,ssm,bj,student,import,节点
来源: https://blog.csdn.net/qq_52252193/article/details/121106880

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有