ssm搭建簡單web項目實現CURD


在之前已經對spring,spring-mvc,mybatis等框架有了了解,spring整合mybatis也進行了練習,ssm框架就是這三種框架的簡稱,那么我們如何使用這三種框架來設計web項目呢?

今天就簡單的使用ssm框架搭建web項目,實現增刪改查等基本操作:

maven搭建web項目

導入需要使用的依賴文件:

<dependencies>
        <!--核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

        <!--數據連接包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--事務包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
pom

創建數據庫,實體;

package com.zs.entity;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Emp {
    private int empno;
    private String ename;
    private String job;
    private int deptno;
    private double sal;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date hiredate;

    public Emp() {
    }

    public Emp(int empno, String ename, String job, int deptno, double sal, Date hiredate) {
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.deptno = deptno;
        this.sal = sal;
        this.hiredate = hiredate;
    }

    public int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", deptno=" + deptno +
                ", sal=" + sal +
                ", hiredate=" + hiredate +
                '}';
    }
}
實體類

dao層:

package com.zs.dao;

import com.zs.entity.Emp;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface IEmpDao {

    /**
     * 查詢員工,條件查詢/所有
     * @return
     */
    List<Emp> listEmp(@Param("empno") Integer empno);

    /**
     * 插入
     * @param emp
     * @return
     */
    int insertEmp(Emp emp);

    /**
     * 修改
     * @param emp
     * @return
     */
    int updateEmp(Emp emp);

    /**
     * 刪除
     * @param empno
     * @return
     */
    int deleteEmp(int empno);
}
dao接口

mapper文件:

<!DOCTYPE mapper PUBLIC "-//mybatis.org// Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zs.dao.IEmpDao">

    <select id="listEmp" resultType="Emp">
        select * from emp
        <where>
            <if test="empno!=null">
                and empno=#{empno}
            </if>
        </where>
    </select>

    <insert id="insertEmp" parameterType="Emp">
        insert into emp(ename,job,deptno,sal,hiredate) value(#{ename},#{job},#{deptno},#{sal},#{hiredate})
    </insert>

    <update id="updateEmp" parameterType="Emp">
        update emp set ename=#{ename},job=#{job},deptno=#{deptno},sal=#{sal},hiredate=#{hiredate} where empno=#{empno}
    </update>

    <delete id="deleteEmp" >
        delete from emp where empno=#{empno}
    </delete>
</mapper>
mapper

以上的文件都可以采用mybatis插件自動生成

service接口及實現類

package com.zs.service;

import com.zs.entity.Emp;
import org.springframework.stereotype.Service;

import java.util.List;

public interface EmpService {
    /**
     * 查詢所有
     * @return
     */
    List<Emp> listEmp(Integer empno);

    /**
     * 插入
     * @param emp
     * @return
     */
    boolean insertEmp(Emp emp);

    /**
     * 修改
     * @param emp
     * @return
     */
    boolean updateEmp(Emp emp);

    /**
     * 刪除
     * @param empno
     * @return
     */
    boolean deleteEmp(int empno);
}
service接口
package com.zs.service;

import com.zs.dao.IEmpDao;
import com.zs.entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private IEmpDao empDao;
    @Override
    public List<Emp> listEmp(Integer empno) {
        return empDao.listEmp(empno);
    }

    @Override
    public boolean insertEmp(Emp emp) {
        return empDao.insertEmp(emp)>0;
    }

    @Override
    public boolean updateEmp(Emp emp) {
        return empDao.updateEmp(emp)>0;
    }

    @Override
    public boolean deleteEmp(int empno) {
        return empDao.deleteEmp(empno) > 0;
    }
}
實現類

控制器:

package com.zs.controller;

import com.zs.entity.Emp;
import com.zs.service.EmpService;
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
public class EmpController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/list.action")
    private String show(Model model) {
        List<Emp> emps = empService.listEmp(null);
        model.addAttribute("emps", emps);
        return "listEmp";
    }

    @RequestMapping("/insert.action")
    private String insert(Emp emp) {

        boolean b = empService.insertEmp(emp);
        return "redirect:/list.action";
    }

    @RequestMapping("/getEmp.action")
    public String getByEmpno(int empno,Model model) {
        List<Emp> emps = empService.listEmp(empno);
        model.addAttribute("emp", emps.get(0));
        return "update";
    }
    @RequestMapping("/update.action")
    private String update(Emp emp) {
        boolean b = empService.updateEmp(emp);
        return "redirect:/list.action";
    }

    @RequestMapping("/delete.action")
    private String delete(int empno) {
        boolean b = empService.deleteEmp(empno);
        return "redirect:/list.action";
    }

    @RequestMapping("/add.action")
    public String insert() {
        return "insert";
    }
}
controller

配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
<?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"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--掃描包-->
    <context:component-scan base-package="com.zs"/>
    <!--加載數據庫配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置連接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>
    <!--配置mybatis工廠-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.zs.entity"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--配置mapper映射dao接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zs.dao"/>
    </bean>

    <!--spring事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--啟用事務注解配置-->
    <tx:annotation-driven/>
</beans>
applicationContext
<?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.zs.controller"/>
    <!--spring-mvc簡易配置-->
    <mvc:annotation-driven/>
    <!--默認不攔截靜態資源-->
    <mvc:default-servlet-handler/>
    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
spring-mvc
<?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">

    <!--配置spring工廠監聽器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置servlet,默認將指定請求交給spring-mvc處理-->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <!--設置過濾器,將請求的數據格式轉為utf-8,針對post請求的亂碼問題-->
    <filter>
        <filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
web.xml

頁面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fm" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/8/7
  Time: 15:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table cellspacing="1" border="1" style="text-align: center">
    <tr>
        <th>編號</th>
        <th>姓名</th>
        <th>工作</th>
        <th>部門</th>
        <th>工資</th>
        <th>入職日期</th>
        <th>操作</th>
    </tr>
    <tbody>
    <c:forEach items="${emps}" var="emp" varStatus="i">
        <tr>
            <td>${i.count}</td>
            <td>${emp.ename}</td>
            <td>${emp.job}</td>
            <td>${emp.deptno}</td>
            <td>${emp.sal}</td>
            <td><fm:formatDate value="${emp.hiredate}" pattern="yyyy-MM-dd"/></td>
            <td>
                <a href="getEmp.action?empno=${emp.empno}">修改</a>
                <a href="delete.action?empno=${emp.empno}">刪除</a>
                <a href="add.action">插入</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>

</body>
</html>
View Code
<%@ taglib prefix="fm" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/8/7
  Time: 16:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="update.action" method="post">
    <input type="hidden" value="${emp.empno}" name="empno"/>
    姓名<input type="text" value="${emp.ename}" name="ename"/><br/>
    工作<input type="text" value="${emp.job}" name="job"/><br/>
    部門<input type="text" value="${emp.deptno}" name="deptno"/><br/>
    工資<input type="text" value="${emp.sal}" name="sal"/><br/>
    入職日期<input type="date" value="<fm:formatDate value="${emp.hiredate}" pattern="yyyy-MM-dd"/>" name="hiredate"/><br/>
    <input type="submit">
</form>
</body>
</html>
View Code

運行tomcat測試

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM