SpringMVC基础-16-基于SpringMVC的restful架构风格

pom.xml

<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.monkey1024</groupId>
  <artifactId>05mvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.4</version>
		</dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
 
    </dependencies>
    <build>
    	<!-- 与工程名一致 -->
        <finalName>05mvc</finalName>
        <plugins>
            <!-- 编译插件,指定编译用的的jdk版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <!-- jdk的版本号 -->
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <servlet>
    <servlet-name>springMVC</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>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

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:p="http://www.springframework.org/schema/p"
       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
        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 	<!-- 解决返回json数据乱码问题 -->
 	<bean id="stringHttpMessageConverter"
 	class ="org.springframework.http.converter.StringHttpMessageConverter">
 		<property name="supportedMediaTypes">
 			<list>
 				<value>text/plain;charset=UTF-8</value>
 				<value>application/json;charset=UTF-8</value>
 			</list>
 		</property>
 	</bean>
 	<!-- 注解驱动 -->
 	<mvc:annotation-driven>
 		<mvc:message-converters>
 			<ref bean="stringHttpMessageConverter"/>
 		</mvc:message-converters>
 	</mvc:annotation-driven>
 	
 	<!-- 注册组件扫描器 -->
 	<context:component-scan base-package="com.monkey1024.*"/>
 	
	<!-- 静态资源 -->
	<mvc:resources mapping="/images/**" location="/images/"/>
	<mvc:resources mapping="/js/**" location = "/js/"/>
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="html/**" location="/html/" />
	
	<!-- 内部视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	
 
</beans> 

User.java

package com.monkey1024.bean;

import java.time.LocalDate;

import org.springframework.format.annotation.DateTimeFormat;

/*
 * 用户
 */
public class User {	
	private String name;
	
	private String phone;
	
	private String address;
	
	@DateTimeFormat(pattern = "yyyy-MM-dd")
	private LocalDate birthday;
	
	public User(){}
	
	public User(String name, String phone, String address, LocalDate birthday){
		this.name = name;
		this.phone = phone;
		this.address = address;
		this.birthday = birthday;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public LocalDate getBirthday() {
		return birthday;
	}

	public void setBirthday(LocalDate birthday) {
		this.birthday = birthday;
	}

}

DataUtil.java

package com.monkey1024.util;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.monkey1024.bean.User;

/*
  * 模拟生成数据的工具类
 */
public class DataUtil {
	private static HashMap<String,User> dataMap = new HashMap<>();
	
	//模拟初始化数据
	static{
		User user1 = new User("jack","18888888","北京",LocalDate.of(2012, 1, 1));
		User user2 = new User("paul","16666666","上海",LocalDate.of(2013, 1, 1));
		User user3 = new User("andy","19999999","深圳",LocalDate.of(2014, 1, 1));
		dataMap.put("1", user1);
		dataMap.put("2", user2);
		dataMap.put("3", user3);
	}
	
	/*
	 * 查询全部数据
	 */
	public static HashMap<String,User> findAll(){
		return dataMap;
	}
	/*
	 * 根据id进行查询
	 */
	public static User findUserById(String id){
		return dataMap.get(id);
	} 
	
	/*
	 * 添加操作
	 */
	public static void create(User user) throws Exception{
		//遍历map找到key的最大值
		Set<Map.Entry<String,User>> entries = dataMap.entrySet();
		Iterator<Map.Entry<String,User>> iterator = entries.iterator();
		
		int max = 3;
		while(iterator.hasNext()){
			Map.Entry<String, User> next = iterator.next();
			int i = Integer.parseInt(next.getKey());
			if(max<i){
				max = i;
			}
		}
		//将最大值做自增运算,然后作为key放到map中
		dataMap.put(++max+"", user);
	}
	
	/*
	 * 修改用户
	 */
	public static void update(String id,User user) throws Exception{
		dataMap.put(id, user);
	}
	/*
	 * 删除用户
	 */
	public static void delete(String id) throws Exception{
		dataMap.remove(id);
	}
}

UserRestController.java

package com.monkey1024.controller;

import java.util.HashMap;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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.RestController;

import com.alibaba.fastjson.JSON;
import com.monkey1024.bean.User;
import com.monkey1024.util.DataUtil;

/*
 * 基于restful风格的增删改查示例
 */
@RestController
public class UserRestController {
	/*
	 * 查询所有用户
	 */
	@GetMapping("/users")
//	@RequestMapping(value="/users",method=RequestMethod.POST)
	public String findAll() throws Exception{
		HashMap<String,User> allUser = DataUtil.findAll();
		//返回json格式的数据
		return JSON.toJSONString(allUser);
	}
	/*
	 * 根据id查找
	 */
	@GetMapping("/users/{id}")
	public String findById(@PathVariable String id) throws Exception{
		User user = DataUtil.findUserById(id);
		return JSON.toJSONString(user);
	}
	
