SpringMVC实现与CRUD整合

一.介绍:

本次代码中使用List模拟了一套数据源,可以实现简单的crud操作,其中修改使用了SpringMVC的问号传参,删除操作使用了路径传参。

1.问号传参与路径传参

(1)问号传参:需要使用问号来拼接参数,在接收方,使用request.getParameter(“key”)来获取问号所传递过来的值,如果数据类型不为String,还需要手动转换。可以传递多个值,如果使用多个值,使用&来拼接,不会改变路径级别.
(2)路径传参:使用路径符号来传递参数,优点,可以不用做类型转换来直接获取其值.路径传参也可以使用统配规则,如果同时统配和具体的url都满足,则以最具体的url来处理该请求。

二.MVC实现与CURD整合

1.注解

(1)RequestMapping:
可以通过method来区分不同的请求方式:
处理post请求:
@RequestMapping(value = “/updateEmp”, method = RequestMethod.POST)
处理get请求:
@RequestMapping(value = “/updateEmp”, method = RequestMethod.GET)
(2)GETMapping,可以简化代码,专门用来处理get请求(4.3以后的Spring版本可用)
(3)PostMapping,可以简化代码,专门用来处理post请求(4.3以后的Spring版本可用)
(4)PathVariable路径传参的注解,可以实现路径传参

2.EmpController.java

以下为代码的具体实现:

import com.qfedu.bean.Emp;
import com.qfedu.service.IEmpService;
import com.qfedu.service.impl.EmpServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {

    private IEmpService empService = new EmpServiceImpl();
    /**
     * 如果有了users请求,那么该方法会被调用,返回值为将来要渲染的页面
     * @return
     */
    @RequestMapping("/emps")
    public String getUsersPage(Model model, HttpSession session){
        List<Emp> list = empService.getAllEmps();
        model.addAttribute("list", list);
        session.setAttribute("list",  list);
        return "emp.jsp";
    }

    @RequestMapping("/getEmpByEid")
    public String getEmpByEid(HttpServletRequest request, Model model){
        String seid = request.getParameter("eid");
        int eid = seid == null ? -1 : Integer.parseInt(seid);
        Emp emp = empService.getEmpByEid(eid);
        model.addAttribute("emp", emp);
        return "updateEmp.jsp";
    }

    //@RequestMapping(value = "/updateEmp", method = RequestMethod.POST)
    @PostMapping("/updateEmp")
    public String updateEmp(Emp e){
        System.out.println(e);
        boolean flag = empService.updateEmp(e);
        if(flag){
            return "redirect:/emp/emps";
        }
        return "";
    }

    @GetMapping("/deleteByEid/{eid}")
    public String deleteByEid(@PathVariable int eid){
        //System.out.println(eid);

        boolean flag = empService.deleteEmpByEid(eid);

        if(flag){
            return "redirect:/emp/emps";
        }
        return "";
    }
}

3. IEmpService.java

package com.qfedu.service;

import com.qfedu.bean.Emp;

import java.util.List;

public interface IEmpService {

    List<Emp> getAllEmps();

    Emp getEmpByEid(int eid);

    boolean updateEmp(Emp emp);

    boolean deleteEmpByEid(int eid);
}

4. EmpServiceImpl.java

import com.qfedu.bean.Emp;
import com.qfedu.dao.impl.EmpDaoImpl;
import com.qfedu.dao.IEmpDao;
import com.qfedu.service.IEmpService;

import java.util.List;

public class EmpServiceImpl implements IEmpService {

    private IEmpDao empDao = new EmpDaoImpl();

    @Override
    public List<Emp> getAllEmps() {
        return empDao.getAllEmps();
    }

    @Override
    public Emp getEmpByEid(int eid) {
        return empDao.getEmpByEid(eid);
    }

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

    @Override
    public boolean deleteEmpByEid(int eid) {
        return empDao.deleteEmpByEid(eid);
    }
}

5. IEmpDao.java

import com.qfedu.bean.Emp;

import java.util.List;

public interface IEmpDao {

    List<Emp> getAllEmps();

    Emp getEmpByEid(int eid);

    boolean updateEmp(Emp emp);

    boolean deleteEmpByEid(int eid);
}

6.EmpDaoImpl.java

import com.qfedu.bean.Emp;
import com.qfedu.dao.IEmpDao;

