SpringMVC實(shí)現(xiàn)與CRUD整合
說明,該demo中使用List模擬了一套數(shù)據(jù)源,可以實(shí)現(xiàn)簡單的crud操作,其中修改使用了SpringMVC的問號(hào)傳參,刪除操作使用了路徑傳參。
對(duì)比問號(hào)傳參與路徑傳參:
? 問號(hào)傳參,需要使用問號(hào)來拼接參數(shù),在接受方,使用request.getParameter(“key”)來獲取問號(hào)所傳遞過來的值,如果數(shù)據(jù)類型不為String,還需要手動(dòng)轉(zhuǎn)換??梢詡鬟f多個(gè)值,如果使用多個(gè)值,使用&來拼接,不會(huì)改變路徑級(jí)別
? 路徑傳參,使用路徑符號(hào)來傳遞參數(shù),優(yōu)點(diǎn),可以不用做類型轉(zhuǎn)換來直接獲取其值。
? 路徑傳參也可以使用統(tǒng)配規(guī)則,如果同時(shí)統(tǒng)配和具體的url都滿足,則以最具體的url來處理該請(qǐng)求。
Emp.java
package com.qfedu.bean;
public class Emp {
private int eid;
private String name;
private double salary;
public Emp() {
}
public Emp(int eid, String name, double salary) {
this.eid = eid;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", name='" + name + '\'' +
", 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ū)分不同的請(qǐng)求方式
@RequestMapping(value = “/updateEmp”, method = RequestMethod.POST)代表處理post請(qǐng)求
@RequestMapping(value = “/updateEmp”, method = RequestMethod.GET)代表處理get請(qǐng)求
GETMapping,可以簡化代碼,專門用來處理get請(qǐng)求(4.3以后的Spring版本可用)
PostMapping,可以簡化代碼,專門用來處理post請(qǐng)求(4.3以后的Spring版本可用)
PathVariable路徑傳參的注解,可以實(shí)現(xiàn)路徑傳參。
package com.qfedu.controller;
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請(qǐng)求,那么該方法會(huì)被調(diào)用,返回值為將來要渲染的頁面
* @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(HttpServletRequest request){
public String updateEmp(Emp e){
//System.out.println(request.getParameter("eid"));
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 "";
}
}
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);
}
EmpServiceImpl.java
package com.qfedu.service.impl;
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);
}
}
IEmpDao.java
package com.qfedu.dao;
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);
}
EmpDaoImpl.java
package com.qfedu.dao.impl;
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;
}
}
emp.jsp
<%--
Created by IntelliJ IDEA.
User: james
Date: 2020/3/3
Time: 4:04 PM
To change this template use File | Settings | File Templates.
--%>
<%@ 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> ${e.eid}</td>
<td> ${e.name}</td>
<td> ${e.salary}</td>
<td> <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>
updateEmp.jsp
<%--
Created by IntelliJ IDEA.
User: james
Date: 2020/3/3
Time: 4:39 PM
To change this template use File | Settings | File Templates.
--%>
<%@ 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>
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/,那么控制器那邊會(huì)在虛擬視圖前拼接該字符串
suffix:.jsp .html,那么控制器那邊會(huì)在虛擬視圖后面拼接該字符串
拼接完字符串的效果
/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處理器,靜態(tài)資源可以直接被訪問-->
<mvc:default-servlet-handler />
<!--
上下文的組件掃描
-->
<context:component-scan base-package="com.qfedu.controller" />
<!--
配置注解驅(qū)動(dòng)
-->
<mvc:annotation-driven />
<!--
bean的id屬性值不能包含特殊字符
name可以,所以路徑需要使用name來標(biāo)識(shí)一個(gè)控制器的路徑
指定name對(duì)應(yīng)路徑交給哪個(gè)控制器來進(jìn)行具體的處理
-->
<bean name="/ProductInput" class="com.qfedu.controller.ProductInputController" />
<bean name="/SaveProductController" class="com.qfedu.controller.SaveProductController" />
</beans>