关闭

springmvc实现Resetful风格url(maven项目)

633人阅读 评论(0) 收藏 举报

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>imooc-arthur</groupId>
	<artifactId>spring-mvc-study</artifactId>
	<version>1.0.0-SNAPSHOT</version>

	<properties>
		<commons-lang.version>2.6</commons-lang.version>
		<slf4j.version>1.7.6</slf4j.version>
		<spring.version>4.1.3.RELEASE</spring.version>
        <jackson.version>2.5.4</jackson.version>
	</properties>


	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-framework-bom</artifactId>
				<version>${spring.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>${commons-lang.version}</version>
		</dependency>


		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.2.2.v20140723</version>
			</plugin>
		</plugins>
	</build>

</project></span>
web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="3.0"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  <display-name></display-name>   
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>   
    <!-- 添加对spring的支持 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>        
    <!-- Spring 刷新Introspector防止内存泄露 -->  
     <listener>  
         <listener-class>  
             org.springframework.web.util.IntrospectorCleanupListener  
         </listener-class>  
     </listener>  
    <!-- Spring MVC配置 -->  
    <servlet>  
        <servlet-name>spring</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>spring</servlet-name>  
         <!-- 不能是/*,否则会报404 -->  
        <url-pattern>/</url-pattern>   
    </servlet-mapping>  
    <!-- 浏览器不支持put,delete等method,由该filter将/user?_method=delete转换为标准的http delete方法 -->    
    <filter>    
       <filter-name>HiddenHttpMethodFilter</filter-name>    
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>    
    </filter>       
    <filter-mapping>    
       <filter-name>HiddenHttpMethodFilter</filter-name>    
       <!-- spring 名称一定要和servlet-mapping中servlet name一致 -->  
       <servlet-name>spring</servlet-name>     
    </filter-mapping>    
    <!-- 指定Spring配置文件位置 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:applicationContext.xml</param-value>  
    </context-param>  
</web-app>  <span style="font-family: Arial, Helvetica, sans-serif;"> </span>

spring-servlet.java

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="   
                http://www.springframework.org/schema/beans   
                http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
                http://www.springframework.org/schema/context   
                http://www.springframework.org/schema/context/spring-context-4.0.xsd   
                http://www.springframework.org/schema/mvc   
                http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
  
    <!-- Spring MVC扫描Control -->  
    <context:component-scan base-package="com.springmvc.control" />  
  
    <!-- 使用如下两个class激活@RequestMapping annotation -->  
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
  
  
    <!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 -->  
    <!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 -->  
    <mvc:resources location="/*.html" mapping="/**.html" />  
    <mvc:resources location="/css/*" mapping="/css/**" />  
    <mvc:resources location="/js/*" mapping="/js/**" />  
    <mvc:resources location="/images/*" mapping="/images/**" />  
  
    <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->  
    <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
  
    <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->  
    <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>  
</beans>  

UserController.java

package com.springmvc.control;  
  
import javax.annotation.Resource;  
import javax.ws.rs.PathParam;  
import javax.ws.rs.Produces;  
  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import org.springframework.stereotype.Repository;  
import org.springframework.ui.Model;  
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.servlet.ModelAndView;  
import com.springmvc.model.User;  
import com.springmvc.service.UserService;  
/** 
 * Scope:表示实例是原型,这样会对每一个请求实例化,保证线程安全 Spring中使用 Controller注解表示该类是控制器 
 * Repository注解Dao访问类 Service注解业务逻辑处理类 Resource注解表示使用某个bean资源 
 * RequestMapping:表示对该类所有方法的请求URL,前面必须接上/user,如/user/login 表示对login方法的请求访问 
 *  
 * @author Administrator 
 *  
 */  
@Scope("prototype")  
@Controller  
@RequestMapping("/user")  
public class UserControl {  
    @Resource(name = "userService")  
    private UserService userService;  
    private String message;  
    /** 
     *  
     * Spring MVC中使用RequestMapping处理URL请求, 
     *     GET:表示查询;POST:表示添加操作 
     *     PUT:表示修改操作;DELETE:表示删除操作 
     * ResponseBody:表示返回对象或者值; 
     * consumes: 表示前端传过来的数据格式; 
     * produces:表示返回数据格式 
     */  
    @RequestMapping(value = "/login", method = RequestMethod.GET, consumes = "application/json", produces = "application/json")  
    @ResponseBody  
    public User login(User user, Model model) {  
        // System.out.println(user.getUsername());  
        User u = userService.findUserByNameAndPassword(user);  
        return u;  
    }    
    @RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = "application/json")  
    @ResponseBody  
    public String addUser(User user) {  
        boolean flag = userService.addUser(user);  
        if (flag) {  
            message = "success";  
        } else {  
            message = "error";  
        }  
        return message;  
    }  
  
    /** 
     * PathVariable:注解方法参数,表示该参数变量值是通过URL传递的 
     * URL中必须包含该参数变量名,变量名需要相同才能完成变量传递注入 
     */  
    @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.DELETE, produces = "application/json")  
    @ResponseBody  
    public String deleteUser(@PathVariable Integer id) {  
        boolean flag = userService.deleteUser(id);  
        if (flag) {  
            message = "success";  
        } else {  
            message = "error";  
        }  
        return message;  
    }  
  
    public void setUserService(UserService userService) {  
        this.userService = userService;  
    }  
    public UserService getUserService() {  
        return userService;  
    }  
}  

