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