1. 搭建基础项目
1.1 新建maven项目demo
1.2 修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.0-alpha10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
1.3. 新增web模块,修改web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<servlet>
<servlet-name>DispatcherServlet</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>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1.4. 新增SpringMVC配置文件springMVC.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.example.mvc.controller"></context:component-scan>
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1" />
<property name="characterEncoding" value="UTF-8" />
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/" />
<!-- 视图后缀 -->
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
<mvc:view-controller path="/" view-name="index" />
<mvc:annotation-driven/>
</beans>
1.5. 创建控制器EmployeeController
package com.example.mvc.controller;
import org.springframework.stereotype.Controller;
@Controller
public class EmployeeController {
}
1.6. 创建视图
在WEB-INF下创建目录templates,在templates目录下创建视图文件index.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>
1.7. 在本地tomcat上部署、运行应用
1.8. 添加实体类Employee
package com.example.mvc.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String fullname;
private String email;
private Integer gender;
}
1.9 添加dao层
package com.example.mvc.dao;
import com.example.mvc.bean.Employee;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class EmployeeDao {
private static Map<Integer,Employee> employees = null;
static {
employees = new HashMap<Integer,Employee>();
employees.put(1001,new Employee(1001,"Steve Jobs","[email protected]",1));
employees.put(1002,new Employee(1002,"Mark Elliot Zuckerberg","[email protected]",1));
employees.put(1003,new Employee(1003,"Elon Musk","[email protected]",1));
employees.put(1004,new Employee(1004,"Jeff Bezos","[email protected]",1));
}
private static Integer initId = 1005;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
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);
}
}
注意两点:
@Repository标注EmployeeDao
修改SpringMVC配置文件springMVC.xml,需要扫描com.example.mvc.dao,以将EmployeeDao注入容器
<context:component-scan base-package="com.example.mvc.controller,com.example.mvc.dao"></context:component-scan>
1
2. 实现查询功能
功能 请求路径 请求方法
查询所有员工信息 /employee GET
2.1. 修改视图文件index.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/employee}">查询所有员工信息</a>
</body>
</html>
2.2. 修改控制器EmployeeController。
package com.example.mvc.controller;
import com.example.mvc.bean.Employee;
import com.example.mvc.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getAll(Model model) {
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("employees",employees);
return "employee_list";
}
}
2.3. 添加视图文件employee_list.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>列表</title>
</head>
<body>
<table border="1">
<tr>
<th>id</th>
<th>fullname</th>
<th>email</th>
<th>gender</th>
</tr>
<tr th:each="employee:${employees}">
<td th:text="${employee.id}"></td>
<td th:text="${employee.fullname}"></td>
<td th:text="${employee.email}"></td>
<td th:text="${employee.gender}"></td>
</tr>
</table>
</body>
</html>
2.4. 运行应用 ,查看效果。
3. 实现删除功能
功能 请求路径 请求方法
删除员工信息 /employee/1001 DELETE
3.1. 修改视图文件employee_list.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>列表</title>
</head>
<body>
<table border="1">
<tr>
<th>id</th>
<th>fullname</th>
<th>email</th>
<th>gender</th>
<th>options</th>
</tr>
<tr th:each="employee:${employees}">
<td th:text="${employee.id}"></td>
<td th:text="${employee.fullname}"></td>
<td th:text="${employee.email}"></td>
<td th:text="${employee.gender}"></td>
<td>
<a th:href="@{'/employee/'+${employee.id}}" onclick="deleteEmpolyee()">delete</a>
</td>
</tr>
</table>
<form method="post" id="deleteForm">
<input type="hidden" name="_method" value="delete"/>
</form>
<script>
function deleteEmpolyee(){
var deleteForm = document.getElementById("deleteForm");
deleteForm.action = event.target.href;
deleteForm.submit();
event.preventDefault();
}
</script>
</body>
</html>
3.2. 修改控制器EmployeeController,添加如下控制器方法。
@RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/employee";
}
3.3. 启动应用,查看效果。
4. 实现更新功能
功能 请求路径 请求方法
根据id查询员工信息 /employee/1001 GET
更新员工信息 /employee PUT
4.1. 修改视图文件employee_list.html。
<td>
<a th:href="@{'/employee/'+${employee.id}}" onclick="deleteEmpolyee()">delete</a>
<a th:href="@{'/employee/'+${employee.id}}">update</a>
</td>
4.2. 新增视图文件employee_update.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>更新</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
<input type="hidden" name="_method" value="put"/>
<input type="hidden" name="id" th:value="${employee.id}"/>
fullname:<input type="text" name="fullname" th:value="${employee.fullname}"/><br/>
email:<input type="text" name="email" th:value="${employee.email}"/><br/>
gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}"/>male
<input type="radio" name="gender" value="0" th:field="${employee.gender}" />female<br/>
<input type="submit" value="update"/>
</form>
</body>
</html>
4.3. 修改控制器EmployeeController,添加如下控制器方法。
@RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id,Model model){
Employee employee = employeeDao.get(id);
model.addAttribute("employee",employee);
return "employee_update";
}
@RequestMapping(value = "/employee",method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
employeeDao.save(employee);
return "redirect:/employee";
}
4.4. 启动应用,查看效果。
5. 实现新增功能
功能 请求路径 请求方法
新增员工信息 /employee POST
5.1. 修改视图文件employee_list.html。
<a th:href="@{/add}">add</a>
1
5.2. 修改SpringMVC配置文件springMVC.xml,添加如下视图控制器,
<mvc:view-controller path="/add" view-name="employee_add"/>
1
5.3. 新增视图文件employee_add.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>新增</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
fullname:<input type="text" name="fullname"/><br/>
email:<input type="text" name="email"/><br/>
gender:<input type="radio" name="gender" value="1"/>male
<input type="radio" name="gender" value="0"/>female<br/>
<input type="submit" value="add"/>
</form>
</body>
</html>
5.4. 修改控制器EmployeeController,添加如下控制器方法。
@RequestMapping(value = "/employee",method = RequestMethod.POST)
public String addEmployee(Employee employee){
employeeDao.save(employee);
return "redirect:/employee";
}
5.5. 启动应用,查看效果。
6. 添加静态资源
6.1. 在webapp目录下新建子目录static,在static下新建index.css,内容如下。
body>a:first-of-type{
display: inline-block;
margin: 10px 0;
padding: 5px 15px;
background: darkgoldenrod;
color: #fff;
text-decoration: none;
}
6.2. 修改视图文件employee_list.html,引入样式文件index.css。
<head>
<meta charset="UTF-8">
<title>列表</title>
<link rel="stylesheet" th:href="@{/static/index.css}"/>
</head>
6.3. 修改SpringMVC配置文件springMVC.xml,添加default-servlet-handler,用来开放对静态资源的调用。
<mvc:default-servlet-handler/>
说到这儿,得提下tomcat自带的web.xml,其中有如下一段配置,
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings (defined either here or in your own -->
<!-- web.xml file). -->
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- The JSP page compiler and execution servlet, which is the mechanism -->
<!-- used by Tomcat to support JSP pages. Traditionally, this servlet -->
<!-- is mapped to the URL pattern "*.jsp". -->
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<!-- The mapping for the default servlet -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- The mappings for the JSP servlet -->
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspx</url-pattern>
</servlet-mapping>
这段配置里有两个Servlet:DefaultServlet和JspServlet。
再加上我们自己在demo项目的web.xml里配置的DispatcherServlet,当前至少有3个servlet了。
DispatcherServlet
<url-pattern>*.jspx</url-pattern>,用来接收、处理除jsp以外的所有请求。
JspServlet
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspx</url-pattern>
用来接收、处理jsp请求。
DefaultServlet
<url-pattern>/</url-pattern>,用来接收所有请求。
也就是说,JspServlet、DispatcherServlet无法处理的请求,最后都会交给DefaultServlet处理,如果DefaultServlet也无法处理则报错。
对静态资源的访问,就是JspServlet和Dispatcher都无法处理的请求,所以最终其实是由DefaultServlet来处理的。
<mvc:annotation-driven/>,开启注解驱动,其实就是让DispatcherServlet处理所有请求。
<mvc:default-servlet-handler/>,开启静态资源访问,其实就是让DefaultServlet来处理静态资源访问这类请求。
6.4. 启动应用,查看效果。
标签:Employee,springframework,案例,org,employee,import,RESTFul,id From: https://www.cnblogs.com/kn-zheng/p/17049177.html