SpringMVC-CRUD

来源:互联网 发布:网络打鱼秘籍 编辑:程序博客网 时间:2024/05/22 15:34
1.需求分析:
(1) 显示所有员工信息


(2) 添加所有员工信息

 完成添加,重定向到 list 页面。

(3) 删除操作
URL:emp/{id}
请求方式:DELETE
删除后效果:对应记录从数据表中删除
修改操作:lastName 不可修改!
(4) 显示修改页面
URI:emp/{id}
请求方式:GET
显示效果:回显表单。
(5) 修改员工信息
URI:emp
请求方式:PUT
显示效果:完成修改,重定向到 list 页面。

2.RESTRUL_CRUD_显示所有员工信息
(1) 搭建开发环境
     ① 拷贝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
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
commons-logging-1.1.3.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
     ② 创建配置文件:springmvc.xml  增加context,mvc,beans名称空间。
<?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:aop="http://www.springframework.org/schema/aop"     xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:context="http://www.springframework.org/schema/context"     xmlns:cache="http://www.springframework.org/schema/cache"     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd           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/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <!-- 配置扫描的包 -->     <context:component-scan base-package="com.atguigu.springmvc.crud.*"/>     <!-- 配置视图解析器,默认菜用转发的形式 -->     <bean id= "viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >          <!-- 前缀 -->          <property name="prefix" value="/WEB-INF/views/"/>          <!-- 后缀 -->          <property name="suffix" value= ".jsp"/>     </bean>           <!--在springMVC-servlet.xml中配置mvc:default-servlet-handler 后,会在Spring MVC上下文中定义一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理-->     <mvc:default-servlet-handler />          <!-- 配置 <mvc:default-servlet-handler/>解决静态资源访问问题,但是,原来的映射路径都找不到了,这个配置就是解决这个问题的-->     <mvc:annotation-driven /></beans>
     ③ 配置核心控制器:web.xml
<?xml version="1.0" encoding="UTF-8"?><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">  <!-- 支持REST风格的过滤器:可以将POST请求转换为PUT或DELETE请求 -->  <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>  <servlet>    <servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>
     ④ 创建相关页面
     ⑤ 增加实体类
     ⑥ 增加DAO类

(2) 显示所有员工信息
     ① 增加页面链接,在inex.jsp页面中。
< a href ="${pageContext.request.contextPath } /emps">Query All Employees</ a>
     ② 增加处理器
@Controllerpublic class EmployeeHandler {     @Autowired     private EmployeeDao employeeDao ;     @Autowired     private DepartmentDao departmentDao ;     @RequestMapping(value="/emps",method=RequestMethod.GET)     public String queryAllEmps(Map<String,Object> map){          map.put("empList", employeeDao.getAll());          return "list";     }}
     ③ 在list.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 }/scripts/jquery-1.9.1.min.js"></script>   <script type="text/javascript">     $(function(){            $(".delete").click(function(){                 var href = this.href ;                $("form").attr("action",href).submit();                return false ;           });                });</script></head><body><form action="" method="POST">     <input type="hidden" name="_method" value="DELETE"></form><c:if test="${empty requestScope.empList}">   沒有查詢到員工信息。。。</c:if><c:if test="${!empty requestScope.empList}">     <center>           <table border="1" width="80%">                <tr>                     <th>id</th>                     <th>lastName</th>                     <th>email</th>                     <th>gender</th>                     <th>departmentName</th>                     <th>更新</th>                     <th>刪除</th>                </tr>                                <c:forEach items="${requestScope.empList}" var="emp">                   <tr>                        <td>${emp.id}</td>                        <td>${emp.lastName }</td>                        <td>${emp.email }</td>                        <td>${emp.gender==0?"Female":"Male"}</td>                        <td>${emp.department.departmentName }</td>                        <td><a href="${pageContext.request.contextPath }/emp/${emp.id}">更新</a></td>                        <td><a class="delete" href="${pageContext.request.contextPath }/emp/${emp.id}">删除</a></td>                   </tr>                </c:forEach>           </table>     </center></c:if><a href="${pageContext.request.contextPath}/emp">添加</a>     </body></html>
(3) 添加操作
     ① 在list.jsp上增加连接,上面有:
<a href= "${pageContext.request.contextPath } /emp" >添加 </ a>
     ② 增加处理器方法
@RequestMapping(value="/emp" ,method=RequestMethod.GET)     public String toAdd(Map<String,Object> map){          map.put( "deptList", departmentDao.getDepartments());          map.put( "employee", new Employee());           return "add" ;     }
     ③ 显示添加页面add.jsp
<%@page import="java.util.Map"%><%@page import="java.util.HashMap"%><%@page import="javax.print.attribute.HashAttributeSet"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%@ 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><form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee">LatName:<form:input path="lastName"/><br><br>Email:<form:input path="email"/><br><br>     <%                Map<String,String> genders = new HashMap<String,String>();                genders.put("0", "female");                genders.put("1", "male");                request.setAttribute("genders", genders);     %>Gender : <form:radiobuttons path="gender" items="${requestScope.genders}"/><br><br>deptName : <form:select path="department.id"                     items="${requestScope.deptList }"                     itemLabel="departmentName"                     itemValue="id">                </form:select>                <br><br>           <input type="submit" value="添加">  <br><br></form:form></body></html>
     ④ 控制器方法
