springMVC SSM整合开发

SSM整合开发

简介:springMVC笔记02

1、建表

使用mytest库中的student表,字段为:id(主键)、name、age

2、创建Maven web项目,添加依赖

pom.xml文件中需包含 servlet、jsp、springmvc、事务、jackson、mybatis-spring、mybatis、mysql驱动、druid、junit等依赖。

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.fridas</groupId>
  <artifactId>demoSSM</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jsp依赖 -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>demoSSM</finalName>
    <resources>
      <!--将src/main/java目录下的拷贝到target/classes目录下,
          解决默认源代码目录下的xml等资源文件并不会在编译的时候一块打包进classes文件夹问题
      -->
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>

3、申明容器对象,配置web.xml文件

1)声明spring的监听器ContextLoaderListener:创建spring的容器对象, 创建service,dao对象
2)声明springmvc的中央调度器DispatherServlet:创建springmvc容器对象,创建controller对象
3)声明字符集的过滤器 CharacterEncodingFilter,解决post请求乱码的问题

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/applicationContext.xml</param-value>
  </context-param>
  
  <!--申明过滤器,解决post请求中乱码问题-->
  <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>
    <!--强制请求及应答(request & response)对象使用encoding的编码方式-->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <!--强制所有请求,先经过过滤器处理-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!--声明spring监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--申明springMVC的核心对象-->
  <servlet>
    <servlet-name>mySpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--自定义配置文件位置-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:conf/springmvc.xml</param-value>
    </init-param>
    <!--表示服务器tomcat创建对象的顺序,大于等于0的整数值,数值越小创建越早-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <!--将一些请求交给mySpringMVC处理-->
    <servlet-name>mySpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

4、创建项目需要的包:dao层、service层、controller、实体类等。目录结构如下

5、配置spring,mybatis,springmvc配置文件

1)spring配置文件:applicationContext.xml

<?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
        http://www.springframework.org/schema/context/spring-context.xsd">


    <import resource="springmvc.xml"/>

    <context:property-placeholder location="classpath:conf/jdbc.properties"/>
    <!--配置dataSource:使用Spring的数据源替换Mybatis的配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:conf/mybatis.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="factory" />
        <property name="basePackage" value="com.fridas.dao" />
    </bean>

    <!--注解支持-->
    <context:annotation-config/>
    <!--指定注解扫描包,这包下的注解会生效-->
    <context:component-scan base-package="com.fridas.service"/>

</beans>

jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

2)mybatis配置文件:mybatis.xml

<?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>

    <!--设置mybatis全局配置-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!--以包为单位,将包下的所有实体类的类型设置成默认的类型别名,即类名且不区分大小写-->
        <package name="com.fridas.domain"/>
    </typeAliases>

    <!--引入映射文件-->
    <mappers>
        <!--以包为单位引入映射文件要求:
        1.mapper接口所在的包要与映射文件所在的包名保持一致
        2.mapper接口要与映射文件名保持一致
        -->
        <package name="com.fridas.dao"/>
    </mappers>
</configuration>

3)springmvc配置文件:springmvc.xml

<?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">

    <!--申明组件扫描器-->
    <context:component-scan base-package="com.fridas.controller"/>
    <!--申明视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀:指定视图文件路径-->
        <property name="prefix" value="/WEB-INF/view/"/>
        <!--后缀:指定视图文件拓展名-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--申明注解驱动:resources和@RequestMapping使用冲突-->
    <mvc:annotation-driven />

    <mvc:resources mapping="/static/**" location="/static/" />

</beans>

6、写java代码, 实体类, dao接口和mapper文件, servie层接口及实现类,controller类。 使用注解声明对象和赋值

1)实体类Student:

package com.fridas.domain;

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

//Setter和Getter及toString方法省略

}

2)dao层接口及其对应mapper文件
StudentDao.java:

package com.fridas.dao;

import com.fridas.domain.Student;
import java.util.List;

public interface StudentDao {

