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 ...
随机推荐
- Stark组件 (一)
Stark组件构建 1.启动所有app下的stark.py文件,的配置实现步骤 1.创建一个Django项目crm,并创建 app1 ,app2, stark 三个app 2.在crm 项目的set ...
- 微信小程序 swiper 显示图片计数 当前/总数
<view class="swiperContainer"> <swiper bindchange="swiperChange" autopl ...
- CentOS7 安装redis4:
phpredis-4.0.12.tar.gz:下载:wget http://download.redis.io/releases/redis-4.0.12.tar.gz $ tar -zxvf ...
- 对偶图 并查集 BZOJ4423
题目链接 题目因为要根据上一次的输出结果来判断这次的输入,也就是要求我们强制在线,不能够把输入全部储存后处理 如果不要求强制在线,我们可以先把所以输入储存起来,从最后开始处理,把删边改成加边,如果在加 ...
- DP 传球问题
洛谷P1057 传球问题 分析:经过m次传球到第i个人的方法可以由经过m-1次传球到第i个人和到第i-1个人传递得来 设dp[i][j]为经过j次传球后到达第i个人的方法数,可得到状态转移方程为: d ...
- spring boot(二)web综合开发
上篇文章介绍了Spring boot初级教程:spring boot(一):入门,方便大家快速入门.了解实践Spring boot特性:本篇文章接着上篇内容继续为大家介绍spring boot的其它特 ...
- input type="number" 时 maxlength不起作用
给input标签添加 oninput=“if(value.length>11) value=value.slice(0,11)”
- 如何引用GitHub的静态资源文件 js css
参考:引用GitHub的静态资源文件 有些人说直接用 Github Raw 浏览器不执行是因为返回的 content-type 是 text/plain,这么说不准确.实际上浏览器对 MIME 类型并 ...
- Oracle Shared Pool之Library Cache
1. Shared Pool组成 Shared Pool由许多区间(Extent)组成,这些区间又由多个连续的内存块(Chunk)组成,这些内存块大小不一.从逻辑功能角度,Shared pool主要包 ...
- 微信小程序 获取位置、移动选点、逆地址解析
WGS- 地心坐标系,即GPS原始坐标体系.在中国,任何一个地图产品都不允许使用GPS坐标,据说是为了保密.GoogleEarth及GPS芯片使用. .GCJ-02火星坐标系,国测局02年发布的坐标体 ...