SSM - JSP

1.什么是SSM?

两个核心配置文件web.xml,applicationContext.xml

web.xml
1.前端控制器DispatcherServlet
2.过滤器CharacterEncodingFilter

applicationContext.xml
1.扫描包 <context:component-scan base-package="cn"/>
2.mvc驱动 <mvc:annotation-driven/>
3.事务驱动 <tx:annotation-driven transaction-manager="txManager"/>
4.配置数据源
5.SqlSessionFactoryBean
6.配置事务
7.数据映射器
8.视图解析器

2.案例

2.1 数据库

CREATE TABLE `t_student` (
  `sid` int(32) NOT NULL AUTO_INCREMENT,
  `sname` varchar(32) DEFAULT NULL,
  `spwd` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

默认就是InnoDB 引擎 所以可以不写

INSERT INTO `t_student` VALUES ('1', 'zs', '123');
INSERT INTO `t_student` VALUES ('2', 'lisi', '555');
INSERT INTO `t_student` VALUES ('3', 'wangwu', '666');

2.2 创建maven工程,目录 ,js(jquery-1.8.3-min.js)

(二八原则)如下

2.3 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<!--过滤器 字符集编码-->
<!--   前端控制器 *处理器-->
    <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:applicationContext.xml</param-value>
        </init-param>
<!--        多个servlet会先执行第一个-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

2.4 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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 1.扫描包 -->
    <context:component-scan base-package="cn" />
    <!-- 2.配置两个driven,使事务的注解有效 -->
    <!--    事务驱动-->
    <tx:annotation-driven transaction-manager="txManager" />
    <!--    mvc驱动-->
    <mvc:annotation-driven />
    <!--3.配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
    <!--        可能不执行 druid 加上这个确保无误-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_student?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true" />
        <property name="username" value="root" />
        <property name="password" value="zjj" />
    </bean>
    <!-- 4.配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 5.配置事务 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 6.配置数据映射器,扫描mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
        <property name="basePackage" value="cn.kgc.mapper" />
    </bean>
    <!-- 7.视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

2.5 pom.xml

<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>
    <spring-version>4.3.7.RELEASE</spring-version>
    <jackson.version>2.5.4</jackson.version>
  </properties>
<!-- 为了防止不兼容,所以统一包的版本  -->
  <dependencies>
<!-- 1.测试依赖包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
</dependency>
<!-- 2.jstl和servlet包
(jsp页面中使用得到,前者jstl表达式会用到,后者servlet对象会用)-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
</dependency>
<!-- 3.mysql的驱动依赖包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
</dependency>
<!-- 4.mybatis依赖包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
</dependency>
<!-- 5.mybatis集成spring的依赖包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
</dependency>
<!-- 6.spring的相关依赖包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring-version}</version>
</dependency>
<!-- 7.spring的事务包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring-version}</version>
</dependency>
<!-- 8.数据源连接池依赖包 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.1</version>
    </dependency>
<!-- 9.json依赖包 --> 
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
<!-- 10.分页插件依赖包-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.6</version>
    </dependency>
  </dependencies>

2.6 Student

package cn.kgc.entity;

public class Student {
    private Integer sId;
    private String sName;
    private String sPwd;
  省略getter和setter方法
}

2.7 StudentMapper.java

package cn.kgc.mapper;
import cn.kgc.entity.Student;
import java.util.List;

public interface StudentMapper {
    //查询所有
    List<Student> findAll();
    //增加
    Integer addStudent(Student student);
    //删除
    Integer delById(Integer id);
    //修改
    Integer updateStudent(Student student);
    //通过id查询对象
    Student findById(Integer id);
}

2.8 StudentMapper.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="cn.kgc.mapper.StudentMapper">
    <select id="findAll" resultType="cn.kgc.entity.Student">
        select * from  t_student
    </select>
    <insert id="addStudent" parameterType="cn.kgc.entity.Student">
        insert into t_student(sname,spwd) values (#{sName},#{sPwd})
    </insert>
    <delete id="delById" parameterType="java.lang.Integer">
        delete from t_student where sid = #{id}
    </delete>
<!--    这边的id和前面的id对应-->
    <update id="updateStudent" parameterType="cn.kgc.entity.Student">
        update t_student set sname=#{sName},spwd=#{sPwd} where sid=#{sId}
    </update>
    <select id="findById" parameterType="java.lang.Integer" resultType="cn.kgc.entity.Student">
        select * from t_student where sid =#{id}
    </select>
</mapper>

2.9 StudentService.java

package cn.kgc.service;
import cn.kgc.entity.Student;
import java.util.List;

public interface StudentService {
    //查询所有
    List<Student> findAll();
    //增加
    Integer addStudent(Student student);
    //删除
    Integer delById(Integer id);
    //修改
    Integer updateStudent(Student student);
    //通过id查询对象
    Student findById(Integer id);
}

2.10 StudentServiceImpl.java (省略导包)

@Service
@Transactional
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public List<Student> findAll() { return studentMapper.findAll(); }

    @Override
    public Integer addStudent(Student student) { return studentMapper.addStudent(student); }

    @Override
    public Integer delById(Integer id) { return studentMapper.delById(id); }

    @Override
    public Integer updateStudent(Student student) { return studentMapper.updateStudent(student); }

    @Override
    public Student findById(Integer id) { return studentMapper.findById(id); }
}

