springMVC参数的获取区别

在springMVC中我们一般使用注解的形式来完成web项目,但是如果不明白springmvc的对于不同注解的应用场景就会很容易犯错误

1、什么是restful形式:

  什么是RESTful

restful形式的在springmvc中使用需要修改前端控制器:非restful形式的是.do或者.action。而restful形式的是/.

两者可以都在web.xml中配置两种前端控制器。但是注意:改为restful形式的需要设置静态资源映射,因为js、css等文件springmvc访问不到了,需要在springMVC.xml中设置

静态资源映射:

	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 加载springmvc配置 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- 配置文件的地址 如果不配置contextConfigLocation, 默认查找的配置文件名称classpath下的:servlet名称+"-serlvet.xml"即:springmvc-serlvet.xml -->
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>

	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
<!-- 可以配置/ ,此工程 所有请求全部由springmvc解析,此种方式可以实现 RESTful方式,
需要特殊处理对静态文件的解析不能由springmvc解析 
可以配置*.do或*.action,所有请求的url扩展名为.do或.action由springmvc解析,
(这里的url配置即网页访问的链接路径,如果使用restful形式,则配为/,此时需要在springmvc中配置资源映射:<mvc:resource....>
如果不是/,则用*.do或*.action,此时不需要配置资源映射,springmvc就可以解析这些静态文件)
此种方法常用 不可以/*,如果配置/*,返回jsp也由springmvc解析,这是不对的。 -->
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<!-- restful的配置 -->
	<servlet>
		<servlet-name>springmvc_rest</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 加载springmvc配置 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- 配置文件的地址 如果不配置contextConfigLocation, 默认查找的配置文件名称classpath下的:servlet名称+"-serlvet.xml"即:springmvc-serlvet.xml -->
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>

	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc_rest</servlet-name>
		<!-- rest方式配置为/ -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

  

restfu形式是否获取json格式的数据,在http头文件中的accept与Content-Type中就确定了使用哪种数据。

RESTful软件开发理念,RESTful对http进行非常好的诠释。

RESTful即Representational State Transfer的缩写。

综合上面的解释,我们总结一下什么是RESTful架构:

  (1)每一个URI代表一种资源;

  (2)客户端和服务器之间,传递这种资源的某种表现层;

  (3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层状态转化"。

如何判断是restful还是非restfu形式的访问:

区别:下面是jsp页面书写的区别:

非RESTful的http的url:http://localhost:8080/items/editItems.action?id=${id}。页面的url是此种类型的,我们可以判断是非restful形式的,

RESTful的url是简洁的:http:// localhost:8080/items/editItems/${id}.通过此我们可以判断是restful形式的访问。

参数通过url传递,rest接口返回json数据

对于这个id的参数绑定的区别:

非restful的参数绑定就是之前介绍过的在controller的方法的参数中直接绑定即可。

http://localhost:8080/items/editItems.action?id=${id}

restful形式的参数绑定和@RequestMapping的写法:

http:// localhost:8080/items/editItems/${id}

所以到底使用哪个注解,取决于是否是restful的形式访问。

4、@RequestParam与@PathVariable注释的区别

所以@PathVariable这里主要用于restful形式的访问。

@RequestParam主要用于非restful的参数绑定,但是如果页面的参数跟方法中的参数名称保持一致就不需要写此注解。如果不一致需要使用。

利用如果有默认值的话,就必须要用此注解,用defaultValue属性。

原文地址:https://www.cnblogs.com/fengli9998/p/6651691.html