SpringMVC学习三
实现有点用处的增删改查,并利用了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学习三的更多相关文章
- (转)SpringMVC学习(三)——SpringMVC的配置文件
http://blog.csdn.net/yerenyuan_pku/article/details/72231527 读者阅读过SpringMVC学习(一)——SpringMVC介绍与入门这篇文章后 ...
- springMVC学习三 注解开发环境搭建
第一步:导入jar包 第二步:配置DispatcherServlet 前端控制器 因为此处把DsipatcherServlet的映射路径配置成了"/",代表除了.jsp文件之外, ...
- SpringMVC 学习 十 SSM环境搭建(三)springMVC文件配置
SpringMVC文件配置的详细过程,可以查看springMVC环境搭建的注解配置篇<springMVC学习三 注解开发环境搭建> <?xml version="1.0&q ...
- springMVC学习总结(三)数据绑定
springMVC学习总结(三)数据绑定 一.springMVC的数据绑定,常用绑定类型有: 1.servlet三大域对象: HttpServletRequest HttpServletRespons ...
- SpringMVC入门学习三
今天是Springmvc学习的第三天,今天我将主要介绍一下: 常用注解的使用 关于非post.get请求的处理 文件上传与下载 拦截器 常用注解的使用 老大在此 @Controller @Cont ...
- springMVC学习总结(三) --springMVC重定向
根据springMVC学习总结(一) --springMVC搭建搭建项目 在com.myl.controller包下创建一个java类WebController. 在jsp子文件夹下创建一个视图文件i ...
- 史上最全的SpringMVC学习笔记
SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...
- SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码
在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...
- SpringMVC学习笔记之二(SpringMVC高级参数绑定)
一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...
随机推荐
- 有标号的DAG计数
看了某神仙博客学了一手,基本的思路就是容斥入度为0的点. n^2做法. F(n)=sigema i (-1)^(i-1)✖ C(n,i)✖ F(i)✖ 2^(j*(i-j)) nlogn做法 对上述式 ...
- Fox And Dinner CodeForces - 510E (最大流)
大意: n只狐狸, 要求分成若干个环, 每个环的狐狸不少于三只, 相邻狐狸年龄和为素数. 狐狸年龄都>=2, 那么素数一定为奇数, 相邻必须是一奇一偶, 也就是一个二分图, 源点向奇数点连容量为 ...
- UUID的意义和作用
UUID介绍: UUID(Universally Unique Identifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的.按照开放软件基金会(OSF) ...
- GitHub C 和 C++ 开源库的清单(含示例代码)
内容包括:标准库.Web应用框架.人工智能.数据库.图片处理.机器学习.日志.代码分析等. 标准库 C++标准库,包括了STL容器,算法和函数等. C++ Standard Library:是一系列类 ...
- H5 DeviceMotionEvent 事件制作“摇一摇效果”
摇一摇”的效果制作主要依赖于H5的deviceMotionEvent事件 先讲怎么使用,具体的原理在后边补充 第一步:捕捉重力加速度 var acceleration = eventData.acce ...
- 53. Maximum Subarray最大子序和
网址:https://leetcode.com/problems/maximum-subarray/submissions/ 很简单的动态规划 我们可以把 dp[i] 表示为index为 i 的位置上 ...
- MySQL5.6复制技术(2)-主从部署以及半同步配置详细过程
当前环境规划 主机名称 ec2t-pgtest-01 ec2t-pgtest-02 IP地址 10.189.102.118 10.189.100.195 角色 master slave 系统版本 Ce ...
- 跳转到页面的某个anchor
var loc = document.location.toString().split('#')[0]; document.location = loc + '#' + anchor;
- django学习之——模版
为了减少模板加载调用过程及模板本身的冗余代码,Django 提供了一种使用方便且功能强大的 API ,用于从磁盘中加载模板, 要使用此模板加载API,首先你必须将模板的保存位置告诉框架. 设置的保存文 ...
- notepad++自动对齐使用空格代替Tab并将空格显示为小点
一.说明 对大多数语言而言自动对齐使用空格还是tab对编译运行并没有什么影响,但对python问题就很大:因为就算是缩进看起来是一样的但某些行用空格某些行用tab运行会报错. 另外除了空格替换tab外 ...