SpringMVC个人零碎总结

前言:对于工作多年的同学来说,相信都接触过了SpringMVC:,但在使用的过程中,多少会心里打鼓,或者还有很多疑问没搞明白,本篇文章就我自己的使用心得做出一个总结,希望能够帮助很多那些还在前行路上摸索的同学。

Q1:当映射路径为,关于对Controller中具体方法访问时需要注意的地方

比如我们在Controller中定义了这么个方法

@RequestMapping(value="/test", method = {RequestMethod.GET})
public String test(){
   return "index";
}

访问方式应该很简单吧,直接 http://localhost:8080/SpringMVC/test 如下图

那给其加上后缀,还能访问到吗,比如

http://localhost:8080/SpringMVC/test.action

http://localhost:8080/SpringMVC/test.abc

答案是可以的,如下图

可以发现,任意后缀都可以,但在项目开发中,到底加不加这个后缀,我给的答案是,如果项目组有要求,URI统一格式都是以某某为后缀,你还是加上吧,虽然你不加最终访问的时候并不会影响,但怎么说呢,保持一致吧。

Q2:Ajax和SpringMVC之间的交互

比如现有如下界面:

<form id="login">
        账 号:<input type="text" name="username" id="username" ><br/>
        密 码:<input type="password" name="password" id="password"><br/>
        <input type="button" id="submit" value="Submit" />
</form>

ajax请求如下:

