SpringMVC学习三

时间:2023-03-09 18:42:52
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。