	/*
	 * 新增
	 */
	@PostMapping("/users")
	public String create(@RequestBody User user){
		try{
			DataUtil.create(user);
		}catch(Exception e){
			e.printStackTrace();
			return JSON.toJSONString("fail");
		}
		return JSON.toJSONString("success");
	}
	
	/*
	 * 更新
	 */
	@PutMapping("/users/{id}")
	public String update(@PathVariable String id,@RequestBody User user){
		try{
			DataUtil.update(id, user);
		}catch (Exception e){
			e.printStackTrace();
			return JSON.toJSONString("fail");
		}
		return JSON.toJSONString("success");
	}
	
	/*
	 * 删除
	 */
	@DeleteMapping("/users/{id}")
	public String delete(@PathVariable String id){
		try{
			DataUtil.delete(id);
		}catch(Exception e){
			e.printStackTrace();
			return JSON.toJSONString("fail");
		}
		return JSON.toJSONString("success");
	}
}

user_list.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

</head>
<body>
<div class="container theme-showcase" role="main">
	<div id="msg">
		<div class="alert alert-info" role="alert">删除成功!</div>
	</div>
    <div class="page-header">
        <input type="text" name="id" placeholder="请输入id">
        <button id="query" type="button" class="btn btn-sm btn-primary">查询</button>
        <button id="add" type="button" class="btn btn-sm btn-success">添加</button>
    </div>
    <div class="row">
        <div class="">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>手机</th>
                    <th>生日</th>
                    <th>地址</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="tbody">
                <tr>
                    <td>1</td>
                    <td>jack</td>
                    <td>15188888888</td>
					<td>2010-01-01</td>
                    <td>北京</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-info">删除</button>
                        <button type="button" class="btn btn-sm btn-warning">修改</button>
                    </td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>paul</td>
                    <td>15188888888</td>
					<td>2018-01-01</td>
                    <td>上海</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-info">删除</button>
                        <button type="button" class="btn btn-sm btn-warning">修改</button>
                    </td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>andy</td>
                    <td>15188888888</td>
					<td>2016-01-01</td>
                    <td>广州</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-info">删除</button>
                        <button type="button" class="btn btn-sm btn-warning">修改</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
    $(function () {
		//绑定添加按钮的点击事件
		$("#add").click(function(){
			$(location).attr("href","/html/user_add.html");
		});
    });
    function findAll(){
    	$.ajax({
    		url:"/users",
    		type:"get",
    		dataType:"json",
    		success:function(result){
    			var dataTR = "";
    			//动态拼接后台返回的数据
    			$.each(result,function(index,value){
    				 var  dataTR =
    	                    "<tr>" +
    	                    "<td>" + userId + "</td>" +
    	                    "<td>" + result.name + "</td>" +
    	                    "<td>" + result.phone + "</td>" +
    	                    "<td>" + result.birthday + "</td>" +
    	                    "<td>" + result.address + "</td>" +
    	                    "<td>" +
    	                    "<button type='button' class='btn btn-sm btn-info' >删除</button>" +
    	                    "<button type='button' class='btn btn-sm btn-warning' >修改</button>" +
    	                    "</td>" +
    	                    "</tr>";

    			});
    			$("#tbody").html(dataTR);
    		}
    	});
    }
</script>
</body>
</html>

user_add.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="../css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="page-header"></div>
<div class="container">
    <form id="user-form" style="max-width: 330px;padding: 15px;margin: 0 auto;">
        <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" class="form-control" id="name" name="name">
        </div>
        <div class="form-group">
            <label for="phone">手机:</label>
            <input type="text" class="form-control" id="phone" name="phone">
        </div>
        <div class="form-group">
            <label for="birthday">生日:</label>
            <input type="date" class="form-control" id="birthday" name="birthday">
        </div>
        <div class="form-group">
            <label for="address">地址:</label>
            <input type="text" class="form-control" id="address" name="address">
        </div>

        <input type="submit" value="提交">
    </form>
</div>
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
	
</script>
</body>
</html>

user_update.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="../css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="page-header"></div>
<div class="container">
    <form action="" method="post" style="max-width: 330px;padding: 15px;margin: 0 auto;">
        <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" class="form-control" id="name">
        </div>
        <div class="form-group">
            <label for="phone">手机:</label>
            <input type="text" class="form-control" id="phone">
        </div>
        <div class="form-group">
            <label for="birthday">生日:</label>
            <input type="date" class="form-control" id="birthday">
        </div>
        <div class="form-group">
            <label for="address">地址:</label>
            <input type="text" class="form-control" id="address">
        </div>

        <input type="submit" value="提交">
    </form>
</div>
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="../js/bootstrap.js"></script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_38826019/article/details/89453950
今日推荐