mapengpeng1999@163.com RestFul风格CRUD,SpringMVC的表单标签

RestFul CRUD

Rest Ful CRUD操作

1. 查询,查询所有的雇员信息
- url : emps
- 请求方式: get
- 渲染效果:表格显示雇员信息

2.新增,新增雇员信息
- url : emp
- 请求方式:post
- 新增完成之后,重定向到emps

3.表单显示,使用SpringMVC提供的表单标签,新增和修改都使用相同表单
- url:新增emp  修改emp?empId=empId
- 请求方式:get
- 显示效果:显示新增表单

4.修改操作:要求姓名不能被修改,emp_name不能修改
- url : emp
- 请求方式:put
- 修改完成之后,重定向到emps

5.删除操作 
- url : emp/{id}
- 请求方式:delete
- 删除完成之后,重定向到emps

SpringMVC的表单标签:SpringMVC提供了一套表单标签,可以将数据模型中的属性值和html的表单标签进行绑定,
以实现表单数据方便的回显。但是,即使是数据新增,SpringMVC表单标签也默认是要进行数据回显的。
一般情况下,通过get请求获得表单页面,通过post请求提交表单页面,
默认情况下,表单的提交的URL和回显的URL是相同的,所以可以不设置表单的action属性。

CRUD准备:

1.创建emp表和dept表
CREATE DATABASE springmvc
CREATE TABLE emp(
	emp_id INT PRIMARY KEY AUTO_INCREMENT,
	emp_name VARCHAR(20) DEFAULT "",
	emp_mail VARCHAR(30) DEFAULT "",
	emp_gender INT DEFAULT 1,
	dept_id INT 
);
CREATE TABLE dept(
	dept_id INT PRIMARY KEY AUTO_INCREMENT,
	dept_name VARCHAR(30) DEFAULT ""
);
INSERT INTO dept(dept_name)
VALUES ("AA"),("BB"),("CC"),("DD"),("EE");
INSERT INTO emp(emp_name,emp_mail,emp_gender,dept_id)
VALUES("aa","aa@163.com",1,1),("bb","bb@163.com",1,2),
("cc","cc@163.com",1,3),("dd","dd@163.com",1,4),
("ee","ee@163.com",1,5);
2.新建SpringMVC工程(动态WEB工程)
1. 查询,查询所有的雇员信息
- url : emps
- 请求方式: get
- 渲染效果:表格显示雇员信息
package com.wanbangee.entrties;
public class Dept {
	private Integer deptId;
	private String deptName;
	public Integer getDeptId() {
		return deptId;
	}
	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
}

package com.wanbangee.entrties;
public class Emp {
	private Integer empId;
	private String empName;
	private String empMail;
	private Integer empGender;
	private Integer deptId;
	private Dept dept;
	public Integer getEmpId() {
		return empId;
	}
	public void setEmpId(Integer empId) {
		this.empId = empId;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public String getEmpMail() {
		return empMail;
	}
	public void setEmpMail(String empMail) {
		this.empMail = empMail;
	}
	public Integer getEmpGender() {
		return empGender;
	}
	public void setEmpGender(Integer empGender) {
		this.empGender = empGender;
	}
	public Integer getDeptId() {
		return deptId;
	}
	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}
	public Dept getDept() {
		return dept;
	}
	public void setDept(Dept dept) {
		this.dept = dept;
	}
}

package com.wanbangee.dao;
import com.wanbangee.entrties.Dept;
public interface DeptDao {
//根据部门ID查询部门
	public Dept selectDeptByDeptId(Integer deptId);
}

package com.wanbangee.dao;
import java.util.List;
import com.wanbangee.entrties.Emp;
public interface EmpDao {
	//查询所有雇员
	public List<Emp> selectAllEmp();
	//查看单个雇员
	public Emp selectEmpByEmpId(Integer empId);
	//新增
	public void insertEmp(Emp emp);
	//修改
	public void updateEmp(Emp emp);
	//删除
	public void deleteEmp(Integer empId);
}

package com.wanbangee.dao.imp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.entrties.Dept;
@Repository
public class DeptDaoImp implements DeptDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public Dept selectDeptByDeptId(Integer deptId) {
		String sql ="select dept_id,dept_name from dept where dept_id = ?";
		RowMapper<Dept> rowMapper = new BeanPropertyRowMapper<>(Dept.class);
		return this.jdbcTemplate.queryForObject(sql, rowMapper,deptId);
	}
}

package com.wanbangee.dao.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.wanbangee.dao.EmpDao;
import com.wanbangee.entrties.Emp;
@Repository
public class EmpDaoImp implements EmpDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<Emp> selectAllEmp() {
		String sql = "select emp_id,emp_name,emp_mail,emp_gender,dept_id from emp";
		RowMapper<Emp> rowMapper = new BeanPropertyRowMapper<>(Emp.class);
		return this.jdbcTemplate.query(sql, rowMapper);
	}

	@Override
	public Emp selectEmpByEmpId(Integer empId) {
		String sql = "select emp_id,emp_name,emp_mail,emp_gender,dept_id from emp where emp_id = ?";
		RowMapper<Emp> rowMapper = new BeanPropertyRowMapper<>(Emp.class);
		return this.jdbcTemplate.queryForObject(sql, rowMapper,empId);
	}

	@Override
	public void insertEmp(Emp emp) {
		String sql = "insert into Emp(emp_name,emp_mail,emp_gender,dept_id) values(?,?,?,?)";	this.jdbcTemplate.update(sql,emp.getEmpName(),emp.getEmpMail(),emp.getEmpGender(),emp.getDeptId());
	}
	
	@Override
	public void updateEmp(Emp emp) {
		String sql ="update Emp set emp_name = ?,emp_mail=?,emp_gender=?,dept_id=? where emp_id = ?";	this.jdbcTemplate.update(sql,emp.getEmpName(),emp.getEmpMail(),emp.getEmpGender(),emp.getDeptId(),emp.getEmpId());
	}
	
	@Override
	public void deleteEmp(Integer empId) {
		String sql ="delete from Emp where emp_id = ?";
		this.jdbcTemplate.update(sql,empId);
	}
}

package com.wanbangee.service;
import java.util.List;
import com.wanbangee.entrties.Emp;
public interface EmpService {
	public List<Emp> selectAllEmp();
}

package com.wanbangee.service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.dao.EmpDao;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Service
public class EmpServiceImp implements EmpService {
	@Autowired
	private EmpDao empDao;
	@Autowired
	private DeptDao deptDao;
	@Override
	public List<Emp> selectAllEmp() {
		List<Emp> emps =  this.empDao.selectAllEmp();
		for (Emp emp : emps) {
			Dept dept = this.deptDao.selectDeptByDeptId(emp.getDeptId());
			emp.setDept(dept);
		}
		return emps;
	}
}

package com.wanbangee.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Controller
public class EmpController {
	@Autowired
	private EmpService empService;
	@RequestMapping(value="emps",method = RequestMethod.GET)
	public String selectAllEmp(Map<String,Object> map) {
		List<Emp> emps = this.empService.selectAllEmp();
		map.put("emps", emps);
		return "emps";
	}
}

conf类路径下的数据池配置文件db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/springmvc
user=root
password=3306
maxSize=10
initSize=5

antlr-2.7.7.jar
c3p0-0.9.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
jstl.jar
mysql-connector-java-5.1.37-bin.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
standard.jar

web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringMVC02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 配置HiddenHttpMethodFilter过滤器,将post请求转换为put或delete请求 -->
<filter>
	<filter-name>hiddenHttp</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
		<filter-name>hiddenHttp</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

springmvc的配置文件springmvc-servlet.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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
	<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.wanbangee"></context:component-scan>
	<!-- 引入外部属性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 配置连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="${driver}"></property>
	<property name="jdbcUrl" value="${url}"></property>
	<property name="user" value="${user}"></property>
	<property name="password" value="${password}"></property>
	<property name="maxPoolSize" value="${maxSize}"></property>
	<property name="initialPoolSize" value="${initSize}"></property>
	</bean>
	<!-- JdbcTemplate配置 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 
		启用事务注解 
			- 默认情况下,事务注解会使用IOC容器中名称为transactionManager的bean,如果不存在,则保存
			- 我们也可以配置事务注解使用IOC容器中bean的名称
				- transaction-manager : 配置具体的事务管理器的bean名称
			- 约定大于配置大于编码
	-->
	<tx:annotation-driven/>
	
	<!-- springmvc配置 -->	
	<!-- 配置视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

欢迎界面index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/selectAllEmp">selectAllEmp</a>
</body>
</html>

视图解析器解析的jsp/emps.jsp页面,使用了EL表达式,记得加jar包
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<table border = "1">
		<caption>雇员信息表</caption>
		<thead>
			<tr>
				<th>EMPID</th>
				<th>EMPNAME</th>
				<th>EMPMAIL</th>
				<th>EMPGENDER</th>
				<th>DEPTNAME</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${emps}" var="emp" >
				<tr>
					<td>${emp.empId}</td>
					<td>${emp.empName}</td>
					<td>${emp.empMail}</td>
					<td>${emp.empGender==1 ? 'Male':'FeMale'}</td>
					<td>${emp.dept.deptName}</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
</body>
</html>
2.新增,新增雇员信息
- url : emp
- 请求方式:post
- 新增完成之后,重定向到emps

3.表单显示,使用SpringMVC提供的表单标签,新增和修改都使用相同表单
- url:新增emp  修改emp?empId=empId
- 请求方式:get
- 显示效果:显示新增表单

package com.wanbangee.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Controller
public class EmpController {
	@Autowired
	private EmpService empService;
	@RequestMapping(value="emps",method = RequestMethod.GET)
	public String selectAllEmp(Map<String,Object> map) {
		List<Emp> emps = this.empService.selectAllEmp();
		map.put("emps", emps);
		return "emps";
	}
	//用于获得新增的表单,可以直接写个表单,但这里用springMVC提供的表单标签
	@RequestMapping(value="emp",method=RequestMethod.GET)
	public String getEmpForm(Map<String,Object> map) {
		map.put("emp", new Emp());
		//表单默认回显的数据,input.jsp页面中EMPNAME和EMPMAIL为null
		//因为new Emp()是空的,这里放过去的 emp的EMPNAME和EMPMAIL是null的,
		
		//准备genders
		Map<String,Object> genders = new HashMap<>();
		genders.put("1", "Male");
		genders.put("0","FeMale");
		map.put("genders", genders);
		
		//准备部门下拉列表
		List<Dept> depts = this.empService.selectAllDept();
			map.put("depts",depts);
			return "input";
		//准备好表单要回显的数据放到请求域,转发到input.jsp
	}
	
	//用于新增保存
	@RequestMapping(value="emp",method=RequestMethod.POST)
	public String insertEmp(Emp emp) {
		this.empService.insertEmp(emp);
		return "redirect:/emps";//重定向,视图解析为转发操作
		//新增完成后重定向到emps查询的地址,再执行一下查询,把最新的数据放到emps.jsp页面显示
	}
}

package com.wanbangee.service;
import java.util.List;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
public interface EmpService {
	public List<Emp> selectAllEmp();
	public List<Dept> selectAllDept();
	public void insertEmp(Emp emp);
}

package com.wanbangee.service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.dao.EmpDao;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Service
public class EmpServiceImp implements EmpService {
	@Autowired
	private EmpDao empDao;
	@Autowired
	private DeptDao deptDao;
	@Override
	public List<Emp> selectAllEmp() {
		List<Emp> emps =  this.empDao.selectAllEmp();
		for (Emp emp : emps) {
			Dept dept = this.deptDao.selectDeptByDeptId(emp.getDeptId());
			emp.setDept(dept);
		}
		return emps;
	}
	@Override
	public List<Dept> selectAllDept() {
		return this.deptDao.selectAllDept();
	}
	@Override
	public void insertEmp(Emp emp) {
		this.empDao.insertEmp(emp);
	}
}

package com.wanbangee.dao;
import java.util.List;
import com.wanbangee.entrties.Dept;
public interface DeptDao {
//根据部门ID查询部门
	public Dept selectDeptByDeptId(Integer deptId);
	//查询所有部门
	public List<Dept> selectAllDept();
}

package com.wanbangee.dao.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.entrties.Dept;
@Repository
public class DeptDaoImp implements DeptDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public Dept selectDeptByDeptId(Integer deptId) {
		String sql ="select dept_id,dept_name from dept where dept_id = ?";
		RowMapper<Dept> rowMapper = new BeanPropertyRowMapper<>(Dept.class);
		return this.jdbcTemplate.queryForObject(sql, rowMapper,deptId);
	}
	@Override
	public List<Dept> selectAllDept() {
		String sql = "select dept_id,dept_name from dept";
		RowMapper<Dept> rowMapper = new BeanPropertyRowMapper<>(Dept.class);
		return this.jdbcTemplate.query(sql, rowMapper);
	}
}

jsp/emps.jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<table border = "1">
		<caption>雇员信息表</caption>
		<thead>
			<tr>
				<th>EMPID</th>
				<th>EMPNAME</th>
				<th>EMPMAIL</th>
				<th>EMPGENDER</th>
				<th>DEPTNAME</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${emps}" var="emp" >
				<tr>
					<td>${emp.empId}</td>
					<td>${emp.empName}</td>
					<td>${emp.empMail}</td>
					<td>${emp.empGender==1 ? 'Male':'FeMale'}</td>
					<td>${emp.dept.deptName}</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	
	<!-- 跳转到EmpController -->
	<a href="${pageContext.request.contextPath }/emp">add Emp</a>
</body>
</html>


jsp/input.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 引入SpringMVC的表单标签 -->
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	      <!--  在这里使用SpringMVC提供的表单标签,了解,开发用不上
		- SpringMVC的表单标签默认是要进行数据回显的,即使是新增表单,
		- 默认回显的数据来自请求域中的command(命令),不用默认的command,用Emp,
		可以使用modelAttribute属性设置回显的数据名称form:form modelAttribute="emp"
		- SpringMVC的表单标签提交的地址action默认为 到这个页面的地址(从哪里到这个页面就回到哪里去)
		@RequestMapping(value="emp",method=RequestMethod.GET)
		return "input";  从这个emp来到input.jsp页面
		表单默认提交方式为post请求,会来到这里
		@RequestMapping(value="emp",method=RequestMethod.POST) 
		- from:input 标签中的path属性相当于普通标签的name + value 属性-->

	<form:form modelAttribute="emp">
		EMPNAME:<form:input path="empName"/>
		<br>
		EMPMAIL:<form:input path="empMail"/>
		<br>
<!-- tems="${genders}":表示会从请求域中找到响应的数据,渲染成单选钮组-->
		EMPGENDER:<form:radiobuttons path="empGender" items="${genders}" delimiter="&nbsp;&nbsp;&nbsp;&nbsp;"/>
		<br>
		<!-- 
			items : 要使用的请求域中的数据
			itemLabel : 下拉列表显示的数据
			itemValue :  下拉列表真实的值
		 -->
		DEPT:<form:select path="deptId" items="${depts}"  itemLabel="deptName" itemValue="deptId"></form:select>
		<br>
		<input type="submit" value="提交"/>
	</form:form>
</body>
</html>
4.修改操作:要求姓名不能被修改,
- url : emp
- 请求方式:put
- 修改完成之后,重定向到emps
package com.wanbangee.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Controller
public class EmpController {
	@Autowired
	private EmpService empService;
	@RequestMapping(value="emps",method = RequestMethod.GET)
	public String selectAllEmp(Map<String,Object> map) {
		List<Emp> emps = this.empService.selectAllEmp();
		map.put("emps", emps);
		return "emps";
	}
	//用于获得新增的表单,可以直接写个表单,但这里用springMVC提供的表单标签
	@RequestMapping(value="emp",method=RequestMethod.GET)
	public String getEmpForm(Map<String,Object> map,@RequestParam(value="empId",required=false)Integer empId) {
		if(empId == null) {
			map.put("emp", new Emp());
			//表单默认回显的数据,input.jsp页面中EMPNAME和EMPMAIL为null
			//因为new Emp()是空的,这里放过去的 emp的EMPNAME和EMPMAIL是null的,
		}else {
			//修改
			map.put("emp",this.empService.selectEmpByEmpId(empId));
		}
		
		//准备genders
		Map<String,Object> genders = new HashMap<>();
		genders.put("1", "Male");
		genders.put("0","FeMale");
		map.put("genders", genders);
		
		//准备部门下拉列表
		List<Dept> depts = this.empService.selectAllDept();
			map.put("depts",depts);
			return "input";
		//准备好表单要回显的数据放到请求域,转发到input.jsp
	}
	
	
	//用于新增保存
	@RequestMapping(value="emp",method=RequestMethod.POST)
	public String insertEmp(Emp emp) {
		this.empService.insertEmp(emp);
		return "redirect:/emps";//重定向,视图解析为转发操作
		//新增完成后重定向到emps查询的地址,再执行一下查询,把最新的数据放到emps.jsp页面显示
	}
	