import java.util.ArrayList;
import java.util.List;

public class EmpDaoImpl implements IEmpDao {
    private static List<Emp> emps = new ArrayList<>();
    static {
        for(int i = 0; i < 20; i++){
            emps.add(new Emp(i + 1, "name " + i, 8000 + i * 100));
        }
    }

    @Override
    public List<Emp> getAllEmps() {
        return emps;
    }

    @Override
    public Emp getEmpByEid(int eid) {
        return emps.get(eid - 1);
    }

    @Override
    public boolean updateEmp(Emp emp) {
        try{
            emps.set(emp.getEid() - 1, emp);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean deleteEmpByEid(int eid) {
        try{
            emps.remove(eid -1 );
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}

7.emp.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>user</title>
</head>
<body>
    <h1>this is users page.</h1>

    <c:if test="${list != null}">
        <table border="1" align="center" width="80%">
            <tr>
                <th>eid</th>
                <th>name</th>
                <th>salary</th>
                <th>manage</th>
            </tr>

            <c:forEach items="${list}" var="e">
                <tr>
                    <td>&nbsp; ${e.eid}</td>
                    <td>&nbsp; ${e.name}</td>
                    <td>&nbsp; ${e.salary}</td>
                    <td>&nbsp; 
                        <a href="/emp/getEmpByEid?eid=${e.eid}">update</a> 
                        <a href="/emp/deleteByEid/${e.eid}">delete</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </c:if>
</body>
</html>

8. updateEmp.jsp

该页面是进行数据更新的页面,但是不涉及到数据库的交互,所以数据只能更新,无法显示.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>update Emp</title>
</head>
<body>
    <h1>this is emp update page.</h1>

    <form method="post" action="/emp/updateEmp">
        eid:<input type="text" name="eid" value="${emp.eid}" readonly="readonly" /><br />
        name:<input type="text" name="name" value="${emp.name}" /><br />
        salary:<input type="text" name="salary" value="${emp.salary}" /><br />
        <%--salary:<input type="text" name="birth.year" value="${emp.salary}" /><br />--%>
        <input type="submit" value="submit" /><br />
    </form>
</body>
</html>

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

    <!--
        配置SpringMVC的视图解析器
            可以分别指定前缀和后缀
                prefix: /WEB-INF/view/,那么控制器那边会在虚拟视图前拼接该字符串
                suffix:.jsp .html,那么控制器那边会在虚拟视图后面拼接该字符串
                拼接完字符串的效果
                    /WEB-INF/view/index.html
                    /WEB-INF/view/detail.jsp
        -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <!--<property name="suffix" value=".jsp" />-->
    </bean>

    <!--配置缺省的servlet处理器,静态资源可以直接被访问-->
    <mvc:default-servlet-handler />

    <!--
        上下文的组件扫描
    -->
    <context:component-scan base-package="com.qfedu.controller" />

    <!--
        配置注解驱动
    -->
    <mvc:annotation-driven />

    <!--
        bean的id属性值不能包含特殊字符
        name可以,所以路径需要使用name来标识一个控制器的路径
            指定name对应路径交给哪个控制器来进行具体的处理
    -->
    <bean name="/ProductInput" class="com.qfedu.controller.ProductInputController" />
    <bean name="/SaveProductController" class="com.qfedu.controller.SaveProductController" />
</beans>

今天是我在千峰线上学习的18天,加油!!!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 绕过树的眼神 风吹起凋零的落叶 不去管什么方向 反正带走的也是枯萎 被季节染黄的树叶 也许曾经怕过风 但害怕渐渐变...
    忧蓝蓝阅读 1,738评论 0 17
  • 一千个人的心中,或许会有一千个自己的倒影。而我,希望在你的眼里,能看见一个特别的我。 即使知道他对自己毫无...
    绾月小仙女阅读 3,624评论 0 0
  • 今天在书房继续看《乌合之众》这本书,虽然本书内容不多,但读起来相对枯燥,也不是很好懂,只好一遍一遍的精读,我...
    禾苗青青阅读 6,940评论 0 3
  • day 1 - Drum kit T: 2017-01-07Drum kit 视频地址主要知识点有: classL...
    JamesSawyer阅读 2,880评论 0 0

友情链接更多精彩内容