1. 程式人生 > >詳細記錄->使用Maven+SSM框架,實現單表簡單的增刪改查

詳細記錄->使用Maven+SSM框架,實現單表簡單的增刪改查

       話不多說,ssm框架整合小列子,這次記錄一個單表增刪改查的ssm例子,所以才手寫mapper,平時我都是用逆向工程自動生成mapper,簡單方便。

需要了解逆向工程請看:https://blog.csdn.net/Destiny_strive/article/details/82915354

 

步驟

1.建立web Maven專案

2.建立資料庫配置檔案:jdbc.properties

3.專案總體目錄:

4.新增spring配置檔案:applicationContext.xml

5.新增springMVC配置檔案:springMVC.xml

6.修改web.xml

7.建立資料庫相關表

8.根據資料庫表建立pojo類:User.java

9.編寫dao層->mapper介面和xml檔案 :UserMapper.java、UserMapper.xml

10.編寫service層->UserService.java、UserServiceImpl.java

11.編寫controller層->UserController.java

12.在jsp資料夾下建立edit.jsp和view.jsp

13.現在配置tomcat執行就能看到user表的列表了,可操作做增刪改查


1.建立web Maven專案

建立專案很簡單的,不做描述,接下來在pom檔案加入專案所需依賴:

<dependencies>
    <!--Spring框架核心庫 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <!-- Spring Web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <!--連線驅動-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
    <!--資料來源-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
    <!-- mybatis ORM框架 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>
    <!--mybatis-spring介面卡 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!--整合mybatis如果不加這個包會報錯 java.lang.NoClassDefFoundError: org/springframewor-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
    <!--測試-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--引入JSTL標籤-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

  </dependencies>

2.建立資料庫配置檔案:jdbc.properties

resources目錄下新增:jdbc.properties

這裡根據自己資料庫做相應修改

#資料庫配置檔案
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=admin

3.專案總體目錄:

先給出專案總體目錄

建立好java目錄下的分層的包,resources下建立存放mapper的包,WEB-INF下建立jsp放跳轉的頁面(下面的配置檔案中會配置這些路徑)

4.新增spring配置檔案:applicationContext.xml

resources目錄下新增: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 匯入資料庫配置檔案 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 掃描包  這裡的包需要根據自己java目錄下的包名修改 -->
    <context:component-scan base-package="com.demo.service" />
    <!-- 配置資料庫連線池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本屬性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

    </bean>

    <!--Mybatis的SessionFactory配置-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="typeAliasesPackage" value="com.demo.pojo" />
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>

    </bean>

    <!--Mybatis的Mapper檔案識別-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.demo.dao"/>
    </bean>

</beans>

5.新增springMVC配置檔案:springMVC.xml

resources目錄下新增:springMVC.xml,並且根據檔案中‘檢視定位’的配置,所以在WEB-INF下建立jsp資料夾

檔案內容如下:

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


    <context:component-scan base-package="com.demo.controller" />
    <!--
        配置如果沒有<mvc:annotation-driven/>,
        那麼所有的Controller可能就沒有解析,所有當有請求時候都沒有匹配的處理請求類,
        就都去<mvc:default-servlet-handler/>即default servlet處理了。
        新增上<mvc:annotation-driven/>後,
        相應的do請求被Controller處理,而靜態資源因為沒有相應的Controller就會被default servlet處理。
        總之沒有相應的Controller就會被default servlet處理就ok了。
    -->
    <mvc:annotation-driven />
    <!--開通靜態資源的訪問-->
    <mvc:default-servlet-handler />

    <!-- 檢視定位 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

6.修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

  <!-- spring的配置檔案-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath: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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring mvc核心:分發servlet -->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- spring mvc的配置檔案 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

7.建立資料庫相關表

我的jdbc.properties檔案中指明瞭資料庫名為test,在test資料庫下我建立了一張user表,結構和資料如下:

8.根據資料庫表建立pojo類:User.java

pojo的編寫規則:資料庫欄位對應類欄位,欄位型別要一直 。

package com.demo.pojo;

public class User {
    private Integer id;
    private String name;
    private String password;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    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 == null ? null : name.trim();
    }
    
}

9.編寫dao層->mapper介面和xml檔案 :UserMapper.java、UserMapper.xml

UserMapper.xml放在resources\mapper下,UserMapper.java放在com.demo.dao這個包下:

注意namespace="com.demo.dao.UserMapper",這裡一定寫對應的mapper介面具體路徑

UserMapper介面的編寫規則:

  (1)方法名和對應的mapper配置檔案中查詢語句的id相同

(2)返回型別和resultType的型別一致,沒有就是void。

(3)方法中的引數列表中的型別和parameterType一致。

(4)mapper配置檔案的namespace對應mapper介面類的全路徑。

package com.demo.dao;

import com.demo.pojo.User;

import java.util.List;

public interface UserMapper {

    List<User> list();

    void del(int id);

    void update(User user);

    void add(User user);

    User get(int id);

}
<?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.demo.dao.UserMapper" >

  <select id="list" resultType="user">
    select * from user
  </select>

  <update id="update" parameterType="user">
     update user set name=#{name} ,password=#{password} where id=#{id}
  </update>

  <insert id="add" parameterType="user">
     insert into user values (null,#{name},#{password});
  </insert>

  <delete id="del">
    delete from user where id=#{id}
  </delete>

  <select id="get" resultType="user">
    select * from user where id =#{id}
  </select>

</mapper>

10.編寫service層->UserService.java、UserServiceImpl.java

UserService.java:

package com.demo.service;

import com.demo.pojo.User;

import java.util.List;

public interface UserService {

    List<User> list();
    void delUser(int id);
    void updateUser(User user);
    void addUser(User user);
    User get(int id);

}

UserServiceImpl.java

package com.demo.service.impl;

import com.demo.dao.UserMapper;
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;
    public List<User> list() {
        return userMapper.list();
    }
    public void addUser(User user) {
        userMapper.add(user);
    }
    public void delUser(int id) {
        userMapper.del(id);
    }
    public void updateUser(User user) {
        userMapper.update(user);
    }
    public User get(int id) {
        return userMapper.get(id);
    }


}

11.編寫controller層->UserController.java

package com.demo.controller;

import com.demo.pojo.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("")
public class UserController {

    @Autowired
    UserService userService;
    @RequestMapping("list")
    public String list(Model model){
        List<User> us= userService.list();
        model.addAttribute("us", us);
        return "view";
    }
    @RequestMapping("add")
    public String add(User user,Model model){
       userService.addUser(user);
        return "redirect:list";
    }
    @RequestMapping("del")
    public String del(int id){
        userService.delUser(id);
        return "redirect:list";
    }
    @RequestMapping("editUI")
    public String editUI(int id,Model model){
        User user = userService.get(id);
        model.addAttribute("user",user);
        return "edit";
    }
    @RequestMapping("update")
    public String update(User user){
        userService.updateUser(user);
        return "redirect:list";
    }

}

12.在jsp資料夾下建立edit.jsp和view.jsp

view.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <style>
        table,table tr th, table tr td { border:1px solid rgba(41, 36, 35, 0.96); }
        #mytable{width:300px;margin: 100px auto}
        #add{width:300px;height:500px;margin: 100px auto}
    </style>
</head>
<body>
<div id="list">
    <table id="mytable">
        <thead>
        <th>id</th>
        <th>名字</th>
        <th>密碼</th>
        <th>修改</th>
        <th>刪除</th>
        </thead>
        <tbody>
        <c:forEach items="${us}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.password}</td>
                <td><a href="editUI?id=${user.id}">edit</a> </td>
                <td><a href="del?id=${user.id}">delete</a></td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
</div>

<div id="add">
    <form action="/add">
        姓名:<input type="text" name="name" value=""/><br/>
        密碼:<input type="text" name="password" value=""/><br/>
        <button type="submit">新增</button>
    </form>
</div>


</body>
</html>

edit.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style>
        #edit{width:300px;height:500px;margin: 100px auto}
    </style>
</head>
<body>
<div id="edit">
    <form action="/update">
        姓名:<input type="text" name="name" value="${user.name}"/><br/>
        密碼:<input type="text" name="password" value="${user.password}"/><br/>
        <input type="hidden" value="${user.id}" name="id">
        <button type="submit" value="">修改</button>
    </form>
</div>
</body>
</html>

最後把index.jsp內容修改為:

<%
    response.sendRedirect(request.getContextPath()+"/list");
%>

13.現在配置tomcat執行就能看到user表的列表了,可操作做增刪改查