当前位置:首页 » 网页前端 » springwebrestful
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

springwebrestful

发布时间: 2022-11-12 01:51:04

1. spring mvc restful 怎么通过控制器访问web-info下面的jsp页面

spring mvc中可以通过页面的以下代码实现访问web-inf下的jsp:
<a href="javascript:<jsp:forward page='WEB-INF/xxxx.jsp'/>"></a>

说明:
如果index.jsp是提交到servlet处理的,那么可以在servlet下使用绝对路径访问就可以了..
/appname/WEB-INF/***.jsp
这样就可以了。

2. springmvc实现的restful api 和cxf实现的restful webservice有什么区别与联系

springmvc实现的restful api 和cxf实现的restful webservice的区别是方法不一样,但是效果都是相同的,随便用哪一个、

3. spring-webmvc和spring-web有什么区别

1、定义不同

spring-web是一个一站式的框架,提供了表现层(springmvc)到业务层(spring)再到数据层的全套解决方案;spring的两大核心IOC(控制反转)和AOP(面向切面编程)更是给我们的程序解耦和代码的简介提供了支持。

而Spring-webMVC是基于Spring功能之上添加的Web框架,想用pring-webMVC必须先依赖pring-web,pring-webMVC仅给spring的表现层提供支持。

2、项目范围

pring-web可以说是一个管理bean的容器,也可以说是包括很多开源项目的总称。

而pring-webMVC只是其中一个开源项目。

(3)springwebrestful扩展阅读:

spring框架的优点有以下几点:

1、JAVA EE应该更加容易使用。

2、面向对象的设计比任何实现技术(比如JAVA EE)都重要。

3、面向接口编程,而不是针对类编程。Spring将使用接口的复杂度降低到零。(面向接口编程有哪些复杂度?)

4、代码应该易于测试。Spring框架会帮助你,使代码的测试更加简单。

5、提供了应用程序配置的最好方法。

4. spring mvc 提供的restful 服务怎么访问

Spring MVC本身对Restful支持非常好。它的@RequestMapping、@RequestParam、@PathVariable、@ResponseBody注解很好的支持了REST。18.2 Creating RESTful services
1. @RequestMapping
Spring uses the @RequestMapping method annotation to define the URI Template for the request. 类似于struts的action-mapping。 可以指定POST或者GET。
2. @PathVariable
The @PathVariable method parameter annotation is used to indicate that a method parameter should be bound to the value of a URI template variable. 用于抽取URL中的信息作为参数。(注意,不包括请求字符串,那是@RequestParam做的事情。)
@RequestMapping("/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
// ...
}

如果变量名与pathVariable名不一致,那么需要指定:
@RequestMapping("/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}

Tip
method parameters that are decorated with the @PathVariable annotation can be of any simple type such as int, long, Date... Spring automatically converts to the appropriate type and throws a TypeMismatchException if the type is not correct.
3. @RequestParam
官方文档居然没有对这个注解进行说明,估计是遗漏了(真不应该啊)。这个注解跟@PathVariable功能差不多,只是参数值的来源不一样而已。它的取值来源是请求参数(querystring或者post表单字段)。
对了,因为它的来源可以是POST字段,所以它支持更丰富和复杂的类型信息。比如文件对象:
@RequestMapping("/imageUpload")
public String processImageUpload(@RequestParam("name") String name,
@RequestParam("description") String description,
@RequestParam("image") MultipartFile image) throws IOException {
this.imageDatabase.storeImage(name, image.getInputStream(),
(int) image.getSize(), description);
return "redirect:imageList";
}

还可以设置defaultValue:
@RequestMapping("/imageUpload")
public String processImageUpload(@RequestParam(value="name", defaultValue="arganzheng") String name,
@RequestParam("description") String description,
@RequestParam("image") MultipartFile image) throws IOException {
this.imageDatabase.storeImage(name, image.getInputStream(),
(int) image.getSize(), description);
return "redirect:imageList";
}

4. @RequestBody和@ResponseBody
这两个注解其实用到了Spring的一个非常灵活的设计——HttpMessageConverter 18.3.2 HTTP Message Conversion
与@RequestParam不同,@RequestBody和@ResponseBody是针对整个HTTP请求或者返回消息的。前者只是针对HTTP请求消息中的一个 name=value 键值对(名称很贴切)。
HtppMessageConverter负责将HTTP请求消息(HTTP request message)转化为对象,或者将对象转化为HTTP响应体(HTTP response body)。
public interface HttpMessageConverter<T> {

// Indicate whether the given class is supported by this converter.
boolean supports(Class<? extends T> clazz);

// Return the list of MediaType objects supported by this converter.
List<MediaType> getSupportedMediaTypes();

// Read an object of the given type form the given input message, and returns it.
T read(Class<T> clazz, HttpInputMessage inputMessage) throws IOException,
;

// Write an given object to the given output message.
void write(T t, HttpOutputMessage outputMessage) throws IOException,
;

}

Spring MVC对HttpMessageConverter有多种默认实现,基本上不需要自己再自定义HttpMessageConverter
StringHttpMessageConverter - converts strings
FormHttpMessageConverter - converts form data to/from a MultiValueMap<String, String>
ByteArrayMessageConverter - converts byte arrays
SourceHttpMessageConverter - convert to/from a javax.xml.transform.Source
- convert to/from RSS feeds
- convert to/from JSON using Jackson's ObjectMapper
etc...
然而对于RESTful应用,用的最多的当然是。
但是不是默认的HttpMessageConverter:
public class extends WebContentGenerator
implements HandlerAdapter, Ordered, BeanFactoryAware {

...

public () {
// no restriction of HTTP methods by default
super(false);

// See SPR-7316
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false);
this.messageConverters = new HttpMessageConverter[]{new ByteArrayHttpMessageConverter(), stringHttpMessageConverter,
new SourceHttpMessageConverter(), new ()};
}
}

如上:默认的HttpMessageConverter是ByteArrayHttpMessageConverter、stringHttpMessageConverter、SourceHttpMessageConverter和转换器。所以需要配置一下:
<bean class="org.springframework.web.servlet.mvc.annotation.">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=GBK</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json." />
</list>
</property>
</bean>

配置好了之后,就可以享受@Requestbody和@ResponseBody对JONS转换的便利之处了:
@RequestMapping(value = "api", method = RequestMethod.POST)
@ResponseBody
public boolean addApi(@RequestBody
Api api, @RequestParam(value = "afterApiId", required = false)
Integer afterApiId) {
Integer id = apiMetadataService.addApi(api);
return id > 0;
}

@RequestMapping(value = "api/{apiId}", method = RequestMethod.GET)
@ResponseBody
public Api getApi(@PathVariable("apiId")
int apiId) {
return apiMetadataService.getApi(apiId, Version.primary);
}

一般情况下我们是不需要自定义HttpMessageConverter,不过对于Restful应用,有时候我们需要返回jsonp数据:
package me.arganzheng.study.springmvc.util;

import java.io.IOException;
import java.io.PrintStream;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.;
import org.springframework.http.converter.json.;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class extends {

public () {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL));
setObjectMapper(objectMapper);
}

@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, {
String jsonpCallback = null;

RequestAttributes reqAttrs = RequestContextHolder.currentRequestAttributes();
if(reqAttrs instanceof ServletRequestAttributes){
jsonpCallback = ((ServletRequestAttributes)reqAttrs).getRequest().getParameter("jsonpCallback");
}

if(jsonpCallback != null){
new PrintStream(outputMessage.getBody()).print(jsonpCallback + "(");
}

super.writeInternal(o, outputMessage);

if(jsonpCallback != null){
new PrintStream(outputMessage.getBody()).println(");");
}
}
}

5. springmvc restful web.xml怎么配置

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

6. 阿里面试必备:100个高频Spring面试题,助你一臂之力!

100个高频Spring面试题,让面试也能聊出花!

1、 Spring是什么?

2、Spring框架的好处?

3、Spring有哪些模块?

4、解释Core Container(Application context)模块

5、BeanFactory实现实例

6、XMLBeanFactory

7、解释AOP模块

8、解释JDBC抽象和DAO模块

9、解释对象/关系映射集成模块

10、解释Spring web模块

11、解释Spring MVC模块

12、Spring配置文件

13、如何才能有多个Spring配置文件?

14、ApplicationContext有哪些常见实现?

15、Bean Factory和ApplicationContext有什么区别?

16、Spring框架的一些最佳实践是什么?

17、使用Spring框架的方式有哪些?

18、我们如何使用Spring创建restful web服务来返回JSON响应结果?

19、Spring vs Spring MVC vs Spring Boot?

20、一个Spring大概是什么样子?

B:依赖注入

21、Spring的IOC容器是什么?

22、IOC的好处有哪些?

23、Spirng中有多少种IOC容器?

24、BeanFactory和ApplicationContext比较

25、什么是Spring中的依赖注入?

26、紧耦合和松耦合有什么区别?

27、IOC(依赖注入)有哪些不同类型?

28、你建议使用构造方法注入还是Setter注入?

C.Spring Beans

29、Spring beans是什么?

30、Spring bean定义包含什么?

31、如何向Spring容器提供配置元数据?

32、怎么定义bean的作用域?

33、说明Sprig支持的bean作用域

34、单例作用域是线程安全的吗?

35、解释Spring Bean的声明周期

36、有哪些重要的bean生命周期方法?你能重写它们吗?

37、Spring的内部bean是什么?

38、如何在Spring中注入Java集合?

39、什么是Spring Bean装配?

40、什么是Bean自动装配?

41、解释不同类型的自动装配

42、自动注入有限制吗?

43、你能在Spring中注入null和空字符串吗?

D.Spring注解

44、有哪些重要的Spring注解?

45、@RequestParam注解的作用是什么?

46、注解@Primary的重要性

47、XML配置和注解之间有什么区别?

48、@SpringBootApplication的作用是什么?

49、解释@InitBinder?

50、定义@ControllerAdvice

100个高频Spring面试题,让面试也能聊出花!

51、我们可以将一个个对象作为控制器处理程序方法的响应吗?

52、解释@ModelAttribute?

53、@RequestMapping注解

54、什么是spring中基于java的配置?给出一注解示例

55、什么是基于注解的容器配置?

56、如何打开注解装配?

E.Spring 数据访问

57、Spring JDBC API中有哪些类?

58、如何在Spring框架中更高效地使用JDBC?

59、JdbcTemplate

60、如何通过spring JdbcTemplate获取数据?

61、NamedParameterJdbcTemplate的优点是什么?

62、什么是SpringJDBCTemplate类以及如何使用它?

63、 JDBC和Spring JDBC有什么区别?

64、Spring DAO支持

65、使用Spring访问Hibernate有哪些方式?

66、Spring支持的ORM

67、如何使用HibernateDaoSupport集成Spring和Hibernate?

68、Spring支持的事务管理类型?

69、Spring框架的事务管理有哪些优点?

70、哪种事务管理类型更可取?

F:Spring AOP

71、解释AOP

72、AOP有哪些优点?

73、AOP有哪些实现?

74、AOP术语有哪些?

75、切面

76、连接点

77、通知

78、切点

79、什么是引入?

80、什么是目标对象?

81、什么是代理?

82、有哪些不同类型的代理?

83、什么是植入。什么是植入应用的不同点?

84、Spring AOP中关注点和横切关注点有什么区别?

85、解释基于XML Schema方式的切面实现

86、解释基于注解的切面实现

G.Spring Model View Controller (MVC)

87、什么是Spring MVC框架?

88、创建spring mvc应用程序所需的最少配置是什么?

89、说出Spring MVC请求处理的主要流程?

90、DispatcherServlet

91、WebApplicationContext

92、 Spring MVC中的控制器是什么?

93、你如何将spring mvc框架与MVC架构联系起来?

94、Spring MVC中的ViewResolver是什么?

95、MultipartResolver是什么?怎么使用?

96、如何在spring mvc应用程序中上传文件?

97、Spring Web MVC怎么校验数据?

这里有三种方式去 提供校验 :使用注解、手动校验、或者两者混合。

98、什么是springmvc拦截器以及如何使用它?

H.扩展

99、Spring Security是什么?

100、为什么要用SpringBoot

(需要这份spring面试题答案PDF版,可以加群:927953692 免费领取)

7. 如何用Spring 3来创建RESTful Web服务

通过REST风格体系架构,请求和响应都是基于资源表示的传输来构建的。资源是通过全局ID来标识的,这些ID一般使用的是一个统一资源标识符(URI)。客户端应用使用HTTP方法(如,GET、POST、PUT或DELETE)来操作一个或多个资源。

8. 如何用Spring 3来创建RESTful Web服务

通过REST风格体系架构,请求和响应都是基于资源表示的传输来构建的。资源是通过全局ID来标识的,这些ID一般使用的是一个统一资源标识符(URI)。客户端应用使用HTTP方法(如,GET、POST、PUT或DELETE)来操作一个或多个资源。通常,GET是用于获取或列出一个或多个资源,POST用于创建,PUT用于更新或替换,而DELETE则用于删除资源。
例如,GET http //host/context/employees/12345将获取ID为12345的员工的表示。这个响应表示可以是包含详细的员工信息的XML或ATOM,或者是具有更好UI的JSP/HTML页面。您看到哪种表示方式取决于服务器端实现和您的客户端请求的MIME类型。
RESTful Web Service是一个使用HTTP和REST原理实现的Web Service。通常,一个RESTful Web Service将定义基本资源URI、它所支持的表示/响应MIME,以及它所支持的操作。
本文将介绍如何使用Spring创建Java实现的服务器端RESTful Web Services。这个例子将使用浏览器、curl和Firefox插件RESTClient作为发出请求的客户端。
本文假定您是熟悉REST基本知识的。
Spring 3的REST支持
在Spring框架支持REST之前,人们会使用其他几种实现技术来创建Java RESTful Web Services,如Restlet、RestEasy和Jersey。Jersey是其中最值得注意的,它是JAX-RS(JSR 311)的参考实现。
Spring是一个得到广泛应用的Java EE框架,它在版本3以后就增加了RESTful Web Services开发的支持。虽然,对REST的支持并不是JAX-RS的一种实现,但是它具有比标准定义更多的特性。REST支持被无缝整合到Spring的MVC层,它可以很容易应用到使用Spring构建的应用中。
Spring REST支持的主要特性包括:
注释,如@RequestMapping 和 @PathVariable,支持资源标识和URL映射
支持为不同的MIME/内容类型使用不同的表示方式
使用相似的编程模型无缝地整合到原始的 MVC 层
创建一个示例RESTful Web Service
本节中的例子将演示Spring 3环境的创建过程,并创建一个可以部署到Tomcat中的“Hello World”应用。然后我们再完成一个更复杂的应用来了解Spring 3 REST支持的重要概念,如多种MIME类型表示支持和JAXB支持。另外,本文还使用一些代码片断来帮助理解这些概念。
Hello World:使用Spring 3 REST支持
要创建这个例子所使用的开发环境,您需要:
IDE:Eclipse IDE for JEE (v3.4+)
Java SE5 以上
Web 容器:Apache Tomcat 6.0(Jetty或其他容器也可)
Spring 3框架(v3.0.3是本文编写时的最新版本)
其他程序库:JAXB 2、JSTL、commons-logging
在 Eclipse 中创建一个Web应用,然后设置Tomcat 6作为它的运行环境。然后,您需要设置web.xml文件来激活Spring
WebApplicationContext。这个例子将Spring bean配置分成两个文件:rest-servlet.xml 包含与MVC/REST有关的配置,rest-context.xml包含服务级别的配置(如数据源 beans)。清单 1 显示了web.xml中的Spring配置的部分。
清单 1. 在web.xml中激活Spring WebApplicationContext

以下是引用片段:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/rest-context.xml
</param-value>
</context-param>

<!-- This listener will load other application context file in addition to
rest-servlet.xml -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>

在rest-servlet.xml文件中创建Spring MVC的相关配置(Controller、View、View Resolver)。清单 2 显示了其中最重要的部分。

清单 2. 在rest-servlet.xml文件中创建Spring MVC配置

以下是引用片段:
<context:component-scan base-package="dw.spring3.rest.controller" />
<!--To enable @RequestMapping process on type level and method level-->
<bean class="org.springframework.web.servlet.mvc.annotation
." />
<bean class="org.springframework.web.servlet.mvc.annotation
." />
<!--Use JAXB OXM marshaller to marshall/unmarshall following class-->
<bean id="jaxbMarshaller"
class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>dw.spring3.rest.bean.Employee</value>
<value>dw.spring3.rest.bean.EmployeeList</value>
</list>
</property>
</bean>
<bean id="employees" class=
"org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg ref="jaxbMarshaller" />
</bean>
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.BeanNameViewResolver" />

上面的代码中:

Component-scan启用对带有Spring注释的类进行自动扫描,在实践中,它将检查控制器类中所定义的@Controller注释。
和使用@ReqeustMapping注释的类或函数的beans由Spring处理这个注释将在下一节进行详细介绍。
Jaxb2Mashaller定义使用JAXB 2进行对象XML映射(OXM)的编组器(marshaller)和解组器(unmarshaller )
MashallingView定义一个使用Jaxb2Mashaller的XML表示view
BeanNameViewResolver使用用户指定的bean名称定义一个视图解析器
本例将使用名为“employees”的MarshallingView。
这样就完成了Spring的相关配置。下一步是编写一个控制器来处理用户请求。清单3显示的是控制器类。

9. springmvc怎么实现restful

restful 是一个风格而不是一个标准,在springmvc web开发中可以说是
兴起于Rails的一种优雅的URI表述方式,是资源的状态和状态转移的描述。

springmvc rest 实现

springmvc的resturl是通过@RequestMapping 及@PathVariable
annotation提供的,通过如@RequestMapping(value="/blog
/{id}",method=RequestMethod.DELETE)即可处理/blog/1 的delete请求.

Java代码
@RequestMapping(value="/blog/{id}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
blogManager.removeById(id);
return new ModelAndView(LIST_ACTION);
}

@RequestMapping @PathVariable如果URL中带参数,则配合使用,如

Java代码
@RequestMapping(value="/blog/{blogId}/message/{msgId}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable("blogId") Long blogId,@PathVariable("msgId") Long msgId,HttpServletRequest request,HttpServletResponse response) {
}

spring rest配置指南

1. springmvc web.xml配置

Xml代码
<!-- 该
servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost
/foo.css ,现在http://localhost/static/foo.css -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- URL重写filter,用于将访问静态资源http://localhost/foo.css 转为http://localhost/static/foo.css -->
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confReloadCheckInterval</param-name>
<param-value>60</param-value>
</init-param>
<init-param>
<param-name>logLevel</param-name>
<param-value>DEBUG</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 覆盖default servlet的/, springmvc servlet将处理原来处理静态资源的映射 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 浏览器不支持put,delete等method,由该filter将/blog?_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>
<servlet-name>springmvc</servlet-name>
</filter-mapping>

2. webapp/WEB-INF/springmvc-servlet.xml配置,使用如下两个class激活@RequestMapping annotation

Java代码
<bean class="org.springframework.web.servlet.mvc.annotation."/>
<bean class="org.springframework.web.servlet.mvc.annotation."/>

完整配置

Java代码
<beans default-autowire="byName" >

<!-- 自动搜索@Controller标注的类 -->
<context:component-scan base-package="com.**.controller"/>

<bean class="org.springframework.web.servlet.mvc.annotation."/>

<bean class="org.springframework.web.servlet.mvc.annotation."/>

<!-- Default ViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/pages"/>
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="i18n/messages"/>

<!-- Mapping exception to the handler view -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.">
<!-- to /commons/error.jsp -->
<property name="defaultErrorView" value="/commons/error"/>
<property name="exceptionMappings">
<props>
</props>
</property>
</bean>

</beans>

3. Controller编写

Java代码
/**
* @RequestMapping("/userinfo") 具有层次关系,方法级的将在类一级@RequestMapping之一,
* 如下面示例, 访问方法级别的@RequestMapping("/new"),则URL为 /userinfo/new
*/
@Controller
@RequestMapping("/userinfo")
public class UserInfoController extends BaseSpringController{
//默认多列排序,example: username desc,createTime asc
protected static final String DEFAULT_SORT_COLUMNS = null;

private UserInfoManager userInfoManager;

private final String LIST_ACTION = "redirect:/userinfo";

/**
* 通过spring自动注入
**/
public void setUserInfoManager(UserInfoManager manager) {
this.userInfoManager = manager;
}

/** 列表 */
@RequestMapping
public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
//pageRequest.getFilters(); //add custom filters

Page page = this.userInfoManager.findByPageRequest(pageRequest);
savePage(page,pageRequest,request);
return new ModelAndView("/userinfo/list","userInfo",userInfo);
}

