springMVC之annotation優化

jopen 11年前發布 | 22K 次閱讀 Spring MVC Web框架 SpringMVC

1.在之前配置的spring配置文件中會有這樣的代碼:

<!-- 方法映射 -->
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
 <!-- 找類 -->
 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>

這兩句是注入開啟映射的類。

在spring3.0后有了mvc標簽,可以將上兩句改為:

<mvc:annotation-driven/>

同樣可以達到以上的結果。

2.在controller中我們是這樣配置的:

package com.yx.controller.annotation;

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;

@Controller public class HelloAnnotationController {

@RequestMapping(value="/user/adduser",method=RequestMethod.GET) public ModelAndView addUser(){

return new ModelAndView("/annotationTest","result","add user");

} @RequestMapping(value="/user/deluser") public ModelAndView delUser(){

return new ModelAndView("/annotationTest","result","delete user");

}

}</pre>

這里面也有很多可以優化的:

(1).對于傳輸方法,在平時開發時沒有必要必須規定是什么方法傳輸,也就是無論get還是post均可以運行。這樣只要將“method=RequestMethod.GET”刪掉即可。

(2).在沒給個方法前面都會出現“/user”即為命名空間,這樣代碼會太重復。可以在類的前面加上“@RequestMapping("/user2")”

(3).在struts2中方法的返回值一般為String,在springMVC中也可以這樣做。

最后controller的代碼可以修改為:

package com.yx.controller.annotation;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;

@Controller @RequestMapping("/user2") public class HelloAnnotationController2 {

@RequestMapping("/adduser") public String addUser(HttpServletRequest request){ request.setAttribute("result","add user 方法"); return "/annotationTest";

} @RequestMapping("/deluser") public String delUser(HttpServletRequest request){ request.setAttribute("result","delete user上述"); return "/annotationTest";

} }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!