스프링 중급 과정

1. 간단 한 프로젝트 웹 페이지 인 SpringBoot 를 만 들 고 [SpringBoot 사이트] [] 에 들 어가 자신 이 필요 로 하 는 의존 (Web, Velocity, AOP) 을 선택 하여 프로젝트 를 생 성하 고 자신 이 설정 한 작업량 을 줄인다.Idea 를 열 고 프로젝트 를 가 져 온 다음 조용히 기다 리 면 됩 니 다.[SpringBoot 사이트]:http://start.spring.io/
  • 간단 한 구조 웹 요청 - > 컨트롤 러 - > 서비스 - > DAO (- > 데이터베이스)
  • 주해 와 대응 방법 파라미터
  • //    ,  value path    ,     ,{"/path1","/path2"}
    @RequestMapping(value = {"/profile/{groupId}/{userId}"})
    //       Controller        ,     HttpMessageConverter        ,   Response   body   。
    //        ,             ,         ,
    @ResponseBody
    //     PathVariable,     RequestParam
    public String profile(@PathVariable("groupId") String groupId,                      
    @PathVariable("userId") int userId,
    @RequestParam(value = "type", defaultValue = "1") int type,                      
    @RequestParam(value = "key", defaultValue = "nowcoder") String key) {
    }
    
  • Velocity 템 플 릿 문법
  • ##     
    $!{  /   }
    #*  
      *#
    ##.index 0    ,.count   
    #foreach($color in $colors)
    Color$!(foreach.count)/$(foreach.index):$!(color)
    #
    
  • 자원 파일
  • 정적: static / templates css 와 images
  • 템 플 릿 파일: templates xxx. vn a. 템 플 릿 파일 예 1
  • //java  
    @RequestMapping(value = {"/vm"})
    //model     ,       html       
    public String news(Model model){
    model.addAttribute("value1", "vv1");   
    List colors = Arrays.asList(new String[]{"RED", "GREEN", "BLUE"});
    Map map = new HashMap();
    for (int i = 0; i < 4; i++) {    
     map.put(String.valueOf(i), String.valueOf(i * i));
    }
    model.addAttribute("colors", colors);
    model.addAttribute("map", map); 
    return "news";
    }
    //            news.vm     value1  
    
    
    
    
    
        Hello, VM
        ##     (    )
        $!{value1}##    ,    
        $!{value2}
        ${value3}##       
    ##for  
        #foreach ($color in $colors)
            Color $!{foreach.index}/$!{foreach.count}:$!{color}
        #end
        #foreach($key in $map.keySet())
            Number $!{foreach.index}/$!{foreach.count}:$!{key} $map.get($key)
        #end
        #foreach($kv in $map.entrySet())
            Number $!{foreach.index}/$!{foreach.count}:$!{kv.key} $!{kv.value}
        #end
        User: $!{user.name}
        User: $!{user.getName()}
      
        #set($hello = "hello") ##     
        #set($hworld1 = "$!{hello} world")
        #set($hworld2 = '$!{hello} world')
        hworld1: $hworld1
        hworld2: $hworld2
    
    b. include 와 parse
    ##header.vm
    Title $!title
    ##news.vm
    ##  title   
    #set($title = "nowcoder")
    Include: #include("header.vm")
    Parse: #parse("header.vm")
    /*   Include: TiTle $!title    Parse: TiTle nowcoder
      ,include    ,parse         */
    

    c. macro
    #macro(render_color, $color, $index)    
        Color By Macro $index, $color
    #end
    #foreach ($color in $colors)    
        #render_color($color, $foreach.index)
    #end
    
  • 요청 과 응답 a. 요청 매개 변수 분석, 쿠키 읽 기, http 요청 필드 와 파일 업로드
  • @RequestMapping(value = {"/request"})
    @ResponseBody
    //          
    public String request(HttpServletRequest req,
    HttpServletResponse resp,
    HttpSession session){    
    StringBuilder sb = new StringBuilder();
    //        ,      
    Enumeration headerNames = req.getHeaderNames();    
    while (headerNames.hasMoreElements()) {
    String name = headerNames.nextElement();
    sb.append(name + ":" + req.getHeader(name) + "
    "); } return sb.toString(); }

    b. 응답 페이지 내용 반환, 쿠키 전송, http 필드 설정, headers
    @RequestMapping(value = {"/response"})
    @ResponseBody
    public String response(@CookieValue(value = "nowcoderid", defaultValue = "a") String nowcoderId,
    @RequestParam(value = "key", defaultValue = "key") String key,
     @RequestParam(value = "value", defaultValue = "value") String value,
    HttpServletResponse resp) {
    resp.addCookie(new Cookie(key,value));
    resp.addHeader(key, value);
    return "NowCoderId From COOkie: " + nowcoderId;}
    
  • 301 로 재 설정: 영구적 으로 이동 합 니 다. 첫 번 째 방문 후 브 라 우 저 에 기록 하고 다시 방문 할 때 원래 주소 에 먼저 접근 하지 않 고 바로 방향 을 바 꾸 는 경 로 를 이동 합 니 다.302: 임시 이전, 직접적인 방식 return "redirect: /"
  • @RequestMapping("/redirect/{code}")
    public RedirectView redirect(@PathVariable("code") int code) {
        RedirectView red = new RedirectView("/",true);
        if (code == 301) {
            red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        }
        return red;
    }
    
  • 오류 처리
  • @RequestMapping("/admin")
    @ResponseBodypublic
     String admin(@RequestParam(value = "key", required = false) String key){
        if ("admin".equals(key)) {
            return "Hello admin! ";
        }
    //      ,    ,       ,
        throw new IllegalArgumentException("Key   ");
    }
    /*  :Whitelabel Error Page
    
    This application has no explicit mapping for /error, so you are seeing this as a fallback.
    
    Wed Nov 16 14:03:51 CST 2016
    There was an unexpected error (type=Internal Server Error, status=500).
    Key   */
    //     
    @ExceptionHandler()
    @ResponseBody
    public String error(Exception e) {
        return "error: " + e.getMessage();
    }
    //  :error: Key   
    
  • IoC: 제어 반전 은 두 가지 유형 으로 나 뉘 는데 주입 (DI) 과 검색 (DL) 에 의존 하고 전자 응용 이 광범 위 하 다. IoC 는 보통 전자
  • 를 말한다.
    //    ,       ,            
    //Service.java
    public String service(){
     return "service()";
    }
    //Application.java
    public String application(){
       private Service service;
       public Application(Service service){
             this.service = service;
       }
    }
    //    ,      ,spring    ,      ,   
    //Service.java
    @Service
    public String service(){
     return "service()";
    }
    //Application.java
    public String application(){
       @AutoWired
       private Service service;
       }
    }
    
  • AOP: 절단면 을 대상 으로 프로 그래 밍 하고 모든 업 무 를 처리 해 야 하 는 업무, 예 를 들 어 log 서비스
  • @Aspect
    @Component
    public class LogAspect {
        private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
        @Before("execution(* com.nowcoder.controller.*Controller.*(..))")
        public void beforeMethod(JoinPoint joinPoint) {
            StringBuilder sb = new StringBuilder();
            for (Object arg : joinPoint.getArgs()) {
                sb.append("arg:" + arg.toString() + "|");
            }
            logger.info("before time: " + new Date());
            logger.info("before method: "+ sb.toString());
        }
        @After("execution(* com.nowcoder.controller.IndexController.*(..))")
        public void afterMethod() {
            logger.info("after method: ");
        }
    }
    

    좋은 웹페이지 즐겨찾기