2.11StudentController.java(省略导包)

@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/findAll.do")
    public String findAll(HttpServletRequest request){
        System.out.println("findAll.do");
        List<Student> list = studentService.findAll();
        request.setAttribute("list",list);
        return "findAll";
    }
    //第一种
    @RequestMapping("/addStudent.do")
    public String addStudent(Student student){
        studentService.addStudent(student);
        //不用写request.getParameter("xxx")
        //下面是重定向
        return "redirect:/findAll.do";
    }
    //第二种
//    @RequestMapping("/addStudent2.do")
//    public void assStudent2(Student student, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("add2*************");
//        //Integer flag = studentService.addStudent(student);
//        request.getRequestDispatcher("/findAll.do").forward(request,response);
//    }
    @RequestMapping("/delById.do")
    public String delById(Integer id){
        studentService.delById(id);
        return "redirect:/findAll.do";
    }
    @RequestMapping("/toUpdateStudent.do")
    public String toUpdateStudent(Integer id,HttpServletRequest request){
        Student student = studentService.findById(id);
        request.setAttribute("stu",student);
        return "update";
    }
    @RequestMapping("/updateStudent.do")
    public String updateStudent(Student student){
        studentService.updateStudent(student);
        return "redirect:/findAll.do";
//        return "update";
        //进入update.jsp
    }
    @RequestMapping("/findById.do")
    public String findById(Integer id,HttpServletRequest request){
        Student student = studentService.findById(id);
        request.setAttribute("student",student);
        return "findById";
    }
}

2.12 findAll.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<%--    引入类库不能有自闭结束标签,要写全--%>
</head>
<body>
    <form>
        <table border="1px solid">
            <tr>
                <td>编号</td>
                <td>名称</td>
                <td>密码</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${list}" var="stu">
                <tr>
                    <td><a href="/findById.do?id=${stu.sId}">${stu.sId}</a></td>
                    <td>${stu.sName}</td>
                    <td>${stu.sPwd}</td>
                    <td>
                        <a href="/toUpdateStudent.do?id=${stu.sId}">修改</a>
                        <a href="/delById.do?id=${stu.sId}">删除</a>
                        <%--第一个用?第二个用&--%>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </form>
</body>
</html>

2.13 add.jsp(省略开头)

<body>
    <form action="/addStudent.do" method="post">
        <table>
            <tr>
                <td>名称</td>
                <td><input type="text" name="sName"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="text" name="sPwd"></td>
            </tr>
            <tr>
                <td><input type="submit" value="提交"></td>
            </tr>
        </table>
    </form>
</body>

2.14 update.jsp(省略开头)

<form action="/updateStudent.do" method="post">
    <table border="1px solid" width="300px">
        <tr>
            <th colspan="2">修改页面</th>
        </tr>
        <input type="hidden" name="sId" value="${stu.sId}" />
        <tr>
            <td>名称:</td>
            <td><input type="text" name="sName" value="${stu.sName}"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="text" name="sPwd" value="${stu.sPwd}"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="修改" />
            </td>
        </tr>
    </table>
</form>

2.15.findById.jsp(省略开头)

<form>
    <table border="1px solid">
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>密码</td>
        </tr>
            <tr>
                <td>${student.sId}</td>
                <td>${student.sName}</td>
                <td>${student.sPwd}</td>
            </tr>
    </table>
</form>

2.16 测试

查询:
http://localhost:8080/findAll.do
SSM - JSP
中间不连贯,简化版增加:
http://localhost:8080/add.jsp
SSM - JSP

SSM - JSP
删除:
在前面基础上点击删除就删除成功(不演示了)

修改:
点击修改
http://localhost:8080/toUpdateStudent.do?id=4
SSM - JSP

SSM - JSP
通过id查询对象:
点击1就跳到对应的
http://localhost:8080/findById.do?id=1SSM - JSP

----2021.12.15&12.16

上一篇:圣诞节熬夜整理一套SSM模板,让你可以快速搭建环境


下一篇:基于SSM框架的仿天猫在线商城系统(一)