	@RequestMapping(value="emp",method=RequestMethod.PUT)
	public String updateEmp(Emp emp) {
		this.empService.updateEmp(emp);
		return "redirect:/emps";
	}
	@ModelAttribute
	public void updateModel(Map<String,Object> map,@RequestParam(value="empId",required=false)Integer empId) {
		if(empId != null) {
			map.put("emp",this.empService.selectEmpByEmpId(empId));
		}
	}
}

package com.wanbangee.service;
import java.util.List;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
public interface EmpService {
	public List<Emp> selectAllEmp();
	public List<Dept> selectAllDept();
	public void insertEmp(Emp emp);
	public Emp selectEmpByEmpId(Integer empId);
	public void updateEmp(Emp emp);
}

package com.wanbangee.service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.dao.EmpDao;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Service
public class EmpServiceImp implements EmpService {
	@Autowired
	private EmpDao empDao;
	@Autowired
	private DeptDao deptDao;
	@Override
	public List<Emp> selectAllEmp() {
		List<Emp> emps =  this.empDao.selectAllEmp();
		for (Emp emp : emps) {
			Dept dept = this.deptDao.selectDeptByDeptId(emp.getDeptId());
			emp.setDept(dept);
		}
		return emps;
	}
	@Override
	public List<Dept> selectAllDept() {
		return this.deptDao.selectAllDept();
	}
	@Override
	public void insertEmp(Emp emp) {
		this.empDao.insertEmp(emp);
	}
	@Override
	public Emp selectEmpByEmpId(Integer empId) {
		return this.empDao.selectEmpByEmpId(empId);
	}
	@Override
	public void updateEmp(Emp emp) {
		this.empDao.updateEmp(emp);
	}
}

jsp/emps.jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<table border = "1">
		<caption>雇员信息表</caption>
		<thead>
			<tr>
				<th>EMPID</th>
				<th>EMPNAME</th>
				<th>EMPMAIL</th>
				<th>EMPGENDER</th>
				<th>DEPTNAME</th>
				<th>EDIT</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${emps}" var="emp" >
				<tr>
					<td>${emp.empId}</td>
					<td>${emp.empName}</td>
					<td>${emp.empMail}</td>
					<td>${emp.empGender==1 ? 'Male':'FeMale'}</td>
					<td>${emp.dept.deptName}</td>
					<td><a href="${pageContext.request.contextPath }/emp?empId=${emp.empId}">Edit</a></td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	
	<!-- 跳转到EmpController -->
	<a href="${pageContext.request.contextPath }/emp">add Emp</a>
</body>
</html>

jsp/input.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 引入SpringMVC的表单标签 -->
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	      <!--  在这里使用SpringMVC提供的表单标签,了解,开发用不上
		- SpringMVC的表单标签默认是要进行数据回显的,即使是新增表单,
		- 默认回显的数据来自请求域中的command(命令),不用默认的command,用Emp,
		可以使用modelAttribute属性设置回显的数据名称form:form modelAttribute="emp"
		- SpringMVC的表单标签提交的地址action默认为 到这个页面的地址(从哪里到这个页面就回到哪里去)
		@RequestMapping(value="emp",method=RequestMethod.GET)
		return "input";  从这个emp来到input.jsp页面
		表单默认提交方式为post请求,会来到这里
		@RequestMapping(value="emp",method=RequestMethod.POST) 
		- from:input 标签中的path属性相当于普通标签的name + value 属性-->
		
<!-- 也可以自己手动设置form:form modelAttribute="emp" action="emp" method="post" -->
	<form:form modelAttribute="emp" action="emp" method="post">
		<c:if test="${empty emp.empId}">  <!-- 数据回显如果empId为null就是新增操作 -->
			EMPNAME:<form:input path="empName"/>
		</c:if>
		<c:if test="${!empty emp.empId}">  <!-- 如果empId不为null就是修改操作 -->
			<form:hidden path="empId"/> <!--将"empId"隐藏起来hidden  -->
			<input type="hidden" name="_method" value="put">
		</c:if>
		<%-- EMPNAME:<input type="text" name="empName" value="${}"/> --%>
		<br>
		EMPMAIL:<form:input path="empMail"/>
		<br>
		<!-- tems="${genders}":表示会从请求域中找到响应的数据,渲染成单选钮组-->
		EMPGENDER:<form:radiobuttons path="empGender" items="${genders}" delimiter="&nbsp;&nbsp;&nbsp;&nbsp;"/>
		<br>
		<!-- 
			items : 要使用的请求域中的数据
			itemLabel : 下拉列表显示的数据
			itemValue :  下拉列表真实的值
		 -->
		DEPT:<form:select path="deptId" items="${depts}"  itemLabel="deptName" itemValue="deptId"></form:select>
		<br>
		<input type="submit" value="提交">
	</form:form>