$(function() {
    $("#submit").click(function() {
        var json = {
              ‘username‘:$(‘#username‘).val(),
              ‘password‘:$(‘#password‘).val()
        };
        //json字符串 {"username":"admin","password":"123456"}
        var postdata = JSON.stringify(json);
        alert(postdata);
        $.ajax({
                type : ‘POST‘,
                contentType : ‘application/json‘,
                processData : false,
                url : ‘<%=path%>/databind/json‘,
                dataType : ‘json‘,
                data : postdata,
                success : function(data) {
                   alert(‘username : ‘+data.username+‘\npassword : ‘+data.password);
                }
        });
   });
});

tip:我们可以看到在用contentType : ‘application/json’发起请求,data我们传的是一个json字符串,而不是json对象,一开始我也认为是可以的,结果不行,直接传对象报错,不妨亲自试试。

SpringMVC需要提供的方法如下:

@RequestMapping(value="/json", method = {RequestMethod.POST})
@ResponseBody
public Account json(@RequestBody Account account){
    System.out.println(account);
    return account;
}

那还是contentType : ‘application/json’发起的请求,我们能不能用如下的方式接收值呢

@RequestMapping(value="json", method = {RequestMethod.POST})
@ResponseBody
public Account json(String username, String password){
    Account account = new Account();
    account.setUsername(username);
    account.setPassword(password);
    return account;
}

答案是不可以的,会抛异常,400 Bad Request

究其原因是:application/json数据发送后台接收必须是Modle,不能是单个属性,且必须加上@RequestBody注解。

如果我们把contentType换成默认的contentType : ‘application/x-www-form-urlencoded’呢,前后台又该怎么写

ajax写法如下:

$(function(){
    $("#submit").click(function(){
           $.ajax({
               type: "POST",
               /* contentType : ‘application/x-www-form-urlencoded‘,*/
               url:  ‘<%=path%>/databind/json‘,
               dataType: "json",
               data: {username:$(‘#username‘).val(),
                      password:$(‘#password‘).val()},
               success: function(data){
                    alert(‘username : ‘+data.username+‘\npassword : ‘+data.password);
               }
           });
    });
});

这里不得不提下,虽然data这里看起来传的是一个json对象,但由于使用了application/x-www-form-urlencoded,最终可以通过firebug可以看到,其实最终传过去的还是username=admin&password=123456,当然你也可以直接传这么个字符串过去,但是有一点要注意,真实项目中字段还是特别多的,这样拼接会相当繁琐,然而我们知道还有个方法供我们使用,jQuery给我们提供的$(“#login”).serialize()序列化表单。

$(function(){
    $("#submit").click(function(){
           var params = $("#login").serialize();
           alert(params);
           $.ajax({
               type: "POST",
               url:  ‘<%=path%>/databind/json‘,
               dataType: "json",
               data: params,
               success: function(data){
                    alert(‘username : ‘+data.username+‘\npassword : ‘+data.password);
               }
           });
    });
});

我提供的这两种方式归根结底其实是一样的,切记,切记。。。

后台接收方式如下:

@RequestMapping(value="json", method = {RequestMethod.POST})
@ResponseBody
public Account json(String username,String password){
    Account account = new Account();
    account.setUsername(username);
    account.setPassword(password);
    return account;
}

那这里要提出一个疑问,如果我需要接受的字段特别多呢,难道我在方法中也需要一个一个参数的去写嘛,比如有20个,还不得累死。

答案是当然啦

@RequestMapping(value="/json", method = {RequestMethod.POST})
@ResponseBody
public Account json(Account account){
    System.out.println(account);
    return account;
}

Q3:什么时候该用@RequestParam注解,什么时候不该用

前面我们已经看到了,接受单个基本类型值的参数,只要在方法中分别写下,并且并不需要使用什么注解就能拿到传过来的值,那为什么还有@RequestParam这个注解呢,并且看到很多地方都在用。

其实呢这个注解,有它的用处,并不是一无是处,首先作为基本类型的参数,如果不使用注解,是可传可不传的,如果为null并不会报错,但当你使用了@RequestParam注解,那么此时该参数就是必传的了,如果不传就不会报错,然而还是可以通过配置来让其可不必传,如@RequestParam(value=”username”, required=false),此外,该注解还可以设置如果前台没有传值过来,会给一个默认值,如@RequestParam(value=”username”, defaultValue=”ruo”)。

我对该注解做的总结是:如果你某个参数不是必传的,就别用它了,如果是必传的,请一定用上它,如果必传参数可以有默认值的话,还请加上defaultValue默认值。

Q4:SpringMVC都有哪些方式可以用来给前端界面传递对象,用来绑定显示

方式有三种,现提供测试例子如下

    <form action="<%=path%>/databind/modelautobind" method="post">
        用户名:<input type="text" name="username"><br/>
        密 码:<input type="password" name="password"><br/>
        <input type="submit" value="Submit" />
    </form>
    <hr>
    <form action="<%=path%>/databind/modelautobind2" method="post">
        用户名:<input type="text" name="username"><br/>
        密 码:<input type="password" name="password"><br/>
        <input type="submit" value="Submit" />
    </form>
    <hr>
    <form action="<%=path%>/databind/modelautobind3" method="post">
        用户名:<input type="text" name="username"><br/>
        密 码:<input type="password" name="password"><br/>
        <input type="submit" value="Submit" />
    </form>

跳转结果界面如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
用户名:${account.username}<br/>
密  码:${account.password}
</body>
</html>

我们使用了三种不同的请求路径URI,现在我们来看看都是如何实现的

@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
public String modelAutoBind(@ModelAttribute("account") Account account){
    System.out.println("第一种方式:" + account);
    return "modelautobindresult";
}

@RequestMapping(value="/modelautobind2", method = {RequestMethod.POST})
public String modelAutoBind(Model model, Account account){
    System.out.println("第二种方式:" + account);
    model.addAttribute("account", account);
    return "modelautobindresult";
}

@RequestMapping(value="/modelautobind3", method = {RequestMethod.POST})
public String modelAutoBind(HttpServletRequest request,Account account){
    System.out.println("第三种方式:" + account);
    request.setAttribute("account", account);
   return "modelautobindresult";
}

这三种方式都是可以的,看结果界面如下:

方式一:

方式二:

方式三:

最后想说的是,使用哪一种,就看个人习惯吧。

时间: 2024-08-01 22:44:03

SpringMVC个人零碎总结的相关文章

MyEclipse建立SpringMVC入门HelloWorld项目

一.首先,建立空的web project项目: 1. 2. 3. 二.其次,导入先关jar包 1.将jar包导入SpringMVCHelloWorld\WebRoot\WEB-INF\lib目录下 三.接下来修改web.xml文件,在web中,指定我们的DispatcherServlet.(从这里进入SpringMVC的可控范围). 1. 2.web.xml中的内容如下: <?xml version="1.0" encoding="UTF-8"?> &l

SpringMVC后台使用对象接受参数字符串转日期

在springMVC配置文件中加入: <bean id="dateConvert" class="com.iomp.util.DateConvert"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property

springMVC+MyBatis+Spring 整合(3)

spring mvc 与mybatis 的整合. 加入配置文件: spring-mybaits.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" xm

SpringMVC 入门

1. SpringMVC 是什么 Spring MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring MVC也是要简化我们日常Web开发的. Spring MVC也是服务到工作者模式的实现,但进行可优化.前端控制器是DispatcherServlet:应用控制器其实拆为处理器映射器(Handler Mapping)进行处理器

SpringMVC中文件上传的客户端验证

SpringMVC中文件上传的客户端验证 客户端验证主要思想:在jsp页面中利用javascript进行对文件的判断,完成验证后允许上传 验证步骤:1.文件名称 2.获取文件的后缀名称 3.判断哪些文件类型允许上传 4.判断文件大小 5.满足条件后跳转后台实现上传 前台界面(验证上传文件是否格式满足要求): <body> <h2>文件上传</h2> <form action="upload01" method="post" 

【巨坑】springmvc 输出json格式数据的几种方式!

最近公司项目需要发布一些数据服务,从设计到实现两天就弄完了,心中窃喜之. 结果临近部署时突然发现.....  服务输出的JSON 数据中  date 类型数据输出格式要么是时间戳,要么是  {"date":26,"day":1,"hours":21,"minutes":38,"month":5,"seconds":22,"time":1498484302259,&qu

springmvc 类型转换器 自定义类型转换器

自定义类型转换器的步骤: 1.定义类型转换器 2.类型转换器的注册(在springmvc配置文件处理) 来解决多种日期格式的问题:

springMVC简单例子

spring MVC是显示层的mvc框架,和struts可以比较:和spring.hibernate没有比较性. 一 .开发流程 1)引jar包 //spring_core spring3.2.9core\commons-logging-1.2.jar spring3.2.9core\spring-beans-3.2.9.RELEASE.jar spring3.2.9core\spring-context-3.2.9.RELEASE.jar spring3.2.9core\spring-core

Maven+SpringMVC+Freemarker入门Demo

1 参考http://blog.csdn.net/haishu_zheng/article/details/51490299,用第二种方法创建一个名为mavenspringmvcfreemarker的Maven工程. 2 文件目录结构如下图所示 3 在pom.xml中添加springmvc和freemarker的依赖包,添加完之后的完整内容为 [html] view plain copy <project xmlns="http://maven.apache.org/POM/4.0.0&q