/** 进入新增 */
@RequestMapping(value="/new")
public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
return new ModelAndView("/userinfo/new","userInfo",userInfo);
}

/** 显示 */
@RequestMapping(value="/{id}")
public ModelAndView show(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
return new ModelAndView("/userinfo/show","userInfo",userInfo);
}

/** 编辑 */
@RequestMapping(value="/{id}/edit")
public ModelAndView edit(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
return new ModelAndView("/userinfo/edit","userInfo",userInfo);
}

/** 保存新增 */
@RequestMapping(method=RequestMethod.POST)
public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
userInfoManager.save(userInfo);
return new ModelAndView(LIST_ACTION);
}

/** 保存更新 */
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public ModelAndView update(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws Exception {
UserInfo userInfo = (UserInfo)userInfoManager.getById(id);
bind(request,userInfo);
userInfoManager.update(userInfo);
return new ModelAndView(LIST_ACTION);
}

/** 删除 */
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public ModelAndView delete(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) {
userInfoManager.removeById(id);
return new ModelAndView(LIST_ACTION);
}

/** 批量删除 */
@RequestMapping(method=RequestMethod.DELETE)
public ModelAndView batchDelete(@RequestParam("items") Long[] items,HttpServletRequest request,HttpServletResponse response) {

for(int i = 0; i < items.length; i++) {

userInfoManager.removeById(items[i]);
}
return new ModelAndView(LIST_ACTION);
}

}

