24 Mayıs 2018 Perşembe

SpringMVC @Controller Anotastonu

Giriş
Şu satırı dahil ederiz.
import org.springframework.stereotype.Controller;
Açıklaması şöyle.
The Controller is where the DispatcherServlet will delegate requests.
Şeklen şöyle. FrontController yani DispatcherServlet istekleri benim Controller koduma yönlendirir.


Açıklaması şöyle.
When you annotate any class with an annotation which extends from @Component annotation (@Controller extends from @Component), Spring will load it to its ApplicationContext if that class falls within the Component Scan Scope
Bu sınıfın kardeşi @RestController anotasyonu.

Kulllanım
1. @RequestMapping ile hangi url ile çalışacağı belirtilir. Örneğin url /hellopage olsun. \src\main\webapp\WEB-INF\views\hellopage.jsp olmalıdır.

2. ModelAndView dönülecekse belirtilen safya yine benzer ilk maddedeki benzer yapıda olmalıdır.

Kod Yapısı
Controller kodları şöyledir
src
|    +--com
|            +--mypackage
|                +--config
|                    |--ServletInitializer.java
|                    |--WebConfig.java
|                +--controller
|                    |--HomeController.java
|    +--resources
|    +--webapp
|        +--WEB-INF
|            +--views
|                |--index.jsp
Örnek
Cevap olarak thymeleaf göndermek için şöyle yaparız.
@Controller
public class HelloController {

  @RequestMapping("/")
  String index() {
    return "index";
  }
}
Örnek
jsp ile kullanmak için şöyle yaparız.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;

@Controller
public class HomeController {

    @RequestMapping(value = "/" method = RequestMethod.GET)
    public String index(ModelMap model){
        System.out.println("This is a test ================>");
        model.addAttribute("message", "Spring MVC Java Configuration Example");
        return "index";
    }

}
jsp için şöyle yaparız.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Spring MVC Java Configuration Example</title>
</head>
<body>

    ${message}

</body>
</html>
Örnek
Elimizde şöyle bir kod olsun
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.servlet.ModelAndView;  
@Controller 
public class HelloWorldController {  
   @RequestMapping("/hello")  
    public ModelAndView helloWorld() {  
        String message = "HELLO SPRING MVC HOW R U";  
        return new ModelAndView("hellopage", "message", message);  
    }  
}  
jsp içinde şöyle yaparız
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
  <title>Hello Page</title>
</head>
<body>
  <%@ page isELIgnored="false" %>
  <P>  ${message}. </P>
</body>
</html>
Örnek
Cevap olarak html göndermek için şöyle yaparız.
@RequestMapping(value="/hello", method = RequestMethod.GET)
public ModelAndView product_save(){
  ModelAndView model = new ModelAndView();
  model.setViewName("hello"); // HTML page name
  return model;
}
Örnek
Başka sayfaya yönlendirmek için şöyle yaparız.
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model,Locale locale) {
  // your code and use return line as follows
  return "redirect:adminHome";
}
Örnek
Başka sayfaya yönlendirmek için şöyle yaparız.
@Controller
public class LoginController {

  @GetMapping("/")
  public String redirectToLogin() {
    ...
    return "redirect:/login";
  }

  @GetMapping("/login")
  public String showLoginForm(Model model,
    @RequestParam(name="error", required=false) String error,
    @RequestParam(name="logout", required=false) String logout) {
    ...
    return "login";
  }

  @PostMapping("/logincheck")
  public String loginCheck(@ModelAttribute(name="userCredentials")
    UserCredential userCredential) {
    ...
    return "redirect:/login?error";
  }
}
Örnek
Elimizde bir controller olsun.
@Controller
public class MyController {

  public String hello() {
    System.out.println("Hello World");
    return "foo";
  }
}
Bu controller'ın ismi verilmediği için camel case olarak myController olur. Dolayısıyla şu kod çalışır.
ApplicationContext ctx = ...;
MyController controller = (MyController) ctx.getBean("myController");
controller.hello();

Hiç yorum yok:

Yorum Gönder