废话不多说,直接开始步骤!

1.创建一个Dynamic Web Project

2.在WEB-INF包下的lib文件夹中引入相关jar

  1. commons-logging-.jar
  2. jstl.jar
  3. spring-aop-.RELEASE.jar
  4. spring-beans-.RELEASE.jar
  5. spring-context-.RELEASE.jar
  6. spring-core-.RELEASE.jar
  7. spring-expression-.RELEASE.jar
  8. spring-web-.RELEASE.jar
  9. spring-webmvc-.RELEASE.jar
  10. standard.jar

3.编写web.xml文件---该文件配置SpringMVC的主控制器DispatcherServlet,该主控负责拦截请求,并将请求分发给handler控制器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  3. <display-name>SpringMVC</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.jsp</welcome-file>
  6. </welcome-file-list>
  7.  
  8. <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
  9. <servlet>
  10. <servlet-name>springDispatcherServlet</servlet-name>
  11. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  12. <init-param>
  13. <param-name>contextConfigLocation</param-name>
  14. <param-value>classpath:springmvc.xml</param-value>
  15. </init-param>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18.  
  19. <!-- Map all requests to the DispatcherServlet for handling -->
  20. <servlet-mapping>
  21. <servlet-name>springDispatcherServlet</servlet-name>
  22. <url-pattern>/</url-pattern>
  23. </servlet-mapping>
  24.  
  25. </web-app>

4.编写springmvc-servlet.xml---该文件必须配置注解自动扫描包(否则注解无法使用),还必须配置视图解析器等等

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  9.  
  10. <context:component-scan base-package="com.jesse"></context:component-scan>
  11.  
  12. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  13. <property name="prefix" value="/WEB-INF/"></property>
  14. <property name="suffix" value=".jsp"></property>
  15. </bean>
  16.  
  17. <mvc:default-servlet-handler/>
  18. <mvc:annotation-driven></mvc:annotation-driven>
  19. </beans>

5.创建三个包,如以下图所实

说明:由于还没整合mybatis,所以先创建一些静态数据,只要方便操作就可以

以下是三个包中的代码:

  1. package com.jesse.model;
  2.  
  3. public class Employee {
  4.  
  5. private Integer id;
  6. private String lastName;
  7. private String email;
  8. private Integer gender;
  9. private Department department;
  10.  
  11. public Integer getId() {
  12. return id;
  13. }
  14.  
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18.  
  19. public String getLastName() {
  20. return lastName;
  21. }
  22.  
  23. public void setLastName(String lastName) {
  24. this.lastName = lastName;
  25. }
  26.  
  27. public String getEmail() {
  28. return email;
  29. }
  30.  
  31. public void setEmail(String email) {
  32. this.email = email;
  33. }
  34.  
  35. public Integer getGender() {
  36. return gender;
  37. }
  38.  
  39. public void setGender(Integer gender) {
  40. this.gender = gender;
  41. }
  42.  
  43. public Department getDepartment() {
  44. return department;
  45. }
  46.  
  47. public void setDepartment(Department department) {
  48. this.department = department;
  49. }
  50.  
  51. @Override
  52. public String toString() {
  53. return "Employee [id=" + id + ", lastName=" + lastName + ", email="
  54. + email + ", gender=" + gender + ", department=" + department
  55. + "]";
  56. }
  57.  
  58. public Employee(Integer id, String lastName, String email, Integer gender,
  59. Department department) {
  60. super();
  61. this.id = id;
  62. this.lastName = lastName;
  63. this.email = email;
  64. this.gender = gender;
  65. this.department = department;
  66. }
  67.  
  68. public Employee() {
  69. // TODO Auto-generated constructor stub
  70. }
  71. }
  1. package com.jesse.model;
  2.  
  3. public class Department {
  4.  
  5. private Integer id;
  6. private String departmentName;
  7.  
  8. public Department() {
  9. // TODO Auto-generated constructor stub
  10. }
  11.  
  12. public Department(int i, String string) {
  13. this.id = i;
  14. this.departmentName = string;
  15. }
  16.  
  17. public Integer getId() {
  18. return id;
  19. }
  20.  
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24.  
  25. public String getDepartmentName() {
  26. return departmentName;
  27. }
  28.  
  29. public void setDepartmentName(String departmentName) {
  30. this.departmentName = departmentName;
  31. }
  32.  
  33. @Override
  34. public String toString() {
  35. return "Department [id=" + id + ", departmentName=" + departmentName
  36. + "]";
  37. }
  38.  
  39. }
  1. package com.jesse.dao;
  2.  
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Repository;
  9.  
  10. import com.jesse.model.Department;
  11. import com.jesse.model.Employee;
  12.  
  13. @Repository
  14. public class EmployeeDao {
  15.  
  16. private static Map<Integer, Employee> employees = null;
  17.  
  18. @Autowired
  19. private DepartmentDao departmentDao;
  20.  
  21. static{
  22. employees = new HashMap<Integer, Employee>();
  23.  
  24. employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
  25. employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
  26. employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
  27. employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
  28. employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
  29. }
  30.  
  31. private static Integer initId = 1006;
  32.  
  33. public void save(Employee employee){
  34. if(employee.getId() == null){
  35. employee.setId(initId++);
  36. }
  37.  
  38. employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
  39. employees.put(employee.getId(), employee);
  40. }
  41.  
  42. public Collection<Employee> getAll(){
  43. return employees.values();
  44. }
  45.  
  46. public Employee get(Integer id){
  47. return employees.get(id);
  48. }
  49.  
  50. public void delete(Integer id){
  51. employees.remove(id);
  52. }
  53. public void update(Integer id,Employee employee){
  54. Employee emp = employees.get(id);
  55. emp = employee;
  56. }
  57. }
  1. package com.jesse.dao;
  2.  
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. import org.springframework.stereotype.Repository;
  8.  
  9. import com.jesse.model.Department;
  10.  
  11. @Repository
  12. public class DepartmentDao {
  13.  
  14. private static Map<Integer, Department> departments = null;
  15.  
  16. static{
  17. departments = new HashMap<Integer, Department>();
  18.  
  19. departments.put(101, new Department(101, "D-AA"));
  20. departments.put(102, new Department(102, "D-BB"));
  21. departments.put(103, new Department(103, "D-CC"));
  22. departments.put(104, new Department(104, "D-DD"));
  23. departments.put(105, new Department(105, "D-EE"));
  24. }
  25.  
  26. public Collection<Department> getDepartments(){
  27. return departments.values();
  28. }
  29.  
  30. public Department getDepartment(Integer id){
  31. return departments.get(id);
  32. }
  33.  
  34. }

