javascript
基于注释的Spring MVC Web应用程序入门
這是使Maven啟動Spring 3 MVC項目的最小方法。
首先創建spring-web-annotation/pom.xml文件,并包含Spring依賴項:
現在在spring-web-annotation/src/main/java/springweb/WebApp.java為MVC部件創建Servlet 3 Web初始化程序和Spring注釋配置。
package springweb;import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class<?>[0];}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class<?>[]{ WebAppConfig.class };}@Overrideprotected String[] getServletMappings() {return new String[]{ "/" };}@Configuration@EnableWebMvc@ComponentScan("springweb.controller")public static class WebAppConfig {} }WebApp類擴展了Spring內置的Servlet3 Web初始化程序代碼。 它允許Servlet3容器(例如Tomcat7)自動檢測此Web應用程序,而無需進行web.xml配置設置。 因為我們不使用web.xml ,所以我們需要此類來允許Spring掛接到Servlet容器中以引導其調度程序servlet。 另外,我們現在可以使用基于WebAppConfig所有注釋,而不是典型的Spring bean xml文件配置。
注意,我已經將WebAppConfig組合為內部類,但是您可以輕松地將其作為全面應用程序中的頂級類移出。 這是容器配置的Spring注釋版本。 您可以通過在此處添加新的@Bean輕松定制應用程序。
注意:不要忘記用"/"覆蓋getServletMappings方法,否則您的URL請求將不會定向到Spring調度程序進行處理! 這一步很容易被遺忘,您可能會發現自己在追逐為什么Spring控制器無法正常工作的原因。
以上實際上是啟動戰爭項目所需的最低設置。 接下來,您要添加至少一個控制器以驗證某些輸出。 創建此控制器文件spring-web-annotation/src/main/java/springweb/controller/IndexController.java
package springweb.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;@Controller public class IndexController {@RequestMapping(value="/")public String index() {return "index";} }現在,您將需要JSP視圖spring-web-annotation/src/main/webapp/index.jsp
Hello World.現在cd進入spring-web-annotation并執行mvn org.apache.tomcat.maven:tomcat7-maven-plugin:run 。 您應該看到Spring應用程序已啟動,并且能夠瀏覽http://localhost:8080/spring-web-annotation URL。
Spring MVC可以完成很多有趣的工作。 查閱他們的真棒文檔以獲取更多詳細信息。
翻譯自: https://www.javacodegeeks.com/2013/10/getting-started-with-annotation-based-spring-mvc-web-application.html
總結
以上是生活随笔為你收集整理的基于注释的Spring MVC Web应用程序入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ddos清洗服务(国外ddos清洗)
- 下一篇: 使用Spring Webservices