------------------------------------------------------------------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. 1074, "Column length too big for column 'err_solution' (max = 21845); use BLOB or TEXT instead"

    一个注意点,就是sqlalchemy 使用create_all()建表的时候,要在 create_all()所在页面import那些表的model sqlalchemy.exc.Operational ...

  2. [讨论] win7封装时如何直接开通局域网共享

    ekincheng 发表于 2016-10-31 20:17:54 https://www.itsk.com/thread-371838-1-5.html Win7封装时不能像XP那样直接开启局域网共 ...

  3. centos6.5安装sublime text 2

    今天在看ueillemmx的博客的时候,看到一神级编辑器,随即安装试了试,我了个去,果然好用,自动补全,自动对齐,样样精通啊! 下面是根据ueillemmx的步骤在CentOS上安装Sublime的过 ...

  4. linux笔记:shell基础-环境变量配置文件

    source命令(重新读入配置文件,不用重启就直接生效): 环境变量配置文件: linux中的环境变量配置文件(~代表当前用户的家目录): 配置文件读取顺序: /etc/profile 文件的作用:

  5. 作用域链–JS基础核心之一

    JS中的作用域,大家都知道的,分为全局作用域和局部作用域,没有块级作用域,听起来其实很简单的,可是作用域是否能够有深入的了解,对于JS代码逻辑的编写成功率,BUG的解决能力,以及是否能写出更优秀的代码 ...

  6. 通过一行代码学习javascript

    [].forEach.call($$("*"), function (a){ a.style.outline = "1px solid #"+(~~(Math. ...

  7. css透明度的兼容!!!

    以前总是写透明度的代码,今天弄了个弹出框要求就边框透明,于是有了下边的结论,虽然很多东西不合理了,日后找到更合理在做更新!!! html <div class="new_playerf ...

  8. 英文缩写&名词

    DAO:Data Access Object 数据访问对象 Abstract Oriented Programing 面向借口编程 IOC: Inversion of Control 控制反转 DI: ...

  9. PostgreSQL 列出所有表名和数据库名

    列出表名   直接 \d 不加参数 或 SELECT   tablename   FROM   pg_tables   WHERE   tablename   NOT   LIKE   'pg%'   ...

  10. iOS开发UI篇—从代码的逐步优化看MVC

    iOS开发UI篇—从代码的逐步优化看MVC 一.要求 要求完成下面一个小的应用程序. 二.一步步对代码进行优化 注意:在开发过程中,优化的过程是一步一步进行的.(如果一个人要吃五个包子才能吃饱,那么他 ...