------------------------------------------------------------------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">

<display-name>SpringMVCTest3</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>

<!--配置SpringMVC的DispatcherServlet -->

<servlet>

<servlet-name>springDispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--配置DispatcherServlet的一个初始化参数:作用是,配置SpringMVC配置文件的位置和名称 -->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:spring.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>

<!-- 配置filter:把POST 请求转化为DELETE、PUT请求 -->

<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>

---------------------------------------------------spring.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:mvc="http://www.springframework.org/schema/mvc"

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-3.2.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<!-- 配置自动扫描的包 -->

<context:component-scan base-package="controller;dao;domain" />

<!--配置视图解析器 -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />

</bean>

<!-- 将在SpringMVC上下文中定义一个DefaultServletHttpRequestHandler, 他会对进入DispatcherServlet的请求 进行筛选,如果发现是没经过映射的请求,就将请求交给WEB的应用服务器默认 的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理

一般WEB应用服务器的Servlet的名称都是default -->

<mvc:default-servlet-handler />

<mvc:annotation-driven></mvc:annotation-driven>

</beans>

---------------------------------------------------------------------------------------------------comtroller.UserHandler.java--------------------------------------------

package controller;

//@Controller注解:将该类表示为控制器

@Controller

public class UserHandler {

// @Autowired它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set,get方法。

@Autowired

private UserDao userDao;

@Autowired

private AddressDao addressDao;

/**

* 有 @ModelAttribute标记的方法,会在每个目标方法执行之前被SpringMVC调用。

* @RequestParam(value="id", required=false)表单中的参数,required表示是否必须

*/

@ModelAttribute

public void setUser(@RequestParam(value="id", required=false)Integer id, Map<String, Object> map){

if(id != null){

map.put("user", userDao.getUser(id));

}

}

/**

* 修改保存操作

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

*/

@RequestMapping(value="/saveUser", method=RequestMethod.PUT)

public String updateUser(User user){

userDao.saveUser(user);

return "redirect:/getUsers";

}

/**

* 编辑修改操作

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

* @PathVariable("id")路径URL中的参数信息

*/

@RequestMapping(value="/editUser/{id}", method=RequestMethod.GET)

public String editUser(@PathVariable("id") Integer id, Map<String, Object> map){

map.put("addresses", addressDao.getAddresses());

map.put("user", userDao.getUser(id));

return "add";

}

/**

* 删除操作

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

* @PathVariable("id")进行接受参数

*/

@RequestMapping(value="/deleteUser/{id}", method=RequestMethod.DELETE)

public String deleteUser(@PathVariable("id") Integer id){

userDao.deleteUser(id);

//删除后进行显示操作

return "redirect:/getUsers";

}

/**

* 保存操作

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

*/

@RequestMapping(value = "/saveUser", method = RequestMethod.POST)

public String saveUser(User user) {

userDao.saveUser(user);

// 保存完成后进入到显示操作

return "redirect:/getUsers";

}

/**

* 进入到添加操作页面

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

*/

@RequestMapping(value = "/addUser", method = RequestMethod.GET)

public String addUser(Map<String, Object> map) {

map.put("addresses", addressDao.getAddresses());

// 对应struts1里边的from表单对象

map.put("user", new User());

return "add";

}

/**

* 显示操作

*

* @RequestMapping("/addUser")使用requestMapping来映射URL method对应的请求方式

*/

@RequestMapping("/getUsers")

public String getUses(Map<String, Object> map) {

map.put("users", userDao.getUsers());

return "list";

}

}

-------------------------------------------dao.UserDao.java------------------------------------------------------------

package dao;

//@Repository注解:它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean

@Repository

public class UserDao {

private static Map<Integer, User> users;

@Autowired

private AddressDao addressDao;

static {

users = new HashMap<Integer, User>();

users.put(1, new User(1, "a", 11, 1, new Address(101, "beijing")));

users.put(2, new User(2, "b", 22, 0, new Address(102, "shanghai")));

users.put(3, new User(3, "c", 33, 1, new Address(103, "guangzhou")));

}

private static Integer initId = 4;

public void saveUser(User user) {

if (user.getId() == null) {

user.setId(initId++);

}

user.setAddress(addressDao.getAddress(user.getAddress().getId()));

users.put(user.getId(), user);

}

public Collection<User> getUsers() {

return users.values();

}

public User getUser(Integer id) {

return users.get(id);

}

public User deleteUser(Integer id) {

return users.remove(id);

}

}