    int insertStudent(Student student);

    int deleteStudent(String name);

    int updateStudent(Student student);

    List<Student> selectStudents();
}

StudentDao.xml:

<?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.fridas.dao.StudentDao">

    <!--int insertStudent(Student student);-->
    <insert id="insertStudent">
        insert into student(name,age) values(#{name},#{age})
    </insert>

    <!--int deleteStudent(String name);-->
    <delete id="deleteStudent">
        delete from student where name = #{name}
    </delete>

    <!--int updateStudent(Student student);-->
    <update id="updateStudent">
        update student set name = #{name},age = #{age} where name = #{name}
    </update>

    <!--List<Student> selectStudents();-->
    <select id="selectStudents" resultType="com.fridas.domain.Student">
        select id,name, age from student order by id desc
    </select>

</mapper>

3)servie层接口及实现类
StudentService.java:

package com.fridas.service;

import com.fridas.domain.Student;
import java.util.List;

public interface StudentService {
    int addStudent(Student student);
    int deleteStudent(String name);
    int updateStudent(Student student);
    List<Student> queryStudents();
}

StudentServiceImpl.java:

package com.fridas.service.impl;

import com.fridas.dao.StudentDao;
import com.fridas.domain.Student;
import com.fridas.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    /**
     * dao 是引用类型。 StudentDao类型的对象是在spring的配置文件中创建的对象
     * 引用类型自动注入  @Autowired, @Resource
     */
    @Autowired
    private StudentDao dao;

    @Override
    public int addStudent(Student student) {
        int rows = dao.insertStudent(student);
        return rows;
    }

    @Override
    public int deleteStudent(String name) {
        int result = dao.deleteStudent(name);
        return result;
    }

    @Override
    public int updateStudent(Student student) {
        int updateStudent = dao.updateStudent(student);
        return updateStudent;
    }

    @Override
    public List<Student> queryStudents() {
        List<Student> students = dao.selectStudents();
        return students;
    }
}

4)后端controller处理文件

package com.fridas.controller;

import com.fridas.domain.Student;
import com.fridas.service.StudentService;
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 javax.naming.Name;
import java.util.List;

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

    /**
     * 声明引用类型, 调用引用类型的业务方法
     * 引用类型自动注入  @Autowired, @Resource
     */
    @Resource
    private StudentService service;

    @RequestMapping(value = "/addStudent")
    public ModelAndView addStudents(Student student) {
        System.out.println("执行addStudents方法");
        ModelAndView addMV = new ModelAndView();

        /*调用service,处理业务逻辑,把处理结果返回给用户*/
        int rows = service.addStudent(student);

        String msg = "注册失败!!!";
        if (rows > 0) {
            /*注册成功, 给用户成功的数据和视图*/
            msg = "注册成功的";
        }
        addMV.addObject("msg", student.getName() + "," + msg);
        addMV.setViewName("show");

        return addMV;
    }

    @RequestMapping(value = "/deleteStudent")
    public ModelAndView deleteStudent(String name) {
        System.out.println("执行deleteStudent方法");
        ModelAndView deleteMV = new ModelAndView();

        /*调用service,处理业务逻辑,把处理结果返回给用户*/
        int rows = service.deleteStudent(name);

        String msg = "删除失败!!!";
        if (rows > 0) {
            /*删除成功, 给用户成功的数据和视图*/
            msg = "删除成功";
        }
        deleteMV.addObject("msg", name + "," + msg);
        deleteMV.setViewName("show");

        return deleteMV;
    }

    @RequestMapping(value = "/updateStudent")
    public ModelAndView updateStudent(Student student) {
        System.out.println("执行updateStudent方法");
        ModelAndView updateMV = new ModelAndView();

        /*调用service,处理业务逻辑,把处理结果返回给用户*/
        int rows = service.updateStudent(student);

        String msg = "更改失败!!!";
        if (rows > 0) {
            /*更改成功, 给用户成功的数据和视图*/
            msg = "更改成功";
        }
        updateMV.addObject("msg", student.getName() + "," + msg);
        updateMV.setViewName("show");

        return updateMV;
    }

    @RequestMapping(value = "/queryStudent")
    @ResponseBody
    public List<Student> queryStudents() {
        System.out.println("执行queryStudents方法");
        List<Student> students = service.queryStudents();
        return students;
    }
}

