实现有点用处的增删改查,并利用了AJAX(javascript)动态修改,还有json的返回读取,以及文件上传和下载。

配置基础Employee类以及Dao类

package com.springmvc;

public class Department {//成员department
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department(int id, String name) { this.id = id;
this.name = name;
}
public Department() {
} } package com.springmvc; import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository; @Repository//利用的是spring的注解自动加载持久层
public class DepartmentDao {
private static Map<Integer,Department> departments = new HashMap<Integer,Department>();//内置几个属性
static{
departments.put(1, new Department(1,"AA"));
departments.put(2, new Department(2,"BB"));
departments.put(3, new Department(3,"CC"));
departments.put(4, new Department(4,"DD"));
}
public Collection<Department> getDepartments(){
return departments.values();
} public Department getDepartment(int id){
return departments.get(id);
}
} package com.springmvc; public class Employee {
private int id;
private String name;
private String email;
private int sex;
private Department department;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee(int id, String name, String email, int sex,
Department department) {
this.id = id;
this.name = name;
this.email = email;
this.sex = sex;
this.department = department;
}
public Employee() {//要有空值建构器 } } package com.springmvc; import java.util.Collection;
import java.util.HashMap;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; @Repository
public class EmployeeDao { @Autowired//spring的自动装配
private DepartmentDao departmentDao; private static Map<Integer,Employee> Employees = new HashMap<Integer,Employee>(); static {
Employees.put(1, new Employee(1,"xiaobai","11276971@qq.com",1,new Department(1,"AA")));
Employees.put(2, new Employee(2,"xiaozhi","836659812@qq.com",0,new Department(2,"BB")));
Employees.put(3, new Employee(3,"dabai","9798451@qq.com",1,new Department(4,"DD")));
Employees.put(4, new Employee(4,"dahong","2324225@qq.com",0,new Department(3,"CC")));
}
static private int eid=4; public void insert(Employee employee){
if (employee.getId()==0){
eid++;
employee.setId(eid);
}
employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
Employees.put(employee.getId(),employee );
} public void delete(int id){
Employees.remove(id);
} public Collection<Employee> getEmployees(){
return Employees.values();
} public Employee getEmployee(int id){
return Employees.get(id);
}
}

之后是 Controler类

package com.springmvc;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; @Controller
public class EmployeeHandler { @Autowired
private EmployeeDao employeeDao; @Autowired
private DepartmentDao departmentDao;
//自动填装两个bean类 @RequestMapping("/emps")//建构一个map,将值返回给list ,查询效果实现
public String getAll(Map<String,Object>map){
map.put("employees", employeeDao.getEmployees());
return "list";
} @RequestMapping(value="/emp",method=RequestMethod.GET)//新增效果实现,用map填入必须参数,add界面读取和建构
public String addView(Map<String,Object>map){
map.put("departments", departmentDao.getDepartments());
map.put("employee", new Employee());
return "add";
} @RequestMapping(value="/emp",method=RequestMethod.POST)
public String save (Employee employee){//post ,添加成功页面,post将add界面的employee加入
employeeDao.insert(employee);
return "redirect:/emps";
} @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
public String delete (@PathVariable(value="id") Integer id){//根据ID来删除,pathvariable则可以拿到ID值。
System.out.println("delete: "+id);
employeeDao.delete(id);
return "redirect:/emps";
} @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
public String updateClick(@PathVariable(value="id") Integer id,Map<String,Object>map){//不同的是这里用一个id值取得employee参数后放回构造,在添加页面有if判断。
map.put("departments", departmentDao.getDepartments());
map.put("employee",employeeDao.getEmployee(id));
return "add";
} @RequestMapping(value="/emp",method=RequestMethod.PUT)//这里代表更新操作
public String update(Employee employee){
employeeDao.insert(employee);
return "redirect:/emps";
} @RequestMapping("/testJson")
@ResponseBody
public Collection<Employee> getEmployees(){//测试JSON来返回数组 return employeeDao.getEmployees();
} @RequestMapping("/upload")//上传页面,使用的是multipartfile 所以xml配资文件里面也要有对应的解析器,空文件的判断不是null,而是empty。
public String upLoad(MultipartFile file,HttpSession session) throws IllegalStateException, IOException{
if(!file.isEmpty()){
String path = session.getServletContext().getRealPath("/resources");
String fileName=file.getOriginalFilename();
File upfile = new File(path,fileName);
file.transferTo(upfile);
return "success";
}
return "fail"; } @RequestMapping("/download")//下载页面,使用的是流下载,实录是将其文件以流形式装换成字节数组,之后再传输。
public ResponseEntity<byte[]> download (HttpSession session) throws IOException{
byte[] body = null;
InputStream in = session.getServletContext().getResourceAsStream("/resources/getclass.txt");
body = new byte[in.available()];
in.read(body); HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=getclass.txt");
ResponseEntity<byte[]> respon = new ResponseEntity<byte[]>(body,headers,HttpStatus.OK);
return respon;
} }

add ,界面。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ 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=ISO-8859-1">
<title>Add employee</title>
</head>
<body>
<form:form action="/HelloWeb/emp" method="POST" modelAttribute="employee"> <c:if test="${employee.id == 0 }"> LastName: <form:input path="name" />
<form:errors path="name"></form:errors>
</c:if>
<c:if test="${employee.id != 0 }">
<form:hidden path="id" />
<form:input path="name" type="hidden"/>
</c:if> Email:<form:input path="email"/><br>
<%
Map<String,String> genders = new HashMap<String,String>();
genders.put("1", "Male");
genders.put("2", "Female");
request.setAttribute("genders", genders); %>
Sex:<form:radiobuttons path="sex" items="${ genders}"/><br>
Departments:<form:select path="department.id" items="${departments}" itemLabel="name" itemValue="id"></form:select>
<input type="submit" value="Submit"> </form:form>
</body>
</html>

modelattribute 就是其controler,employeeHandler给的值

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:if test="${empty requestScope.employees} }">
No employees imformation!
</c:if>
<c:if test="${!empty requestScope.employees}">
<table border="1" >
<tr>
<th>ID</th>
<th>Name</th>
<th>Emai</th>
<th>Sex</th>
<th>DepatmentName</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<c:forEach items="${requestScope.employees}" var="emp">
<tr>
<td>${emp.id }</td>
<td>${emp.name }</td>
<td>${emp.email }</td>
<td>${emp.sex==0?'Female':'Male' }</td>
<td>${emp.department.name }</td>
<td><a href="emp/${emp.id }">Edit</a></td>
<td>
<form action="/HelloWeb/emp/${emp.id}" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="delete"/>
</form>
</td>
</tr>
</c:forEach>
</table> </c:if>
<a href="/HelloWeb/emp">add new employee</a><br><br> </body>
</html>

requestScope,则是employees的内容

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-3.2.1.min.js"></script>
<script >
$(function(){
$("#testJson").click(function(){
var url = this.href;
var args = {};
$.post(url, args, function(data){
for(var i=0; i<data.length; i++){
var id = data[i].id;
var name = data[i].name;
alert(id + ": " + name);
}
})
return false;
})
})
</script>
</head>
<body>
<a href="/HelloWeb/path/pathVariable/5">PathVariable</a>
<a href="/HelloWeb/path/RequestParam?name=xiaozhi&password=no">RequestParam</a>
<a href="/HelloWeb/path/cookie">Cookie</a>
<a href="/HelloWeb/requestHeader">RequestHeader</a>
<a href="/HelloWeb/testModel">ModelAndView</a>
<a href="/HelloWeb/testModel2">ModelAndView2</a>
<a href="/HelloWeb/emps">emps</a>
<a href="/HelloWeb/testJson" id="testJson">Test Json</a> <form action="/HelloWeb/path/rest/5" method="post">
<input type="hidden" name="_method" value="put"/>
<input type="submit" value="put 5"/>
</form> <form action="/HelloWeb/path/rest/5" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="delete"/>
</form> <form action="/HelloWeb/path/rest" method="post">
<input type="submit" value="test post"/>
</form> <form action="/HelloWeb/testPOJO" method="post">
ID<input type="text" name="id"><br>
Name<input type="text" name="name"><br>
Salary<input type="text" name="salary"><br>
Province<input type="text" name="address.province"><br>
City<input type="text" name="address.city"><br>
<input type="submit" name="submit">
</form>
<br>
<form action="/HelloWeb/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="sub"/>
</form>
<br>
<a href="/HelloWeb/download">Download</a> </body>
</html>

注意,这里使用了javascript。ajax技术,需要在对应目录下导入min.js文件,因为处理的是json,所以,需要json的处理bean,在bean中配置,以及file文件的配置。

<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.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.1.xsd">
<!-- 自动扫描,加载Bean -->
<context:component-scan base-package="com.springmvc"></context:component-scan> <!-- 这是ModelAndView里面的解析,类的返回 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <mvc:annotation-driven/> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" >
<value>100000</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
</beans>

注: 在表头请求的方法中,只有post 和 get ,需要自己配置过滤器,在表单中添加hidden属性,将post映射成delete和put。

SpringMVC学习三的更多相关文章

  1. (转)SpringMVC学习(三)——SpringMVC的配置文件

    http://blog.csdn.net/yerenyuan_pku/article/details/72231527 读者阅读过SpringMVC学习(一)——SpringMVC介绍与入门这篇文章后 ...

  2. springMVC学习三 注解开发环境搭建

    第一步:导入jar包 第二步:配置DispatcherServlet  前端控制器 因为此处把DsipatcherServlet的映射路径配置成了"/",代表除了.jsp文件之外, ...

  3. SpringMVC 学习 十 SSM环境搭建(三)springMVC文件配置

    SpringMVC文件配置的详细过程,可以查看springMVC环境搭建的注解配置篇<springMVC学习三 注解开发环境搭建> <?xml version="1.0&q ...

  4. springMVC学习总结(三)数据绑定

    springMVC学习总结(三)数据绑定 一.springMVC的数据绑定,常用绑定类型有: 1.servlet三大域对象: HttpServletRequest HttpServletRespons ...

  5. SpringMVC入门学习三

    今天是Springmvc学习的第三天,今天我将主要介绍一下: 常用注解的使用 关于非post.get请求的处理 文件上传与下载 拦截器   常用注解的使用 老大在此 @Controller @Cont ...

  6. springMVC学习总结(三) --springMVC重定向

    根据springMVC学习总结(一) --springMVC搭建搭建项目 在com.myl.controller包下创建一个java类WebController. 在jsp子文件夹下创建一个视图文件i ...

  7. 史上最全的SpringMVC学习笔记

    SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...

  8. SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码

    在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...

  9. SpringMVC学习笔记之二(SpringMVC高级参数绑定)

    一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...

随机推荐

  1. jQuery -- touch事件之滑动判断(左右上下方向)

    $("body").on("touchstart", function(e) { // 判断默认行为是否可以被禁用 if (e.cancelable) { // ...

  2. 三种css样式表及其优先级

    1.行内样式 body内: <p style="text-indent: 2em;color: red"> 我是行内样式 </p> 2.内部样式表 body ...

  3. 1.1 从UNIX到Linux的发展历程

    MIT的CTSS:第一个分时操作系统 ◼ Multics系统(Multiplexed Information and Computing System) ⚫ 1965年AT&T,MIT和GE的 ...

  4. python基础之生成器,生成器函数,列表推导式

    内容梗概: 1. 生成器和生成器函数. 2. 列表推导式. 1.生成器函数1.1 生成器函数. 就是把return换成yield def gen(): print("爽歪歪") y ...

  5. Python之深浅copy与字符编码

    一.深浅copy 1. 首先看赋值运算 l1 = [1,2,3,['barry','alex']] l2 = l1 l1[0] = 111 print(l1) # [111, 2, 3, ['barr ...

  6. 【PowerDesigner】【6】Table视图同时显示Code和Name

    效果图: —————————————————————— 步骤: 文字版: 1,顶部工具栏Tools→Display Preference 2,Columns→List columns右侧按钮 3,勾选 ...

  7. acl使用示例

    declare   v_count  number;  uprinciple varchar2(20);  principle  varchar2(20);  begin uprinciple := ...

  8. MongoDB 教程(五):连接、新建数据库、删除数据库

    连接 启动 MongoDB 服务 只需要在 MongoDB 安装目录的 bin 目录下执行 mongodb 即可. 执行启动操作后,mongodb 在输出一些必要信息后不会输出任何信息,之后就等待连接 ...

  9. Qt Widgets——子区域和子窗口

    QMdiArea 一般使用于主窗口QMainWindow,用于容纳多个子窗口QMdiSubWindow qt creator 3.0的设计师有MdiArea可直接拖入使用. 界面如下,图中灰色框即是个 ...

  10. ButterKnife没有Generate ButterKnife Injections问题

    Butterknife 一键自动生成findviewbyid和onclick的代码. 步骤如下: 一: 二: 三: 完成! 如果没有Generate ButterKnife Injections选择项 ...