1.spring-mvc.xml加入配置
<!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器 --> <context:component-scan base-package="com.net.xinfang.controller" />
2.@controller/@RequestMapping/@RequestParam寫法
@Controller @RequestMapping(value = "/cte") ---代表第一層url public class CntoEnController { @RequestMapping(value="/getcte", method = {RequestMethod.GET}) ---代碼第二次url public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){ ---請求的值傳給langType return "cte"; } } 完整請求路徑為:http://ip地址:端口號/項目名/cte/getcte?langType=zh
3.@RequestMaping寫法
@RequestMapping(value="",method={"",""},headers={},params={"",""})
參數:
value:設置訪問地址
method:設置訪問方式,常用的method=RequestMethod.POST,和method=RequestMethod.GET
headers:頭域,可以設置瀏覽器支持的格式
params:訪問參數設置
注解作用:
用來定義訪問的url。可以是方法級別的,也可以是類級別的。兩者可以協同工作,縮小選擇范圍。也可以隱藏代碼的真實路徑,更加具有安全性和可讀性。
@Autowired
注解作用:
可以對成員變量、方法和構造函數進行標注,來完成自動裝配工作。可以消除get,set方法。
可以使用@Autowired注解來減少代碼量。首先,在applicationContext中加入:
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
然后,在變量上添加@Autowired注解,並去掉相應的getter和setter方法:
public class ClasServiceImpl implements ClasService{ @Autowired private ClasDAO clasDAO; ... }
並且在applicationContext中將相應的<property></property>標簽去掉:
<bean id="clasService" class="com.school.service.ClasServiceImpl"> </bean>
Spring啟動時,AutowiredAnnotationBeanPostProcessor會掃描所有的Bean,當發現其中有@Autowired注解時,就會找相應類型的Bean,並且實現注入。
@ResponseBody
注解作用:
直接放在方法上,表示返回類型將會直接作為Http響應字節流輸出,可以用於Ajax。
@RequestParam(required=,value="",defaultValue="")
參數:
required:參數是否必須,boolean類型,默認為true
value:傳遞的參數名稱,String類型,可選項,有值則對應方法的參數
defaultValue:參數沒有傳遞時為參數默認指定的值
@Override
偽代碼,表示重寫(當然不寫也可以),不過也有好處:
1、可以當注釋用,方便閱讀;