-------------------------------------------------------------dao.AddressDao.java-------------------------------------------------------------------

package dao;

@Repository

public class AddressDao {

private static Map<Integer, Address> addresses;

static {

addresses = new HashMap<Integer, Address>();

addresses.put(101, new Address(101, "beijign"));

addresses.put(102, new Address(102, "shanghai"));

addresses.put(103, new Address(103, "guangzhou"));

}

public Collection<Address> getAddresses() {

return addresses.values();

}

public Address getAddress(Integer id) {

return addresses.get(id);

}

}

-----------------------------------------domain------------------------------------------------

package domain;

public class Address {

private Integer id;

private String name;

}

----------------------------

package domain;

public class User {

private Integer id;

private String name;

private Integer age;

private Integer sex;

private Address address;

}

--------------------------------------------views/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>

<c:if test="${empty requestScope.users }">

没有任何员工信息

</c:if>

<c:if test="${!empty requestScope.users }">

<table border="1">

<tr>

<th>id</th>

<th>name</th>

<th>age</th>

<th>sex</th>

<th>address</th>

<th>edit</th>

<th>delete</th>

</tr>

<c:forEach items="${requestScope.users }" var="user">

<tr>

<td>${user.id }</td>

<td>${user.name}</td>

<td>${user.age}</td>

<td>${user.sex==0?"女":"男" }</td>

<td>${user.address.name}</td>

<td><a href="editUser/${user.id }">edit</a></td>

<td>

<form action="deleteUser/${user.id}" method="post">

<input type="hidden" name="_method" value="DELETE"/>

<input type="submit" value="delete"/>

</form></td>

</tr>

</c:forEach>

</table>

</c:if>

<br>

<br>

<a href="addUser">addUser</a>

</body>

</html>

---------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@page import="java.util.HashMap"%>

<%@ 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>

<form:form action="${pageContext.request.contextPath }/saveUser" method="POST" modelAttribute="user">

<c:if test="${user.name==null }">

name:<form:input path="name"/><br>

</c:if>

<c:if test="${user.name!=null }">

<form:hidden path="id"/>

<input type="hidden" name="_method" value="PUT">

</c:if>

age:<form:input path="age"/><br>

<%

HashMap<String, String> sex = new HashMap<String, String>();

sex.put("0", "女");

sex.put("1", "男");

request.setAttribute("sex", sex);

%>

sex:<form:radiobuttons path="sex" items="${sex }"/><br>

address:<form:select path="address.id" items="${addresses }" itemLabel="name" itemValue="id"/><br>

<input type="submit" value="submit">

</form:form>

</body>

</html>

============================================SpringMVC form标签===============================================================

<!--Springform表单标签:form:input 、form:password、form:hidden、form:textarea:对应HTML表单的Text、password、hidden、textarea标签  -->

<!-- form:radiobutton:单选框组建标签,对那个表单bean对应的属性和value值相等时,单选框被选中。 -->

<!-- form:radiobuttons:单选框组件标签,用于构造多个单选框

-items:可以是一个list、String【】或者map

-itemValue:指定radio的value值。可以是集合中的bean的一个属性值

-itemLabel:指定radio的label值

-delimiter:多个单选框可以通过delimiter指定分割符 -->

<!--form:checkbox:复选框组件。用户构造单个复选框

form:checkboxs:用户构造多个复选框。使用方式同form:radiobuttons标签

form:select:用于构造下拉框组件,使用方式等同于form:radiobuttons标签

form:option :下拉框选项组件标签。使用方式等同于form:radiobuttons标签

from:errors:显示表单组件或数据校验所对应的错误  -->

版权声明:本文为博主原创文章,未经博主允许不得转载。

