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 {

	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	public 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;
	
	@Autowired
	private 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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://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-app
	version="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" /> &nbsp;&nbsp;&nbsp;&nbsp;
 		   女:<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"/> &nbsp;&nbsp;&nbsp;&nbsp;
      	     女:<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" /> &nbsp;&nbsp;&nbsp;&nbsp;
 		   女:<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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
用MVC模式的实现对数据库的增删改查 部分代码: package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import common.DBConnection; import bean.Contact; public class ContactDAO { public List getAllContact() throws Exception{ Connection conn=DBConnection.getConntion(); PreparedStatement ps=conn.prepareStatement("select * from Contact"); ResultSet rs=ps.executeQuery(); List list = new ArrayList(); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String phone = rs.getString("phone"); String address = rs.getString("address"); Contact c = new Contact(); c.setId(id); c.setName(name); c.setPhone(phone); c.setAddress(address); list.add(c); } rs.close(); ps.close(); conn.close(); return list; } public void addContact(String name,String phone,String address) throws Exception{ String sql = "insert into contact(id,name,phone,address) values(seq_contact.nextval,?,?,?)"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, phone); pstmt.setString(3, address); pstmt.executeUpdate(); } public void delContact(int id) throws Exception{ String sql = "delete from contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); } public Contact getContactById(int id) throws Exception{ String sql = "select * from Contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); Contact c = null; while(rs.next()){ // int id = rs.getInt("id"); String name=rs.getString("name"); String p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值