Spring MVC ile XML kullanmadan Hello World Uygulaması Gerçekleştirelim.
Başla
Adım 1:
Netbeans ile Maven Projesi Oluşturalım. Gerekli Spring kütüphanelerini ekleyelim. Nasıl oluşturulur. Bakınız
Adım 2:
Web Pages klasöründe bulunan index.html sayfasını silelim.Web Pages' e sağ tıklayalım WEB-INF adında yeni klasör (Folder) oluşturalım.
Proje Yapısını Aşağıdaki Gibi Düzenleyelim. Gerekli Java Class' larını Ekleyelim.
Adım 3:
Config.java
package com.mycompany.config; import org.springframework.context.annotation.Bean; 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.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; /** * * @author gurkan */ @Configuration @ComponentScan("com.mycompany") @EnableWebMvc public class Config extends WebMvcConfigurerAdapter{ @Bean public UrlBasedViewResolver viewResolver(){ UrlBasedViewResolver resolver = new UrlBasedViewResolver(); resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class); return resolver; } }
Adım 4:
WebInitializer.java
package com.mycompany.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration.Dynamic; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * * @author gurkan */ public class WebInitializer implements WebApplicationInitializer{ @Override public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(Config.class); ctx.setServletContext(sc); Dynamic servlet = sc.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/"); } }
Adım 5:
HelloController.java
package com.mycompany.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author gurkan */ @Controller public class HelloController { @RequestMapping(value = "/" , method = RequestMethod.GET) public String index(ModelMap map) { map.put("hello", "Hello Spring MVC"); return "index"; } }
Adım 6:
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>${hello}</h1> </body> </html>
Adım 7:
Projeyi Build ve Run edelim.
Spring MVC 4 Apache Tiles Entegrasyonu İçin Buradan Geçebilirsiniz.
Hiç yorum yok:
Yorum Gönder