学习SpringMVC的第三天
目录
一、重定向
@RequestMapping("/testRedirect")
public String testRedirect() {
System.out.println("testRedirect");
return "redirect:/index.jsp";
}
二、RESTful SpringMVC CRUD
结构
1、环境搭建
(1)创建动态项目并导包(有些不是必须的)
(2)配置web.xml和springmvc.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_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- 配置SpringVMC的DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
配置org.springframework.web.filter.HiddenHttpMethodFilter: 可以把POST请求转为DELETE 或 POST请求
-->
<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>
<?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.atguigu.springmvc"></context:component-scan>
<!-- 配置视图解析处理器:如何把handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置视图BeanNameViewResolver解析器:使用视图名字来解析视图 -->
<!-- 通过order属性来定义视图的优先级,order越小优先级越高 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="100"></property>
</bean>
<!-- 配置国际化资源文件 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
<!-- 配置直接转发的页面 -->
<mvc:view-controller path="/success" view-name="success"/>
<!-- 在实际开发中通常都需配置mvc:annotation-driven -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
(3)添加相关文件
package com.atguigu.springmvc.crud.entity;
public class Department {
private Integer id;
private String departmentName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Department(int id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
public Department() {
super();
}
@Override
public String toString() {
return departmentName;
}
}
package com.atguigu.springmvc.crud.entity;
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male 0 female
private Integer gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee(int id, String lastName, String email, int gender, Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
public Employee() {
super();
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender
+ ", department=" + department + "]";
}
}
package com.atguigu.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.atguigu.springmvc.crud.entity.Department;
@Repository
public class DepartmentDao {
private static Map<Integer, Department> departments = null;
static {
departments = new HashMap<Integer , Department>();
departments.put(101,new Department(101,"D-AA"));
departments.put(102,new Department(102,"D-BB"));
departments.put(103,new Department(103,"D-CC"));
departments.put(104,new Department(104,"D-DD"));
departments.put(105,new Department(105,"D-EE"));
}
public Collection<Department> getDepartments() {
return departments.values();
}
public Department getDepartments(Integer id) {
return departments.get(id);
}
}
package com.atguigu.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.atguigu.springmvc.crud.entity.Department;
import com.atguigu.springmvc.crud.entity.Employee;
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap<Integer,Employee>();
employees.put(1001, new Employee(1001,"E-AA","aa@163.com",1,new Department(101,"D-AA")));
employees.put(1002, new Employee(1002,"E-BB","bb@163.com",1,new Department(102,"D-BB")));
employees.put(1003, new Employee(1003,"E-CC","cc@163.com",1,new Department(103,"D-CC")));
employees.put(1004, new Employee(1004,"E-DD","dd@163.com",1,new Department(104,"D-DD")));
employees.put(1005, new Employee(1005,"E-EE","ee@163.com",1,new Department(105,"D-EE")));
}
private static Integer initId = 1006;
public void save(Employee employee) {
if(employee.getId() == null) {
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartments(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
public Collection<Employee> getAll() {
return employees.values();
}
public Employee get(Integer id) {
return employees.get(id);
}
public void delete(Integer id) {
employees.remove(id);
}
}
二、实例:添加
package com.atguigu.springmvc.crud.handlers;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.atguigu.springmvc.crud.dao.DepartmentDao;
import com.atguigu.springmvc.crud.dao.EmployeeDao;
import com.atguigu.springmvc.crud.entity.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@RequestMapping("/emps")
public String list(Map<String, Object> map) {
map.put("employees", employeeDao.getAll());
return "list";
}
@RequestMapping(value="emp",method=RequestMethod.GET)
public String input(Map<String, Object> map) {
map.put("departments", departmentDao.getDepartments());
map.put("employee", new Employee());
return "input";
}
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
}
<!--index.jsp-->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="emps">List All Employees</a>
</body>
</html>
<!--input.jsp-->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
为什么使用form标签?
可以更快速开发出表单页面,而且可以更方便的进行表单值得回显
注意:
可以通过modelAttribute属性指定绑定的模型属性,
若没有指定该属性,则默认从request域对象中读取command的表单bean
如果该属性值也不存在,则会发生错误。
-->
<form:form action="emp" method="POST" modelAttribute="employee">
<!-- path属性对应HTML表单标签的name属性值 -->
LastName:<form:input path="lastName"/>
<br>
Email:<form:input path="email"/>
<%
Map<String , String> genders = new HashMap();
genders.put("1","male");
genders.put("0","female");
request.setAttribute("genders", genders);
%>
<br>
Gender:<form:radiobuttons path="gender" items="${genders }"/>
<br>
Department:<form:select path="department.id" items="${departments }" itemLable="departmentName" itemValue="id"></form:select>
<br>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
<!--list.jsp-->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${empty requestScope.employees }">
没有任何员工信息
</c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>LastName</th>
<th>Email</th>
<th>Gender</th>
<th>Department</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${requestScope.employees }" var="emp">
<tr>
<td>${emp.id }</td>
<td>${emp.lastName }</td>
<td>${emp.email }</td>
<td>${emp.gender == 0 ? 'Female' : 'Male' }</td>
<td>${emp.department.departmentName }</td>
<td><a href="">ESdit</a></td>
<td><a href="">Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
<br><br>
<a href="emp"> Add New Employee</a>
</body>
</html>
三、链接
链接:https://pan.baidu.com/s/1v7znGo3fIr0pJUOqK4gwlA
提取码:o746
复制这段内容后打开百度网盘手机App,操作更方便哦--来自百度网盘超级会员V2的分享