1. 程式人生 > >SpringMVC:SpringMVC+mybatis實現基本操作

SpringMVC:SpringMVC+mybatis實現基本操作

SpringMVC第一次課:第一次

 

對於SpringMVC 有了一個基本的認識。

匯入SpringMVC+mybatis的依賴

spring-webmvc:springmvc核心依賴

 

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

匯入C標籤!:jstl、standard,C標籤的基本庫和方法庫

web.xml:

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

    <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>forceEncoding</param-name>
            <param-value>true</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:springmvc.xml</param-value>
        </init-param>
    </servlet>

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

    <welcome-file-list>
        <welcome-file>/students.action</welcome-file>
    </welcome-file-list>

</web-app>

配置亂碼過濾器characterEncodingFilter

DispatcherServlet:springmvc入口servlet

welcome-file:首頁

 

實體類:

具體封裝alt+insert

 

 private int stuId;
    private String stuName;
    private String stuSex;
    private int stuAge;

student對映Mapper:實現操作的SQL

cache:二級快取

concat:拼接模糊查詢的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.hc.dao.StudentDao">

    <cache></cache>

    <select id="likeStudent" resultType="Student">
        select * from student
        <where>
            <if test="likeStr!=null">
                stuName like concat('%',#{likeStr},'%') or
                stuSex like concat('%',#{likeStr},'%') or
                stuAge like concat('%',#{likeStr},'%')
            </if>
        </where>

    </select>


    <select id="selectStudent" resultType="Student" parameterType="int">
        select * from student where stuId=#{stuid}
    </select>


    <select id="allStudent" resultType="Student">
        select * from student
    </select>

    <update id="updateStudent" parameterType="Student">
        update student
        <set>
            <trim suffixOverrides=",">
                <if test="stuName!=null">
                    stuName=#{stuName},
                </if>
                <if test="stuSex!=null">
                    stuSex=#{stuSex},
                </if>
                <if test="stuAge!=null and stuAge!=0">
                    stuAge=#{stuAge},
                </if>
            </trim>
        </set>
        <if test="stuId!=null">
            where stuId=#{stuId}
        </if>
    </update>


    <delete id="deleteStudent">
        delete from student where stuId=#{stuid}
    </delete>


    <sql id="keys">
        <trim suffixOverrides=",">
            <if test="stuName!=null">
                stuName,
            </if>
            <if test="stuSex!=null">
                stuSex,
            </if>
            <if test="stuAge!=null and stuAge!=0">
                stuAge,
            </if>
        </trim>
    </sql>

    <sql id="values">
        <trim suffixOverrides=",">
            <if test="stuName!=null">
                #{stuName},
            </if>
            <if test="stuSex!=null">
                #{stuSex},
            </if>
            <if test="stuAge!=null and stuAge!=0">
                #{stuAge},
            </if>
        </trim>
    </sql>

    <insert id="insertStudent" parameterType="Student">
        insert into student(<include refid="keys"></include>) values(<include refid="values"></include>)
    </insert>

</mapper>

student的mapper會被sqlsession藉助dao的介面呼叫

 

dao介面:

動態sql的模糊查需要Map

package com.hc.dao;

import com.hc.entity.Student;
import java.util.List;
import java.util.Map;

public interface StudentDao {

    public void insertStudent(Student student);
    public void deleteStudent(int stuId);
    public void updateStudent(Student student);

    public Student selectStudent(int stuId);
    public List<Student> likeStudent(Map<String,Object> map);
    public List<Student> allStudent();
}

 

dao的實現類

定義factory ,載入mybatis配置,myBatis-config載入具體的物件Mapper

session通過factory 開啟

dao被session例項化

日後的諸如此類的載入物件,將會通過spring工廠產生

package com.hc.dao;

import com.hc.entity.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentImpl {

    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(getClass().getClassLoader().getResourceAsStream("myBatis-config.xml"));
    SqlSession session = factory.openSession();
    StudentDao studentDao = session.getMapper(StudentDao.class);

    public List<Student> allStudent() {
        List<Student> studentList=studentDao.allStudent();
        session.close();
        return studentList;
    }

    public List<Student> likeStudent(String likeStr) {
//      string:  if 判斷 需要map 無需指明傳入的參及參的型別
        Map<String,Object> map=new HashMap<>();
        map.put("likeStr",likeStr);
        List<Student> studentList=studentDao.likeStudent(map);
        session.close();
        return studentList;
    }

    public Student selectStudent(int stuId) {
        Student student= studentDao.selectStudent(stuId);
        session.close();
        return student;
    }


    public void insertStudent(Student student) {
         studentDao.insertStudent(student);
         session.commit();
         session.close();
    }
    public void deleteStudent(int stuId) {
        studentDao.deleteStudent(stuId);
        session.commit();
        session.close();
    }
    public void updateStudent(Student student) {
        studentDao.updateStudent(student);
        session.commit();
        session.close();
    }
}

封裝各個方法,以便 controller 使用

controller:

在類之上,進行controller的註解

方法:RequestMapping ,括號內的是訪問路徑,只有這個訪問路徑被允許呼叫這個方法

package com.hc.controller;

import com.hc.dao.StudentImpl;
import com.hc.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class StudentController {

    @RequestMapping("/students")
    public String allStudent(HttpServletRequest request){
        request.setAttribute("students",new StudentImpl().allStudent());
        return "success";
    }

    @RequestMapping("/likeStudent")
    public String likeStudent(@RequestParam("likeStr") String likeStr, HttpServletRequest request){
        request.setAttribute("students",new StudentImpl().likeStudent(likeStr));
        return "success";
    }

    @RequestMapping("/insertStudent")
    public String insertStudent(Student student){
        new StudentImpl().insertStudent(student);
        return "redirect:students.action";
    }

    @RequestMapping("/deleteStudent")
    public String deleteStudent(int stuId){
        new StudentImpl().deleteStudent(stuId);
        return "redirect:students.action";
    }

    @RequestMapping("/updateStudent")
    public String updateStudent(Student student){
        new StudentImpl().updateStudent(student);
        return "redirect:students.action";
    }

    @RequestMapping("/selectStudent")
    public String selectStudent(int stuId, Map map){
        map.put("student",new StudentImpl().selectStudent(stuId));
        return "first";
    }
}

redirect:轉發,一個方法調另一個方法 

 

資料展示頁面:

匯入C標籤

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/2
  Time: 19:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<a href="/students.action">students</a>
<a href="/insert.jsp">insert</a>

<div align="center">

    <form action="/likeStudent.action" method="post">

        <input type="text" name="likeStr">
        <input type="submit" value="搜尋">
    </form>


<table border="1" width="600">

    <tr align="center">
        <td>編號</td>
        <td>姓名</td>
        <td>性別</td>
        <td>年齡</td>
        <td>銷戶</td>
        <td>資料</td>
    </tr>
    <c:forEach items="${students}" var="student">

        <tr align="center">
            <td>${student.stuId}</td>
            <td>${student.stuName}</td>
            <td>${student.stuSex}</td>
            <td>${student.stuAge}</td>
            <td><a href="/deleteStudent.action?stuId=${student.stuId}" onclick="return confirm('是否刪除?')">刪除</a></td>
            <td><a href="/selectStudent.action?stuId=${student.stuId}">修改</a></td>
        </tr>
    </c:forEach>


</table>
</div>


</body>
</html>

C:foreach:可迴圈list,items是傳過來的list,var代表的是一個物件

${ }:EL表示式

注意:EL一定要在最上方宣告:  isELIgnored="false"

 

insert:

普通的表單,輸入框的name一定要與物件的屬性名一致,否則,無法自動收集

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/2
  Time: 17:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<div align="center">
<form action="/insertStudent.action" method="post">
    名字:<input type="text" name="stuName"><br><br>
    性別:<input type="text" name="stuSex"><br><br>
    年齡:<input type="text" name="stuAge"><br><br>
    <input type="submit" value="新增">
</form>
</div>
</body>
</html>

 align="center":居中

 

update:

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/11/2
  Time: 17:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<div align="center">
<form action="/updateStudent.action" method="post">
     <input type="hidden" value="${student.stuId}" name="stuId">
    名字: <input type="text" value="${student.stuName}" name="stuName"><br><br>
    性別: <input type="text" value="${student.stuSex}" name="stuSex"><br><br>
    年齡: <input type="text" value="${student.stuAge}" name="stuAge"><br><br>
    <input type="submit" value="歐克">
</form>
</div>
</body>
</html>

傳過來的是一個物件,無需C標籤,直接EL表示式即可

 

Springmvc.xml配置

mybatis-config.xml見上期

初步整合!

if 再加上Spring,就是SSM!