前端JSP页面Ajax请求

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
<head>  
<base href="<%=basePath%>">  
  
<title>My JSP 'index.jsp' starting page</title>  
<meta http-equiv="pragma" content="no-cache">  
<meta http-equiv="cache-control" content="no-cache">  
<meta http-equiv="expires" content="0">  
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
<meta http-equiv="description" content="This is my page">  
<!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    -->  
<!-- action uri 前面不能加/ 否则路径变成从根开始  -->  
<!-- <script type="text/javascript" src="js/jquery-easyui-1.4.4/jquery.min.js"></script> -->  
<script type="text/javascript"  
    src="js/jquery-easyui-1.4.4//jquery.min.js"></script>  
<script type="text/javascript">  
    $(document).ready(  
            function() {  
                $("#btnQuery").click(  
                        function() {  
                            var username = $("#username").val();  
                            var password = $("#password").val();  
                            var data = {  
                                "username" : username,  
                                "password" : password  
                            };  
                            // alert(JSON.stringify(data));  
                            $.ajax({  
                                type : "GET",  
                                url : "user/login",  
                                dataType : "json", //后台返回值类型  
                                data : data,  
                                beforeSubmit : function() {  
  
                                },  
                                success : function(data) {  
                                    alert(data.username + " " + data.password  
                                            + " " + data.address + " "  
                                            + data.tel);  
  
                                },  
                                error : function(data) {  
                                    alert("error");  
                                }  
                            });  
                        });  
                $("#btnAdd").click(  
                        function() {  
                            var username = $("#username").val();  
                            var password = $("#password").val();  
                            var address = $("#address").val();  
                            var tel = $("#tel").val();  
                            var data = {  
                                "username" : username,  
                                "password" : password,  
                                "address" : address,  
                                "tel" : tel  
                            };  
                              
                            $.ajax({  
                                type : "POST",  
                                url : "user/addUser",  
                                dataType : "json", //后台返回值类型  
                                data : data,  
                                beforeSubmit : function() {  
  
                                },  
                                success : function(data) {  
                                    if(data == 'success') {  
                                        alert("添加成功");  
                                    }else {  
                                        alert("添加失败");  
                                    }  
                                },  
                                error : function(data) {  
                                    alert("error");  
                                }  
                            });  
                        });  
                  
                  
                $("#btnDel").click(  
                        function() {  
                            var id = $("#id").val();  
                            $.ajax({  
                                type : "DELETE",  
                                url : "user/deleteUser/"+id,  
                                dataType : "json", //后台返回值类型  
                                beforeSubmit : function() {  
  
                                },  
                                success : function(data) {  
                                    if(data == 'success') {  
                                        alert("删除成功");  
                                    }else {  
                                        alert("删除失败");  
                                    }  
                                },  
                                error : function(data) {  
                                    alert("error");  
                                }  
                            });  
                        });  
            });  
</script>  
</head>  
  
<body>  
      
   <!-- 查询 -->  
    用户名:  
    <input type="text" id="username" value="xx">  
    <br> 密码:  
    <input type="password" id="password" value="1233">  
    <br>  
    <a href="javascript:void(0)" id="btnQuery">查询</a>  
      
    <br>  
    <!-- 添加 -->  
    用户名:  
    <input type="text" id="username" value="张三图">  
    <br> 密码:  
    <input type="password" id="password" value="1233">  
    <br> 地址:  
    <input type="text" id="address" value="安徽天长">  
    <br> 联系方式:  
    <input type="password" id="tel" value="1232333">  
    <br>  
    <input type="button" id="btnAdd" value="提交">  
  
    <br>  
    <!-- 删除 -->  
    <input type="text" id="id" value="51">  
    <input type="button" id="btnDel" value="删除">  
      
    <%--  
     <form:form action="user/login" method="post">  
                 用户名:<input type="text" name="username" value="xx"><br>  
                   密码:    <input type="password" name="password" value="1233"><br>  
                       用户名:<input type="text" name="address" value="ss"><br>  
                   密码:    <input type="password" name="tel" value="1232333"><br>  
        <input type="submit" value="提交">  
     </form:form>  
       
      --%>  
    <%--<form:form action="user/deleteUser/50" method="delete">  
        <input type="submit" value="提交">  
     </form:form>  
  --%>  
</body>  
</html>  
HTTP请求中本身是不支持PUT和DELETE method方法请求的,本文在web.xml中添加了过滤器处理该部分请求,并且通过Ajax发送请求。但是Spring MVC本身也提供了<form:form>标签,通过表单提交的方式发送Restful请求,如上面代码中注释内容所示。只需要在页面前面导入标签库即可。

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  

1
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:49146次
    • 积分:936
    • 等级:
    • 排名:千里之外
    • 原创:38篇
    • 转载:52篇
    • 译文:0篇
    • 评论:6条