SpringMVC實(shí)現(xiàn)與CRUD整合

》#千鋒逆戰(zhàn)#
修改使用了SpringMVC的問號傳參,刪除操作使用了路徑傳參。
對比問號傳參與路徑傳參:
? 問號傳參,需要使用問號來拼接參數(shù),在接受方,使用request.getParameter(“key”)來獲取問號所傳遞過來的值,如果數(shù)據(jù)類型不為String,還需要手動轉(zhuǎn)換。可以傳遞多個值,如果使用多個值,使用&來拼接,不會改變路徑級別
? 路徑傳參,使用路徑符號來傳遞參數(shù),優(yōu)點(diǎn),可以不用做類型轉(zhuǎn)換來直接獲取其值。
路徑傳參也可以使用統(tǒng)配規(guī)則,如果同時統(tǒng)配和具體的url都滿足,則以最具體的url來處理該請求。

代碼實(shí)現(xiàn):

Emp.java

package com.qfedu.bean;

public class Emp {
    private int eid;
    private String name;
    private double salary;

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Emp{");
        sb.append("eid=").append(eid);
        sb.append(", name='").append(name).append('\'');
        sb.append(", salary=").append(salary);
        sb.append('}');
        return sb.toString();
    }

    public Emp() {
    }

    public Emp(int eid, String name, double salary) {
        this.eid = eid;
        this.name = name;
        this.salary = salary;
    }

    public int getEid() {
        return eid;
    }

    public void setEid(int eid) {
        this.eid = eid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

EmpController.java

RequestMapping
可以通過method來區(qū)分不同的請求方式
@RequestMapping(value = “/updateEmp”, method = RequestMethod.POST)代表處理post請求
@RequestMapping(value = “/updateEmp”, method = RequestMethod.GET)代表處理get請求
GETMapping,可以簡化代碼,專門用來處理get請求(4.3以后的Spring版本可用)

PostMapping,可以簡化代碼,專門用來處理post請求(4.3以后的Spring版本可用)

package com.qfedu.controller;

import com.qfedu.bean.Emp;
import com.qfedu.service.EmpService;
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 EmpService empService = new EmpServiceImpl();
    @RequestMapping("/emps")
    public String getUserPage(Model model, HttpSession session){

        List<Emp> list = empService.getAllEmps();
        model.addAttribute("list",list);
        session.setAttribute("list",list);
        return "users.jsp";
    }
    @RequestMapping("/getEmpById")
    public String getEmpById(HttpServletRequest request,Model model){
        String seid = request.getParameter("eid");

        int eid=seid==null?0:Integer.parseInt(seid);
        Emp emp = empService.getEmpById(eid);
        model.addAttribute("emp",emp);
        return "updateEmp.jsp";
    }
    //@RequestMapping("/updateEmp")
    @PostMapping("/updateEmp")
    public String updateEmp(Emp emp){
        boolean flg = empService.updateEmp(emp);
        if (flg) {
            return "redirect:/emp/emps";
        }
        return "";
    }
    @GetMapping("/deleteById/{eid}")
    public  String deleteById(@PathVariable int eid){


        boolean flg = empService.deleteById(eid);
        if(flg) {
            return "redirect:/emp/emps";
        }
        return "";
    }
}

EmpService.java

package com.qfedu.service;

import com.qfedu.bean.Emp;

import java.util.List;

public interface EmpService {
    List<Emp> getAllEmps();

    Emp getEmpById(int eid);

    boolean updateEmp(Emp emps);

    boolean deleteById(int eid);
}

EmpServiceImpl.java

package com.qfedu.service.impl;

import com.qfedu.bean.Emp;
import com.qfedu.dao.EmpDao;
import com.qfedu.dao.impl.EmpDaoImpl;
import com.qfedu.service.EmpService;

import java.util.List;

public class EmpServiceImpl implements EmpService {
    private EmpDao empDao = new EmpDaoImpl();
    @Override
    public List<Emp> getAllEmps() {
        return empDao.getAllEmps();
    }

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

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

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

EmpDao.java

package com.qfedu.dao;

import com.qfedu.bean.Emp;

import java.util.List;

public interface EmpDao {

    List<Emp> getAllEmps();

    Emp getEmpById(int eid);

    boolean updateEmp(Emp emps);

    boolean deleteById(int eid);

}

EmpDaoImpl.java

package com.qfedu.dao.impl;

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

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

public class EmpDaoImpl implements EmpDao {
    private static List<Emp> emp = new ArrayList();
    
    static {
        for (int i = 0; i < 50; i++) {
            emp.add(new Emp(i+1,"name"+i,8900+i*100));
        }
    }
    @Override
    public List<Emp> getAllEmps() {
        return emp;
    }
    @Override
    public Emp getEmpById(int eid) {
        return emp.get(eid-1);
    }

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

    @Override
    public boolean deleteById(int eid) {
        try {

            emp.remove(eid-1);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}

user.jsp

<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/getEmpById?eid=${e.eid}">update</a>&nbsp;<a href="/emp/deleteById/${e.eid}">delete</a></td>
            </tr>
        </c:forEach>
    </table>
</c:if>

updateEmp.jsp

<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/>
    <input type="submit" value="submit"/><br/>
</form>

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


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <!--<property name="suffix" value=".jsp" />-->
    </bean>
    <!--過濾靜態(tài)資源-->
    <mvc:default-servlet-handler />
    <!--上下文組件掃描-->
    <context:component-scan base-package="com.qfedu.controller"/>
    <!--配置注解驅(qū)動-->
    <mvc:annotation-driven/>
    <!--bean 的id 屬性值不能包含特殊字符
        name可以,所以路徑需要name來標(biāo)識一個控制器的路徑
        指定name對應(yīng)的路徑交給哪個控制器來進(jìn)行具體處理
    -->
    <bean name="/ProductInput" class="com.qfedu.controller.ProductInputController"/>
    <bean name="/SaveProductController" class="com.qfedu.controller.SaveProductController"/>
</beans>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容