@RequestMapping(value= "/emp" ,method=RequestMethod. POST)      public String doAdd(Employee employee){           employeeDao .save(employee);           return "redirect:/emps" ;     }
(4) 删除操作
     ① 页面链接
< td><a class= "delete" href="${pageContext.request.contextPath } /emp/${emp.id }" >删除</ a></td >
     ② 控制器方法
@RequestMapping(value="/emp/{id}" ,method=RequestMethod.DELETE)  public String delete( @PathVariable("id" ) Integer id){        employeeDao.delete(id);        return "redirect:/emps" ;  }
     ③ HiddenHttpMethodFilter过滤器
     发起请求,无法执行,因为delete请求必须通过post请求转换为delete请求,借助:HiddenHttpMethodFilter过滤器
     注意:需要使用jQuery来转换请求方式
     a.加入jQuery库文件:/scripts/jquery-1.9.1.min.js
     b.在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/>和<mvc:annotation-driven />
     c.关于<mvc:default-servlet-handler/>作用
<!--  该标签属性default-servlet-name默认值是"default",可以省略。<mvc:default-servlet-handler/>  --><mvc:default-servlet-handler default-servlet-name="default"/>
     ④ 通过jQuery转换为DELETE请求
< td><a class= "delete" href="${pageContext.request.contextPath } /emp/${emp.id }" >删除</ a></td ><form action= "" method ="POST">           <input type= "hidden" name ="_method" value="DELETE" ></form ><script type= "text/javascript">     $(function(){           $( ".delete").click(function (){               var href = this .href ;               //var href = $(this).attr("href") ;              $( "form").attr("action" ,href).submit();               return false ;          });     });</script>
5.修改操作:
     ① 页面链接
< td><a href= "${pageContext.request.contextPath }/emp/ ${emp.id }"> 更新</a ></td>
     ② 控制器方法
@RequestMapping(value= "/emp/{id}",method=RequestMethod.GET)public String toUpdate( @PathVariable("id" ) Integer id , Map<String,Object> map){      map.put( "deptList", departmentDao.getDepartments());      map.put( "employee", employeeDao .get(id));       return "update" ;}
     ③ 修改页面
<%@page import= "java.util.HashMap"%><%@page import= "java.util.Map"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding= "UTF-8"%><%@ 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框架提供的标签库完成表单页面开发          好处:自动回显          表单回显时需要获取一个模型对象名称为: "commond"对应的实体对象的属性值;如果没有这个实体对象就会抱错:              java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute          只需要在控制器方法的map中绑定一个  map.put("commond", obj); //obj中只要提供表单上所有path属性对应属性名称就可以          如果希望map中的key不为command;可以在表单上使用modelAttribute来指定map中的key,从key所对应的对象中查找与path名称一致的属性      -->     <form:form action="${pageContext.request.contextPath }/emp" method ="POST" modelAttribute= "employee">               <form:hidden path= "id"/>           <!-- 由于模型对象中没有 "_method"这个属性,所以不能进行表单回显,所以不能使用form:hidden标签作为隐含域,而是采用 html标签 -->           <input type= "hidden" name ="_method" value= "PUT">           <!-- lastName 不需要更新,保证这个属性值不丢失 -->           <%-- LastName : <form:input path="lastName"/> <br><br> --%>          Email : <form:input path= "email"/><br ><br>           <%              Map<String,String> genders = new HashMap<String,String>();              genders.put( "0", "female" );              genders.put( "1", "male" );              request.setAttribute( "genders", genders);           %>          Gender : <form:radiobuttons path= "gender" items=" ${requestScope.genders }"/> < br><br >           <!--          itemLabel : 用于下拉中显示          itemValue : 用于提交选择的选项值           -->          deptName : <form:select path= "department.id"                    items= "${requestScope.deptList }"                    itemLabel="departmentName"                    itemValue="id" ></form:select>   <br>< br>           <input type= "submit" value ="修改">   < br><br >     </form:form ></body></html>
     ④ 控制器方法
@RequestMapping(value="/emp" ,method=RequestMethod.PUT)     //public String delete(Employee employee){     public String doUpdate(Employee employee){           employeeDao.save(employee); //更新和保存共用一个方法           return "redirect:/emps" ;     }//在每一个处理器方法前都要执行     @ModelAttribute     public void getEmployee(@RequestParam(value="id" ,required=false) Integer id, Map<String,Object> map){ //这个方法提供模型对象,不是处理请求的方法,没有@RequestMapping           if(id!=null ){              Employee employee = employeeDao.get(id);              map.put( "emp", employee);          }     }


原创粉丝点击