6.首先先创建index.jsp,用于跳转显示所有数据(查询)

  1. <a href="query">query</a>

以上代码在我们运行时显示query,只要我们点击,就会跳转到控制器中调用使用@RequestMapping("query")修饰的方法

  1. @Controller
  2. public class EmployeeHandler {
  3.  
  4. @Autowired
  5. private EmployeeDao employeeDao;
  6.  
  7. /*
  8. @Autowired
  9. private DepartmentDao departmentDao;
  10. */
  11.  
  12. /**
  13. * 查询
  14. */
  15. @RequestMapping("query")
  16. public String query(Map<String,Object> map){
  17. map.put("allEmployees", employeeDao.getAll());
  18. return "list";
  19. }

根据视图解析器的配置,当调用该方法后会跳转/WEB-INF/list.jsp页面,现在就来编写list.jsp页面,以让我们看到所有数据

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2. pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <table border="1" cellpadding="10" cellspacing="0">
  12. <tr>
  13. <th>id</th>
  14. <th>lastName</th>
  15. <th>email</th>
  16. <th>gender</th>
  17. <th>department</th>
  18. <th>Edit</th>
  19. <th>Delete</th>
  20. </tr>
  21. <c:forEach items="${requestScope.allEmployees}" var="emp">
  22. <tr>
  23. <td>${emp.id}</td>
  24. <td>${emp.lastName}</td>
  25. <td>${emp.email}</td>
  26. <td>${emp.gender==0?'Female':'Male'}</td>
  27. <td>${emp.department.departmentName}</td>
  28. <td><a href="edit/${emp.id}">Edit</a></td>
  29. <td><a href="delete/${emp.id}">Delete</a></td>
  30. </tr>
  31. </c:forEach>
  32. </table>
  33. <a href="readyData">Add Employee</a>
  34. </body>
  35. </html>

查询就写好了,让大家一起来看显示的结果,界面有点粗糙,但是是练习,所有漂亮美观与否无关紧要,把握时间才重要!

7.添加数据

在上图中,只要一点击Add Employee,就会跳转到添加页面,我们要做成以下图例的样子:

从上图看出,Department是下拉框,这意味着值必须从DepartmentDao取,所以我们得通过handler来取值

  1. @RequestMapping("readyData")
  2. public String readyData(Map<String,Object> map){
  3. map.put("department", departmentDao.getDepartments());
  4. map.put("employee", new Employee());
  5. //map.put("actionType", "add");
  6. return "addPage";
  7. }

创建一个addPage.jsp的页面

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2. pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  4. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  5. <%@page import="java.util.Map"%>
  6. <%@page import="java.util.HashMap"%>
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  11. <title>Insert title here</title>
  12. <%
  13. String path = request.getContextPath();
  14. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  15. %>
  16. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  17. <html>
  18. <head>
  19. <base href="<%=basePath%>">
  20. </head>
  21. <body>
  22. <form:form action="add" method="post" modelAttribute="employee">
  23. <form:hidden path="id"/>
  24. LastName:<form:input path="lastName"/><br>
  25. Email:<form:input path="email"/><br>
  26. <%
  27. Map<String,String> gender = new HashMap();
  28. gender.put("0", "Female");
  29. gender.put("1","Male");
  30. request.setAttribute("gender",gender);
  31. %>
  32. Gender:<form:radiobuttons path="gender" items="${gender}"/><br>
  33. Department:<form:select path="department.id" items="${department}" itemValue="id" itemLabel="departmentName">
  34. </form:select><br>
  35. <input type="submit" value="submit">
  36. </form:form>
  37. </body>
  38. </html>

也许大家注意到了,为什么方法中要存放一个空的Employee对象--->map.put("employee", new Employee());  而addPage.jsp表单标签中也使用了该属性modelAttribute="employee",原因在于回显数据的功能,它认为我们肯定在更新数据时都要回显数据,所以必须有一个对象和表单内的属性一一对应,一个没对应都会异常,由于我们是添加数据,而不是回显数据,所有传入一个空的对象即可,当submit后,就会去寻找以下方法:

  1. @RequestMapping("add")
  2. public String addEmployee(Employee employee){
  3. employeeDao.save(employee);
  4. return "redirect:/query";
  5. }

添加成功就重定向到查询结果集页面

8.删除数据

删除数据只要在方法中传入要删除数据的id,即可删除

在结果集点击Delete后,直接调用以下方法:

  1. @RequestMapping(value="delete/{id}",method=RequestMethod.GET)
  2. public String delete(@PathVariable("id") Integer id){
  3. employeeDao.delete(id);
  4. return "redirect:/query";
  5. }

同样的是删除成功后重定向到查询结果集页面

9.更新数据,也是整个增删改成最繁琐的,涉及到回显数据,以及@ModelAttribute的使用等等

在结果集点击Edit,跳转到修改数据页面,该页面之前是添加数据的页面,不同得是之前传的employee对象new出来的一个空对象,而现在传的employee是已查询出来的一个对象

回显数据:

  1. @RequestMapping("edit/{id}")
  2. public String updateEmployee(@PathVariable("id") Integer id,
  3. Map<String,Object> map){
  4. map.put("employee", employeeDao.get(id));
  5. map.put("actionType", "update");
  6. map.put("department", departmentDao.getDepartments());
  7. return "addPage";
  8. }

说明:map中key值为employee的对象,是通过@PathVariable("id")获得的,就相当于根据id来获取结果集中的某一条记录,然后将该记录放入map中,并且这条记录必须和刚才的添加页面的modelAttribute="employee"的值是对应的,也就是表单标签具备回显功能,只要这两个值对应,自动把那条记录传入进来,结果为:

但是一个问题来了,更新页面其实是使用的之前的添加页面,而action值为add,这时需要进行修改,否则提交的都是add方法

在add方法和updateEmployee方法都放上一个actionType作为判断依据:

map.put("actionType", "update");

map.put("actionType","add");

然后再提交页面进行判断:

  1. <form:form action="${requestScope.actionType=='add'?'add':'update'}" method="post" modelAttribute="employee">
  2. <form:hidden path="id"/>
  3. LastName:<form:input path="lastName"/><br>
  4. Email:<form:input path="email"/><br>
  5. <%
  6. Map<String,String> gender = new HashMap();
  7. gender.put("0", "Female");
  8. gender.put("1","Male");
  9. request.setAttribute("gender",gender);
  10. %>
  11. Gender:<form:radiobuttons path="gender" items="${gender}"/><br>
  12. Department:<form:select path="department.id" items="${department}" itemValue="id" itemLabel="departmentName">
  13. </form:select><br>
  14. <input type="submit" value="submit">
  15. </form:form>

如果传入进来的actionType是update,调用控制器方法更新:

  1. @RequestMapping("update")
  2. public String update(@RequestParam(value="id") Integer id,Employee employee){
  3. employeeDao.update(id, employee);
  4. return "redirect:/query";
  5. }

必须要注意的是:

必须使用@ModelAttribute编写一个方法,在update调用前查询出数据,然后将要更新的值直接更新,不更新的值保持之前查询数来的值,比如:

Employee[name=spring age=10 salary=2000]这时如果只更新salary的值,我们想要的结果如下:

Employee[name=spring age=10 salary=3000]

  1. @ModelAttribute
  2. public void solvePro(@RequestParam(value="id",required=false)Integer id,
  3. Map<String,Object> map){
  4. if (id != null) {
  5. map.put("employee", employeeDao.get(id));
  6. }
  7. }

缺少以上方法,那更新结果就变成:

Employee[name=null age=null salary=3000]

整个增删改成的过程就是这样,可能表述的不是很清楚,欢迎提出您的困惑!

基于SpringMVC的增删改查的更多相关文章

  1. springMVC实现增删改查

    首先需要准备好一张数据库表我这里用emp这张表:具体代码: /* SQLyog 企业版 - MySQL GUI v8.14 MySQL - 5.1.73-community ************* ...

  2. Mybatis_3.基于注解的增删改查

    1.实体类User.java public class User { private int id; private String name; private int age; //getter.se ...

  3. ASP.NET Web API基于OData的增删改查,以及处理实体间关系

    本篇体验实现ASP.NET Web API基于OData的增删改查,以及处理实体间的关系. 首先是比较典型的一对多关系,Supplier和Product. public class Product { ...

  4. [转]ASP.NET Web API基于OData的增删改查,以及处理实体间关系

    本文转自:http://www.cnblogs.com/darrenji/p/4926334.html 本篇体验实现ASP.NET Web API基于OData的增删改查,以及处理实体间的关系. 首先 ...

  5. Node.js、express、mongodb 入门(基于easyui datagrid增删改查)

    前言 从在本机(win8.1)环境安装相关环境到做完这个demo大概不到两周时间,刚开始只是在本机安装环境并没有敲个Demo,从周末开始断断续续的想写一个,按照惯性思维就写一个增删改查吧,一方面是体验 ...

  6. SpringMvc学习-增删改查

    本节主要介绍SpringMVC简单的增删改查功能. 1.查询 dao中的代码 public List<WeatherPojo> getAllWeather(){ String sql=&q ...

  7. Mybatis_2.基于XML的增删改查

    1.实体类User.java public class User { private int id; private String name; private int age; //getter.se ...

  8. 基于django做增删改查组件,分页器组件

    增删改查组件 一.Djangoadmin的启发 二.基于Djangoadmin实现数据的增删改查 分页器组件 分页器组件的介绍以及源码解读 补充:源码下载,

  9. CRM基于.NET的增删改查

    一.准备工作: 1.添加 microsoft.crm.sdk.proxy.dll和microsoft.xrm.sdk.dll 引用到项目中!并引用以下using! using Microsoft.Xr ...

随机推荐

  1. [题解]USACO 1.3 Wormholes

    Wormholes Farmer John's hobby of conducting high-energy physics experiments on weekends has backfire ...

  2. Splinter学习--初探3,两种方式登录QQ邮箱

    目前,qq邮箱的登录方式有: 1.利用账号.密码登录 2.快捷登录,前提是你本地已有qq账号登录中 和前面一样,还是先到qq邮箱登录首页,审查页面元素,找到我们进行登录操作所相关的链接.按钮或是输入框 ...

  3. Java是如何读取和写入浏览器Cookies的

    首先我们认识下什么是cookies: cookie实际上是一个存在你硬盘里的数据,但是这些数据很特殊,只能由web应用提交给浏览器帮助存储,并且我们还能读取浏览器存在本地的cookie web应用一般 ...

  4. ASP.NET中的Session怎么正确使用

    Session对象用于存储从一个用户开始访问某个特定的aspx的页面起,到用户离开为止,特定的用户会话所需要的信息.用户在应用程序的页面切换时,Session对象的变量不会被清除. 对于一个Web应用 ...

  5. Linux命令小结:crontab/netstat/iostat/sar

    crontab cron可以设定在指定的时间运行任务. 1.查看定时任务 [root@client1 ~]# crontab -l -u root */1 * * * * date >> ...

  6. winrar命令行加压解密

    加密的操作 Rar.exe a -P123 test1.rar test.txt 其中参数a表示添加文件或文件夹到压缩包中,-P参数表示是带密码的加密 Rar.exe e -P123 test1.ra ...

  7. sql报句柄无效。 (异常来自 HRESULT:0x80070006 (E_HANDLE))

    是由于数据库连接资源被耗尽或者用完没被释放导致的. 我在字符串中加了启用连接池好了. 如果错误信息为:sql 无效操作.连接被关闭 也是这个问题导致的.

  8. Fuzzy Probability Theory---(3)Discrete Random Variables

    We start with the fuzzy binomial. Then we discuss the fuzzy Poisson probability mass function. Fuzzy ...

  9. java访问ftp的一些操作

    通过java代码来访问ftp服务器,进行下载操作

  10. (Python)异常处理try...except、raise

    一.try...except 有时候我们写程序的时候,会出现一些错误或异常,导致程序终止.例如,做除法时,除数为0,会引起一个ZeroDivisionError 例子: a=10 b=0 c=a/b ...