</body>
</html>
5.删除操作 
- url : emp/{id}
- 请求方式:delete
- 删除完成之后,重定向到emps
package com.wanbangee.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Controller
public class EmpController {
	@Autowired
	private EmpService empService;
	@RequestMapping(value="emps",method = RequestMethod.GET)
	public String selectAllEmp(Map<String,Object> map) {
		List<Emp> emps = this.empService.selectAllEmp();
		map.put("emps", emps);
		return "emps";
	}
	//用于获得新增的表单,可以直接写个表单,但这里用springMVC提供的表单标签
	@RequestMapping(value="emp",method=RequestMethod.GET)
	public String getEmpForm(Map<String,Object> map,@RequestParam(value="empId",required=false)Integer empId) {
		if(empId == null) {
			map.put("emp", new Emp());
			//表单默认回显的数据,input.jsp页面中EMPNAME和EMPMAIL为null
			//因为new Emp()是空的,这里放过去的 emp的EMPNAME和EMPMAIL是null的,
		}else {
			//修改
			map.put("emp",this.empService.selectEmpByEmpId(empId));
		}
		
		//准备genders
		Map<String,Object> genders = new HashMap<>();
		genders.put("1", "Male");
		genders.put("0","FeMale");
		map.put("genders", genders);
		
		//准备部门下拉列表
		List<Dept> depts = this.empService.selectAllDept();
			map.put("depts",depts);
			return "input";
		//准备好表单要回显的数据放到请求域,转发到input.jsp
	}
	
	
	//用于新增保存
	@RequestMapping(value="emp",method=RequestMethod.POST)
	public String insertEmp(Emp emp) {
		this.empService.insertEmp(emp);
		return "redirect:/emps";//重定向,视图解析为转发操作
		//新增完成后重定向到emps查询的地址,再执行一下查询,把最新的数据放到emps.jsp页面显示
	}
	
	@RequestMapping(value="emp",method=RequestMethod.PUT)
	public String updateEmp(Emp emp) {
		this.empService.updateEmp(emp);
		return "redirect:/emps";
	}
	@ModelAttribute
	public void updateModel(Map<String,Object> map,@RequestParam(value="empId",required=false)Integer empId) {
		if(empId != null) {
			map.put("emp",this.empService.selectEmpByEmpId(empId));
		}
	}
	
	@RequestMapping(value="emp/{empId}",method=RequestMethod.DELETE)
	public String deleteEmp(@PathVariable(value="empId") Integer empId) {
		this.empService.deleteEmp(empId);
		return "redirect:/emps";
	}
}

package com.wanbangee.service;
import java.util.List;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
public interface EmpService {
	public List<Emp> selectAllEmp();
	public List<Dept> selectAllDept();
	public void insertEmp(Emp emp);
	public Emp selectEmpByEmpId(Integer empId);
	public void updateEmp(Emp emp);
	public void deleteEmp(Integer empId);
}

package com.wanbangee.service.imp;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wanbangee.dao.DeptDao;
import com.wanbangee.dao.EmpDao;
import com.wanbangee.entrties.Dept;
import com.wanbangee.entrties.Emp;
import com.wanbangee.service.EmpService;
@Service
public class EmpServiceImp implements EmpService {
	@Autowired
	private EmpDao empDao;
	@Autowired
	private DeptDao deptDao;
	@Override
	public List<Emp> selectAllEmp() {
		List<Emp> emps =  this.empDao.selectAllEmp();
		for (Emp emp : emps) {
			Dept dept = this.deptDao.selectDeptByDeptId(emp.getDeptId());
			emp.setDept(dept);
		}
		return emps;
	}
	@Override
	public List<Dept> selectAllDept() {
		return this.deptDao.selectAllDept();
	}
	@Override
	public void insertEmp(Emp emp) {
		this.empDao.insertEmp(emp);
	}
	@Override
	public Emp selectEmpByEmpId(Integer empId) {
		return this.empDao.selectEmpByEmpId(empId);
	}
	@Override
	public void updateEmp(Emp emp) {
		this.empDao.updateEmp(emp);
	}
	@Override
	public void deleteEmp(Integer empId) {
		this.empDao.deleteEmp(empId);
	}
}