7、创建视图文件, 各种jsp

1)首页index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>

    <div align="center">
        <p>SSM整合例子</p>
        <table>
            <tr>
                <td><a href="affair/addStudent.jsp">注册学生信息</a> </td>
                <td>&nbsp;&nbsp;</td>
                <td><a href="affair/deleteStudent.jsp">删除学生信息</a> </td>
            </tr>
            <tr>
                <td><a href="affair/updateStudent.jsp">修改学生信息</a> </td>
                <td>&nbsp; &nbsp;</td>
                <td><a href="affair/listStudent.jsp">查看学生信息</a> </td>
            </tr>
        </table>
    </div>

</body>
</html>

2)增删改查处理界面:
addStudent.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加学生信息</title>

</head>
<body>

    <div align="center">
        <a href="http://localhost:8080/demoSSM/index.jsp">首页</a>
        <p>注册学生信息</p>
        <form action="http://localhost:8080/demoSSM/student/addStudent" 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>操作:</td>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </div>

</body>
</html>

deleteStudent.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>删除学生信息</title>
</head>
<body>

<div align="center">
    <a href="http://localhost:8080/demoSSM/index.jsp">首页</a>
    <p>删除学生信息</p>
    <form action="http://localhost:8080/demoSSM/student/deleteStudent" method="post">
        <table>
            <tr>
                <td>姓名:</td>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <td>操作:</td>
                <td><input type="submit" value="提交"></td>
            </tr>
        </table>
    </form>
</div>

</body>
</html>

updateStudent.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改学生信息</title>
</head>
<body>

<div align="center">
    <a href="http://localhost:8080/demoSSM/index.jsp">首页</a>
    <p>修改学生信息</p>
    <form action="http://localhost:8080/demoSSM/student/updateStudent" 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>操作:</td>
                <td><input type="submit" value="提交"></td>
            </tr>
        </table>
    </form>
</div>

</body>
</html>

listStudent.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>查看学生信息</title>
    <script type="text/javascript" src="../static/js/jquery-3.4.1.js"></script>
    <script type="text/javascript">
        var root = "http://localhost:8080/demoSSM/"
        $(function(){
            //在页面加载后,执行ajax,获取数据
            getStudentInfo();

            $("#doAjax").click(function(){
                getStudentInfo();
            })
        })

        function getStudentInfo(){
            $.ajax({
                url: root+"student/queryStudent",
                dataType:"json",
                success:function(resp){
                    console.log(resp)
                    $("#stuinfo").empty();
                    $.each(resp,function(i,n){
                        $("#stuinfo").append(
                            "<tr><td>"+n.id+"</td><td>"
                            +n.name+"</td><td>"
                            +n.age+"</td></tr>");
                    })
                },
                error: function (error) {
                    console.log(error)
                }
            })
        }
    </script>
</head>
<body>

    <div align="center">
        <a href="http://localhost:8080/demoSSM/index.jsp">首页</a>
        <p>浏览学生 <button id="doAjax">获取学生数据</button> </p>
        <table>
            <thead>
            <tr>
                <td>id</td>
                <td>姓名</td>
                <td>年龄</td>
            </tr>
            </thead>
            <tbody id="stuinfo"> </tbody>
        </table>
    </div>
</body>
</html>

3)操作处理成功提示界面show.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>show</title>
</head>
<body>
<a href="http://localhost:8080/demoSSM/index.jsp">首页</a>
<h3>显示show.jsp:${msg}</h3>
</body>
</html>
posted @   Fridas_QF_Zhou  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示