上面是rapid-framework 新版本生成器生成的代码,以后也将应用此规则,rest url中增删改查等基本方法与Controller的方法映射规则

Java代码
/userinfo => index()
/userinfo/new => _new()
/userinfo/{id} => show()
/userinfo/{id}/edit => edit()
/userinfo POST => create()
/userinfo/{id} PUT => update()
/userinfo/{id} DELETE => delete()
/userinfo DELETE => batchDelete()

注(不使用 /userinfo/add => add() 方法是由于add这个方法会被maxthon浏览器当做广告链接过滤掉,因为包含ad字符)

4. jsp 编写

Html代码
<form:form action="${ctx}/userinfo/${userInfo.userId}" method="put">
</form:form>

生成的html内容如下, 生成一个hidden的_method=put,并于web.xml中的HiddenHttpMethodFilter配合使用,在服务端将post请求改为put请求

Java代码
<form id="userInfo" action="/springmvc_rest_demo/userinfo/2" method="post">
<input type="hidden" name="_method" value="put"/>
</form>

另外一种方法是你可以使用ajax发送put,delete请求.

5. 静态资源的URL重写

如上我们描述,现因为将default servlet映射至/static/的子目录,现我们访问静态资源将会带一个/static/前缀.

如 /foo.gif, 现在访问该文件将是 /static/foo.gif.
那如何避免这个前缀呢,那就是应用URL rewrite,现我们使用 http://tuckey.org/urlrewrite/, 重写规则如下

Xml代码
<urlrewrite>
<!-- 访问jsp及jspx将不rewrite url,其它.js,.css,.gif等将重写,如 /foo.gif => /static/foo.gif -->
<rule>
<condition operator="notequal" next="and" type="request-uri">.*.jsp</condition>
<condition operator="notequal" next="and" type="request-uri">.*.jspx</condition>
<from>^(/.*\..*)$</from>
<to>/static$1</to>
</rule>
</urlrewrite>

另笔者专门写了一个 RestUrlRewriteFilter来做同样的事件,以后会随着rapid-framework一起发布. 比这个更加轻量级.

并且该代码已经贡献给spring,不知会不会在下一版本发布

在线DEMO地址: http://demo.rapid-framework.org.cn:8080/springmvc_rest_demo/userinfo