jsp/emps.jsp页面,(jsp/input.jsp页面不做改动)
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function(){
	$(".delete").click(function(event){
		event.preventDefault();//取消表单默认行为
		var href = $(this).attr("href");
		$("#deleteForm").attr("action",href);
		$("#deleteForm").submit();//提交表单
		//return false;
	});
});
</script>
</head>
<body>
	<table border = "1">
		<caption>雇员信息表</caption>
		<thead>
			<tr>
				<th>EMPID</th>
				<th>EMPNAME</th>
				<th>EMPMAIL</th>
				<th>EMPGENDER</th>
				<th>DEPTNAME</th>
				<th>EDIT</th>
				<th>DELETE</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${emps}" var="emp" >
				<tr>
					<td>${emp.empId}</td>
					<td>${emp.empName}</td>
					<td>${emp.empMail}</td>
					<td>${emp.empGender==1 ? 'Male':'FeMale'}</td>
					<td>${emp.dept.deptName}</td>
					<td><a href="${pageContext.request.contextPath }/emp?empId=${emp.empId}">Edit</a></td>
					<td><a href="${pageContext.request.contextPath }/emp/${emp.empId}" class="delete">Delete</a></td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	
	<!-- 跳转到EmpController -->
	<a href="${pageContext.request.contextPath }/emp">add Emp</a>
	
	<form method="post" id="deleteForm">
		<input type="hidden" name="_method" value="delete">
	</form>
</body>
</html>


springmvc-servlet.xml配置文件做修改(修改配置文件后一定要重启服务器)
加上下面这些配置:
<!-- 处理静态资源 : SpringMVC会认为所有的请求都是静态资源,所以会导致正常经过请求处理器的请求出现404-->
	<mvc:default-servlet-handler/>
<!-- 万能的额配置 : 表示请求先找静态资源,如果没有静态资源则找正常的请求处理器 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	
	
<?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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		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-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
	<!-- 配置自动扫描的包 -->
	<context:component-scan base-package="com.wanbangee"></context:component-scan>
	<!-- 引入外部属性文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 配置连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="${driver}"></property>
	<property name="jdbcUrl" value="${url}"></property>
	<property name="user" value="${user}"></property>
	<property name="password" value="${password}"></property>
	<property name="maxPoolSize" value="${maxSize}"></property>
	<property name="initialPoolSize" value="${initSize}"></property>
	</bean>
	<!-- JdbcTemplate配置 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 
		启用事务注解 
			- 默认情况下,事务注解会使用IOC容器中名称为transactionManager的bean,如果不存在,则报错
			- 我们也可以配置事务注解使用IOC容器中bean的名称
				- transaction-manager : 配置具体的事务管理器的bean名称
			- 约定大于配置大于编码
	-->
	<tx:annotation-driven/>
	
	<!-- springmvc配置 -->	
	<!-- 配置视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
<!-- 处理静态资源 : SpringMVC会认为所有的请求都是静态资源,所以会导致正常经过请求处理器的请求出现404-->
	<mvc:default-servlet-handler/>
<!-- 万能的额配置 : 表示请求先找静态资源,如果没有静态资源则找正常的请求处理器 -->
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>

删除引起的静态资源问题:

修改配置文件后一定要重启服务器
目前DispatcherServlet处理所有的请求,那么会导致一些css,js,html,图片 文件的加载
都会认为是需要经过请求处理器的,但是又没有对应的请求处理器的映射的值,所以出现404错误,解决方案有两种:
    - *.do 或者 *.action,只有以.do,或者.action结尾的请求地址才进入到SpringMVC的请求处理器,但是优雅的SprngMVC不提倡使用这种形式
    
   - 处理静态资源 :
         SpringMCV提倡使用的方式:
<!-- 处理静态资源 : SpringMVC会认为所有的请求都是静态资源,所以会导致正常经过请求处理器的请求出现404-->
  <mvc:default-servlet-handler/>
<!-- 万能的额配置 : 表示请求先找静态资源,如果没有静态资源则找正常的请求处理器 -->
  <mvc:annotation-driven></mvc:annotation-driven>
上一篇:Mybatis实现CRUD


下一篇:goweb之书城基本CRUD增删改查