springmvc十八:RestfulCRUD增删改查小实战
生活随笔
收集整理的這篇文章主要介紹了
springmvc十八:RestfulCRUD增删改查小实战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
水滸好漢列表展示: 查詢所有好漢
? ? ?水滸好漢列表展示:訪問index.jsp---->直接發送/emps---->控制器查詢所有好漢---->將數據放在請求域中----->轉發到list頁面展示
? ? ?添加好漢: 在list頁面點擊"添加好漢"------>來到添加頁面(add.jsp)------->輸入員工數據--------->點擊保存-------->處理器收到員工保運請求(保存員工)---------->保存完成后還是來到list頁面
? ? 修改好漢信息: 點擊"edit"------>查出要修改的員工信息,放在請求域中,來到修改頁面進行回顯---------->來到edit.jsp----->數據修改完畢,將修改的數據提交給服務器 /emp/1 ?PUT?
? web工程目錄結構如下:
controller層
package com.atchina.controller;import java.util.Collection;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;import com.atchina.dao.AddressDao; import com.atchina.dao.EmployeeDao; import com.atchina.pojo.Address; import com.atchina.pojo.Employee;@Controller public class EmployeeController {@Autowiredprivate EmployeeDao employeeDao;@Autowiredpublic AddressDao addressDao;// 查詢所有數據@RequestMapping("/emps")public String getEmployees(Model model){Collection<Employee> emps = employeeDao.getEmployees();model.addAttribute("emps", emps);return "list";}// 跳轉到添加頁面add.jsp@RequestMapping("/toaddpage")public String toAddPage(Model model){// 查詢出所有地址Collection<Address> addresses = addressDao.getAddresss();// 添加到請求域中model.addAttribute("address", addresses);// 用于數據回顯model.addAttribute("employee", new Employee());return "add";}// 保存添加頁面,提價過來的數據@RequestMapping(value="/emp", method=RequestMethod.POST)public String save(Employee employee){employeeDao.save(employee);//return "forward:/emps";return "redirect:/emps";}// 查詢好漢信息@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)public String getEmp(@PathVariable("id")String id, Model model){Employee ee = employeeDao.getEmployeeById(id);// 用于數據回顯model.addAttribute("employee", ee);// 查詢出所有地址Collection<Address> addresses = addressDao.getAddresss();// 添加到請求域中model.addAttribute("address", addresses);//return "forward:/emps";return "edit";}// 修改好漢信息@RequestMapping(value="/emp/{id}", method=RequestMethod.PUT)public String updateEmp(@PathVariable("id")String id, Employee employee){Employee ee = employeeDao.getEmployeeById(id);employee.setId(id);employee.setName(ee.getName());employeeDao.save(employee);//return "forward:/emps";return "redirect:/emps";}// 刪除好漢信息@RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)public String deleteEmp(@PathVariable("id")String id){employeeDao.delete(id);//return "forward:/emps";return "redirect:/emps";} }DAO層?
package com.atchina.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import org.springframework.stereotype.Repository;import com.atchina.pojo.Address; import com.atchina.pojo.Employee;@Repository public class AddressDao {private static Map<String,Address> addresss;static{addresss = new HashMap<String,Address>();addresss.put("100", new Address("100","山東省菏澤市鄆城縣宋家村"));addresss.put("101", new Address("101","山東省菏澤市鄆城縣車市村"));addresss.put("102", new Address("102","渭州(今甘肅平涼)"));addresss.put("103", new Address("103","邢臺市清河縣"));addresss.put("104", new Address("104","陜西,華陰縣史家村"));addresss.put("105", new Address("105","扈家莊"));addresss.put("106", new Address("106","北京大名府"));addresss.put("107", new Address("107","山東鄆城縣東溪村"));}public Collection<Address> getAddresss(){return addresss.values();}public Address getgetAddressById(String id){return addresss.get(id);}private static Integer intid = 108;public void save(Address address){if(address.getAid() == null){address.setAid(intid.toString());intid++;}addresss.put(address.getAid(), address);}public void delete(String aid){addresss.remove(aid);} } package com.atchina.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;import com.atchina.pojo.Address; import com.atchina.pojo.Employee;@Repository public class EmployeeDao {private static Map<String,Employee> employees;@Autowiredprivate AddressDao addressDao;static{employees = new HashMap<String,Employee>();employees.put("1", new Employee("1","宋江",1,new Address("100","山東省菏澤市鄆城縣宋家村")));employees.put("2", new Employee("2","吳用",1,new Address("101","山東省菏澤市鄆城縣車市村")));employees.put("3", new Employee("3","魯智深",1,new Address("102","渭州(今甘肅平涼)")));employees.put("4", new Employee("4","武松",1,new Address("103","邢臺市清河縣")));employees.put("5", new Employee("5","史進",1,new Address("104","陜西,華陰縣史家村")));employees.put("6", new Employee("6","扈三娘",0,new Address("105","扈家莊")));}public Collection<Employee> getEmployees(){return employees.values();}public Employee getEmployeeById(String id){return employees.get(id);}private static Integer intid = 7;public void save(Employee employee){if(employee.getId() == null){employee.setId(intid.toString());intid++;}employee.setAddress(addressDao.getgetAddressById(employee.getAddress().getAid()));employees.put(employee.getId(), employee);}public void delete(String id){employees.remove(id);} }pojo層
package com.atchina.pojo;public class Address {private String aid;public String getAid() {return aid;}public Address() {}public Address(String aid, String aname) {super();this.aid = aid;this.aname = aname;}public void setAid(String aid) {this.aid = aid;}public String getAname() {return aname;}public void setAname(String aname) {this.aname = aname;}private String aname; } package com.atchina.pojo;public class Employee {private String id;private String name;public String getId() {return id;}public Employee() {}public Employee(String id, String name, Integer gender, Address address) {super();this.id = id;this.name = name;this.gender = gender;this.address = address;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}private Integer gender;private Address address;}springmvc配置文件
<?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:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.atchina"></context:component-scan><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/pages/"></property><property name="suffix" value=".jsp"></property></bean><!-- 靜態資源可以訪問了 --><mvc:default-servlet-handler/><mvc:annotation-driven></mvc:annotation-driven> </beans>web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><display-name></display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet><servlet-name>DispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><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>DispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 字符編碼過濾 --><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><init-param><param-name>isForceResponseEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 支持restful風格請求 --><filter><filter-name>HiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class></filter><filter-mapping><filter-name>HiddenHttpMethodFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> </web-app>jsp文件
add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'hello.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><!-- 表單標簽:通過SpringMVC的表單標簽可以實現將模型數據中的屬性和html表單元素相綁定,以實現表單數據更便捷編輯和表值的回顯.1). SpringMVC認為,表單 數據中的每一項最終都是要回顯的。path指定的是一個屬性,這個屬性是從隱含模型(請求域中取出的某個對象中屬性)path指定的每一個屬性,請求域中必須有一個對象(這個對象就是請求域中的command對應的對象),擁有這個屬性;modelAttribute="",以前我們表單標簽會從請求域中獲取一個command對象;把這個對象中的每一個屬性對應的顯示出來.modelAttribute="employee",可以告訴SpringMVC不要去取command的值了,我做了一個modelAttribute指定的值;取對象時用的key就是我modelAttribute指定的"employee"--><%=path%><%pageContext.setAttribute("ctp", request.getContextPath());%><fm:form action="${ctp}/emp" method="post" modelAttribute="employee"><!-- path就是原來html-input的name值;需要寫path 1).當做原生的name項2).自動回顯隱含模型中某個對象對應的這個屬性的值-->姓名: <fm:input path="name"/> <br/>性別: 男:<fm:radiobutton path="gender" value="1" /> 女:<fm:radiobutton path="gender" value="0" /><br/><!-- items="": 指定要遍歷的集合;自動遍歷;遍歷出的每一個元素是一個address對象itemLabel="屬性名":指定遍歷出的這個對象的哪個屬性是作為option標簽體的值itemValue="屬性名":指定剛才遍歷出來的這個對象的哪個屬性是作為要提交的value值-->地址: <fm:select path="address.aid" items="${address}" itemLabel="aname" itemValue="aid"></fm:select><br/> <input type="submit" value="提交"/> </fm:form><!-- <body><form action="emp" method="post">姓名: <input type="text" name="name"/> <br/>性別: 男:<input type="radio" name="gender" value="1"/> 女:<input type="radio" name="gender" value="0"/> <br/>地址: <select name="address.aid"><c:forEach items="${address}" var="ads"><option value="${ads.aid}">${ads.aname}</option></c:forEach></select> <br/><input type="submit" value="提交"/></form></body>--> </html>edit.jsp?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'hello.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><!-- 表單標簽:通過SpringMVC的表單標簽可以實現將模型數據中的屬性和html表單元素相綁定,以實現表單數據更便捷編輯和表值的回顯.1). SpringMVC認為,表單 數據中的每一項最終都是要回顯的。path指定的是一個屬性,這個屬性是從隱含模型(請求域中取出的某個對象中屬性)path指定的每一個屬性,請求域中必須有一個對象(這個對象就是請求域中的command對應的對象),擁有這個屬性;modelAttribute="",以前我們表單標簽會從請求域中獲取一個command對象;把這個對象中的每一個屬性對應的顯示出來.modelAttribute="employee",可以告訴SpringMVC不要去取command的值了,我做了一個modelAttribute指定的值;取對象時用的key就是我modelAttribute指定的"employee"--><%=path%><%pageContext.setAttribute("ctp", request.getContextPath());%>edit<fm:form action="${ctp}/emp/${employee.id}" method="post" modelAttribute="employee"><input type="hidden" name="_method" value="put" /><!-- path就是原來html-input的name值;需要寫path 1).當做原生的name項2).自動回顯隱含模型中某個對象對應的這個屬性的值-->姓名: <fm:label path="name">${employee.name}</fm:label> <br/>性別: 男:<fm:radiobutton path="gender" value="1" /> 女:<fm:radiobutton path="gender" value="0" /><br/><!-- items="": 指定要遍歷的集合;自動遍歷;遍歷出的每一個元素是一個address對象itemLabel="屬性名":指定遍歷出的這個對象的哪個屬性是作為option標簽體的值itemValue="屬性名":指定剛才遍歷出來的這個對象的哪個屬性是作為要提交的value值-->地址: <fm:select path="address.aid" items="${address}" itemLabel="aname" itemValue="aid"></fm:select><br/> <input type="submit" value="提交"/> </fm:form></html>list.jsp?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><%pageContext.setAttribute("ctp", request.getContextPath());%><head><base href="<%=basePath%>"><title>My JSP 'hello.jsp' starting page</title><script type="text/javascript" src="${ctp}/scripts/jquery-1.9.1.min.js"></script><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><table border="1" cellpadding="5" cellspacing="2" width="400px"><tr><th>id</th><th>名字</th><th>性別</th><th>地址</th><th>修改</th><th>刪除</th></tr><c:forEach items="${emps}" var="emp"><tr><td>${emp.id}</td><td>${emp.name}</td><td>${emp.gender==0?"女":"男"}</td><td>${emp.address.aname}</td><td><a href="emp/${emp.id}">EDIT</a></td><td><a href="emp/${emp.id}" class="delBtn">DELETE</a></td></tr></c:forEach></table><a href="toaddpage">添加好漢</a><form id="deleteForm" action="emp/${emp.id}" method="post"><input type="hidden" name="_method" value="DELETE"/></form><script type="text/javascript">$(function(){$(".delBtn").click(function(){// 1. 改變表單的action查詢$("#deleteForm").attr("action", this.href);// 2. 提交表單$("#deleteForm").submit();return false;});});</script></body> </html>index.jsp?
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>This is my JSP page. <br><a href="hello">hello</a><br><%=basePath%><br/><jsp:forward page="/emps"></jsp:forward></body> </html>?
總結
以上是生活随笔為你收集整理的springmvc十八:RestfulCRUD增删改查小实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java: jstl.jar和stand
- 下一篇: springmvc十九:springmv