SpringMVC案例1——对User表进行CRUD操作的更多相关文章

  1. 【Java EE 学习 44】【Hibernate学习第一天】【Hibernate对单表的CRUD操作】

    一.Hibernate简介 1.hibernate是对jdbc的二次开发 2.jdbc没有缓存机制,但是hibernate有. 3.hibernate的有点和缺点 (1)优点:有缓存,而且是二级缓存: ...

  2. Oracle触发器实现监控某表的CRUD操作

    前提:请用sys用户dba权限登录 1.创建一个表来存储操作日志 create table trig_sql( LT DATE not null primary key, SID NUMBER, SE ...

  3. 【Java框架型项目从入门到装逼】第九节 - 数据库建表和CRUD操作

    1.新建学生表 这节课我们来把和数据库以及jdbc相关的内容完成,首先,进行数据库建表.数据库呢,我们采用MySQL数据库,我们可以通过navcat之类的管理工具来轻松建表. 首先,我们得建一个数据库 ...

  4. 【nodejs】修改了下对股票表进行crud操作的代码

    表是这样的: id是自增长字段,code和name都是255位的varchar. 下面是主角app.js的代码: 'use strict'; var express=require('express' ...

  5. jdbc笔记(二) 使用PreparedStatement对单表的CRUD操作

    首先声明,本文只给出代码,并不是做教程用,如有不便之处,还请各位见谅. PreparedStatement相较于Statement,概括来说,共有三个优势: 1. 代码的可读性和易维护性:Prepar ...

  6. jdbc笔记(一) 使用Statement对单表的CRUD操作

    jdbc连接mysql并执行简单的CRUD的步骤: 1.注册驱动(需要抛出/捕获异常) Class.forName("com.mysql.jdbc.Driver"); 2.建立连接 ...

  7. 6.单表的CRUD操作

    1.插入后用新id初始化被插入对象 <insert id="insertStudentCatchId"> insert into student (age,name,s ...

  8. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)

    本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...

  9. MyBatis入门学习教程-使用MyBatis对表执行CRUD操作

    上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...

随机推荐

  1. 阿里云对象存储OSS————跨域资源共享(CORS)(m3u8 无法加载m3u8:跨域访问被拒绝)

    今天在做视频直播录像的时候,添加一个录制APP的.M3U8文件到OSS的一个test文件中存储,结果是访问不到了: 提示:无法加载m3u8:跨域访问被拒绝!!!!! 项目代码测试地址:https:// ...

  2. mysql exists 和 in的效率比较

    这条语句适用于a表比b表大的情况 select * from ecs_goods a where cat_id in(select cat_id from ecs_category b); 这条语句适 ...

  3. filter 过滤缓存

    package fifter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.Filter ...

  4. Setup Factory Error3014

    在用Setup Factory打包软件的时候出现Error3014 一般都是由于软件冲突引起的 我的问题是由于杀毒软件 ,在打包的时候关闭杀毒软件 就能成功打包了.

  5. Unity5 GI与PBS渲染从用法到着色代码

    http://www.cnblogs.com/zhouxin/p/5168632.html 本文主要介绍Untiy5以后的GI,PBS,以及光源探头,反射探头的用法以及在着色器代码中如何发挥作用,GI ...

  6. python核心编程第六章练习6-12

    6-12.字符串.(a)创建一个名字为findchr()的函数,函数声明如下.def findchr(string, char)findchr()要在字符串string中查找字符char,找到就返回该 ...

  7. java 多线程—— 线程等待与唤醒

    java 多线程 目录: Java 多线程——基础知识 Java 多线程 —— synchronized关键字 java 多线程——一个定时调度的例子 java 多线程——quartz 定时调度的例子 ...

  8. div被object覆盖的解决办法

    代码: <div id="contextmenu" style="width: 120px; height:120px;DISPLAY: none; top: 26 ...

  9. react native ScrollView

    ScrollView是一个通用的可滚动的容器,你可以在其中放入多个组件和视图,而且这些组件并不需要是同类型的.ScrollView不仅可以垂直滚动,还能水平滚动(通过horizontal属性来设置). ...

  10. require.js的使用

    RequireJS是一个非常小巧的JavaScript模块载入框架,是AMD规范最好的实现者之一.最新版本的RequireJS压缩后只有14K,堪称非常轻量.它还同时可以和其他的框架协同工作,使用Re ...