프로젝트 기본설정상태

완료파일

=====================


스프링 MVC를 이용한 웹 요청 처리


=================================이론=====================================

스프링의 MVC의 주요 구성요소
DispatcherServlet : Struts2의 컨트롤러 :
HandlerMapping :
컨트롤러(Controller) : Struts2의 액션 :
ModelAndView :
뷰(View) :


실행 흐름 정리 : http://javai.tistory.com/561

웹브라우저 hello.do -> Dispatcher : DispatcherServlet
컨트롤러 요청 DefaultAnnotationHandlerMapping
HelloController 빈 리턴 -> Dispatcher : DispatcherServlet
처리요청 HelloController -> 모델뷰 리턴 -> Dispatcher : DispatcherServlet
hello에 매칭되는 View 객체 요청 ViewResolver : InternalResourceViewResolver 뷰 리턴 -> Dispatcher : DispatcherServlet
응답 생성 요청 -> InternalResourceView -> JSP를 이용하여 응답생성 -> hello.jsp

Dispatcher : DispatcherServlet 가 모든것을 컨트롤 하는것을 알 수 있다(Struts2의 Controller와 같은 역할)


커맨드 객체로 List 받기
자바빈->ArrayList넣기

컨트롤러 메서드의 파라미터 타입


1.@RequestParam 이용한 파라미터 매핑
필수가 아닌 파라미터의 경우 required 속성값을 false로 지정(기본값이 true)

@Controller
public class SearchController {
   
    @RequestMapping("/search/internal.do")
    public ModelAndView searchInternal(@RequestParam("query") String query, @RequestParam(value = "p", defaultValue = "1")int pageNumber){               //메서드명은 마음대로
        System.out.println("query="+query+",pageNumber"+pageNumber);
       
        return new ModelAndView("search/internal");
    }

    @RequestMapping("/search/external.do")
    public ModelAndView searchExternal(@RequestParam(value="query", required=false)String query,@RequestParam(value="p",defaultValue = "1")int pageNumber){   //메서드명은 마음대로
        System.out.println("query="+query+",pageNumber"+pageNumber);
   
    return new ModelAndView("search/external");
    }
}

dispatcher-servlet.xml 설정
    <!-- 파라미터로 전송된 데이터 처리 -->
    <bean id="searchController" class="madvirus.spring.chap06.controller.SearchController"/>


2.@CookieValue 어노테이션을 이용한 쿠키 매핑

필수가 아닌 쿠키의 경우 required 속성값을 false로 지정(기본값이 true)

@Controller
public class CookieController {
    @RequestMapping("/cookie/make.do")
    public String make(HttpServletResponse response){
        response.addCookie(new Cookie("auth", "1"));
        return "cookie/made";
    }

    //@CookieValue 어노테이션은 클라이언트가 제공하는 쿠키정보를 읽어드림
    @RequestMapping("/cookie/view.do")
    public String view(@CookieValue(value ="auth", defaultValue="0") String auth){
        System.out.println("auth 쿠기 : " + auth);
        return "cookie/view";
    }
}

<!-- @CookieValue 어노테이션을 이용한 쿠키 매핑 -->
<bean id="cookieController" class="madvirus.spring.chap06.controller.CookieController"/>


@RequestMappign(요청URL)

public [return 타입 P231] process([파라미터 타입 P225]  )

return 타입 - 1. ModelAndView :  View,View 개체
                   2. String : View
                   3. Map,Model : 키와 값을 쌍으로 저장할때

5.예제 @RequestHeader
 


@ModelAttribute 검색



Validator인터페이스를 이용한 폼 값 검증



예제9
restful 서비스

http://localhost:8080/chap06/index.do?id=dragon => http://localhost:8080/chap06/index/id/dragon




===============================프로젝트===================================


=================================코드=====================================
chap06
      src
          madvirus.spring.chap06.controller
              ArithmeticOperatorController (11.예제 예외페이지)
package madvirus.spring.chap06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ArithmeticOperatorController {

    @RequestMapping("/math/divide.do")
    public String divide(@RequestParam("op1") int op1, @RequestParam("op2") int op2, Model model){
        model.addAttribute("result", op1 / op2);
       
        return "math/result";
    }
}

              CharacterInfoController (9.예제 restful서비스)
package madvirus.spring.chap06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CharacterInfoController {
   
    @RequestMapping("/game/users/{userId}/characters/{characterId}")
    public String characterInfo(@PathVariable String userId, @PathVariable int characterId, ModelMap model){
        model.addAttribute("userId",userId);
        model.addAttribute("characterId", characterId);
        return "game/character/info";
       
    }   
}

              CookieController (4.예제 @CookieValue)
package madvirus.spring.chap06.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CookieController {
    @RequestMapping("/cookie/make.do")
    public String make(HttpServletResponse response){
        response.addCookie(new Cookie("auth", "1"));
        return "cookie/made"; //View 경로
    }

    //@CookieValue 어노테이션은 클라이언트가 제공하는 쿠키정보를 읽어드림
    @RequestMapping("/cookie/view.do")
    public String view(@CookieValue(value ="auth", defaultValue="0") String auth){
        System.out.println("auth 쿠기 : " + auth);
        return "cookie/view";
    }
}

              CreateAccountController (7.예제)
package madvirus.spring.chap06.controller;

import javax.servlet.http.HttpServletRequest;

import madvirus.spring.chap06.model.Address;
import madvirus.spring.chap06.model.MemberInfo;
import madvirus.spring.chap06.validator.MemberInfoValidator;

import org.springframework.jmx.export.assembler.AutodetectCapableMBeanInfoAssembler;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/account/create.do")
public class CreateAccountController {

    //Command 객체 초기화
    @ModelAttribute("command")
    public MemberInfo formBacking(HttpServletRequest request){
        //equalsIgnoreCase : 대소문자 관계없이 비교해줌 단!영문만 가능
        if(request.getMethod().equalsIgnoreCase("GET")){
            MemberInfo mi = new MemberInfo();
            Address address= new Address();
            address.setZipcode(autoDetectZipcode(request.getRemoteAddr()));
            mi.setAddress(address);
            return mi;
        }else{
            return new MemberInfo();
        }
    }
   
    private String autoDetectZipcode(String remoteAddr){
        return "000000";
    }
   
    @RequestMapping(method = RequestMethod.GET)
    public String form(){
        return "account/creationForm";
    }
   
    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("command")MemberInfo memberInfo,BindingResult result){
       
        new MemberInfoValidator().validate(memberInfo, result);
       
        if(result.hasErrors()){
            return "account/creationForm";
        }
        return "account/created";
    }
}

              GameInfoController (8.예제)
package madvirus.spring.chap06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class GameInfoController {
   
    //@RequestMapping("/game/info") /game/* 를 탈려면 /game을 하면안됨
    /*  /game/info 로 쓰기위해서는
    <!-- 요청 URI 매칭  -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="alwaysUseFullPath" value="true"/>
    </bean>   
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="alwaysUseFullPath" value="true"/>
    </bean>
    */
    @RequestMapping("/game/info")
    public String gameInfo(){
        return "game/info";
    }
   
    @RequestMapping("/game/list")
    public String gameList(){
        return "game/list";
    }
}

             GameSearchController (6.예제)
package madvirus.spring.chap06.controller;

import java.util.ArrayList;
import java.util.List;

import madvirus.spring.chap06.service.SearchCommand;
import madvirus.spring.chap06.service.SearchResult;
import madvirus.spring.chap06.service.SearchService;
import madvirus.spring.chap06.service.SearchType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GameSearchController {

    @Autowired
    private SearchService searchService;
   
    @ModelAttribute("searchTypeList")
    public List<SearchType> referenceSearchTypeList(){
        List<SearchType> options = new ArrayList<SearchType>();
        options.add(new SearchType(1, "전체"));
        options.add(new SearchType(2, "아이템"));
        options.add(new SearchType(3, "캐릭터"));
        return options;       
    }
   
    @ModelAttribute("popularQueryList")
    public String[] getPopularQueryList(){
        return new String[]{"게임","창천2","위메이드"};
    }
   
    @RequestMapping("/search/main.do")
    public String main(){
        return "search/main";
    }
   
    @RequestMapping("/search/game.do")
    public ModelAndView search(@ModelAttribute("command") SearchCommand command){
        ModelAndView mav = new ModelAndView("search/game");
       
        System.out.println("검색어 : " + command.getQuery().toUpperCase());
       
        SearchResult result = searchService.search(command);
        mav.addObject("searchResult",result);
       
        return mav;
    }
   
    @ExceptionHandler(NullPointerException.class)
    public String handleNullPointerException(NullPointerException ex){
        return "error/nullException";
    }
   
    public void setSearchService(SearchService searchService){
        this.searchService = searchService;
    }
}

              HeaderController (5.예제 @RequestHeader)
package madvirus.spring.chap06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HeaderController {

   
    //@RequestHeader 어노테이션은 클라이언트가 전송한 해더 정보 읽기
    @RequestMapping("/header/check.do")
    public String check(
            @RequestHeader("Accept-Language") String languageHeader){
        System.out.println(languageHeader);
       
        return "header/pass";
    }
}

              HelloController (1.예제) - 스프링의 컨트롤러는 Struts2의 액션
package madvirus.spring.chap06.controller;

import java.util.Calendar;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

//컨트롤러 (Struts2 의 Action과 동일)을 구현하기 위해 @Controller 명시
@Controller
public class HelloController {

    //클라이언트의 요청에 대해 호출되는 메소드 지정
    @RequestMapping("/hello.do")
    public ModelAndView hello(){ //메소드명은 마음대로
        //View에 정보를 전달하기 위해 ModelAndView 객체 생성
        ModelAndView mav = new ModelAndView();
        //View의 이름 지정
        mav.setViewName("hello");
        //View에 사용할 데이터 저장
        mav.addObject("greeting", getGreeting());
        return mav;
    }
   
    private String getGreeting(){
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
       
        if(hour >=6 && hour <=10 ){
            return "좋은 아침입니다.";
        }else if(hour >=12 && hour <=15 ){
            return "점심 식사는 하셨나요?";           
        }else if(hour >=18 && hour <=22 ){
            return "좋은 밤 되세요";
        }
        return "안녕하세요";
    }   
}

              NewArticleController (2.예제)
package madvirus.spring.chap06.controller;

import madvirus.spring.chap06.service.ArticleService;
import madvirus.spring.chap06.service.NewArticleCommand;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/*스탠다드 포맷 */


//컨트롤러 설정
@Controller
//클라이언트의 요청에 대해서 호출하는 메서드 지정
@RequestMapping("/article/newArticle.do")
public class NewArticleController {
   
    @Autowired
    private ArticleService articleService;
   
    @RequestMapping(method = RequestMethod.GET)
    public String form(){ //메소드가 지정되어 있는것은 아니지만 일반적으로 사용하는 명칭
        //리턴값은 View설정
        //글로벌설정이 /WEB-INF/view/ 이라  맨앞에/없음
        return "article/newArticleForm";
    }

    @RequestMapping(method = RequestMethod.POST)
                        //Command(자바빈) 클래스 설정)
    public String submit(@ModelAttribute("command") NewArticleCommand command){
        articleService.writeArticle(command);
        //리턴값은 View설정
        return "article/newArticleSubmitted";
    }
   
    public void setArticleService(ArticleService articleService){
        this.articleService =articleService;
    }   
}

              SearchController (3.예제 @RequestParam)
package madvirus.spring.chap06.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SearchController {
   
    @RequestMapping("/search/internal.do")
    public ModelAndView searchInternal(@RequestParam("query") String query, @RequestParam(value = "p", defaultValue = "1")int pageNumber){
        System.out.println("query="+query+",pageNumber"+pageNumber);
       
        return new ModelAndView("search/internal");
    }
   
    @RequestMapping("/search/external.do")
    public ModelAndView searchExternal(@RequestParam(value="query", required=false)String query,@RequestParam(value="p",defaultValue = "1")int pageNumber){
        System.out.println("query="+query+",pageNumber"+pageNumber);
   
    return new ModelAndView("search/external");
    }
}

          SubmitReportController (10.예제 파일업로드)
package madvirus.spring.chap06.model;

import org.springframework.web.multipart.MultipartFile;

//스프링의 Command = 자바빈
public class SubmitReportCommand {

    private String subject;
    private MultipartFile reportFile;
   
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public MultipartFile getReportFile() {
        return reportFile;
    }
    public void setReportFile(MultipartFile reportFile) {
        this.reportFile = reportFile;
    }   
}

          madvirus.spring.chap06.model
              Address (예제7. Command클래스)
package madvirus.spring.chap06.model;

public class Address {
    private String zipcode;
    private String address1;
    private String address2;
   
    public String getZipcode() {
        return zipcode;
    }
    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }
    public String getAddress1() {
        return address1;
    }
    public void setAddress1(String address1) {
        this.address1 = address1;
    }
    public String getAddress2() {
        return address2;
    }
    public void setAddress2(String address2) {
        this.address2 = address2;
    }
}

              MemberInfo (7.예제)
package madvirus.spring.chap06.model;

public class MemberInfo {

    private String id;
    private String name;
    private Address address;
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }   
}

             SubmitReportCommand (10.예제 파일업로드)
package madvirus.spring.chap06.model;

import org.springframework.web.multipart.MultipartFile;

//스프링의 Command = 자바빈
public class SubmitReportCommand {

    private String subject;
    private MultipartFile reportFile;
   
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public MultipartFile getReportFile() {
        return reportFile;
    }
    public void setReportFile(MultipartFile reportFile) {
        this.reportFile = reportFile;
    }   
}

          madvirus.spring.chap06.service
             ArticleService (2.예제)
package madvirus.spring.chap06.service;

public class ArticleService {

    public void writeArticle(NewArticleCommand command) {
        System.out.println("신규 게시글 등록: " + command);
    }
}

              NewArticleCommand (2.예제)
package madvirus.spring.chap06.service;

// *Command = 자바빈과 같은 기능  Command라 부른다.
public class NewArticleCommand {

    private String title;
    private String content;
    private int parentId;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getParentId() {
        return parentId;
    }

    public void setParentId(int parentId) {
        this.parentId = parentId;
    }

    @Override
    public String toString() {
        return "NewArticleCommand [content=" + content + ", parentId="
                + parentId + ", title=" + title + "]";
    }
}

             SearchCommand (6.예제)
package madvirus.spring.chap06.service;
//자바빈
public class SearchCommand {

    private String type;
    private String query;
    private int page;
   
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getQuery() {
        return query;
    }
    public void setQuery(String query) {
        this.query = query;
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }   
}

             SearchResult (6.예제)
package madvirus.spring.chap06.service;

public class SearchResult {

}

             SearchService (6.예제)
package madvirus.spring.chap06.service;

public class SearchService {

    //SearchCommand 객체를 받는거
    public SearchResult search(SearchCommand command){
        return new SearchResult();
    }
}

             SearchType (6.예제)
package madvirus.spring.chap06.service;

public class SearchType {
   
    private int code;
    private String text;   
   
    public SearchType(int code, String text) {
        super();
        this.code = code;
        this.text = text;
    }
   
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }   
}

          madvirus.spring.chap06.validator
             MemberInfoValidator (7.예제 검증)
package madvirus.spring.chap06.validator;

import madvirus.spring.chap06.model.Address;
import madvirus.spring.chap06.model.MemberInfo;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class MemberInfoValidator implements Validator{

    //Validator가 해당 클래스에 대한 값 검증을 지원하는지 여부를 리턴
    @Override
    public boolean supports(Class<?> clazz) {
        return MemberInfo.class.isAssignableFrom(clazz);
    }

    //target객체에 대한 검증을 실행
    @Override
   
    public void validate(Object target, Errors errors) {
        MemberInfo memberInfo = (MemberInfo)target;
        if(memberInfo.getId()==null|| memberInfo.getId().trim().isEmpty()){
            errors.rejectValue("id","required");
        }
        if(memberInfo.getName()==null || memberInfo.getName().trim().isEmpty()){
            errors.rejectValue("name", "required");
        }
        Address address = memberInfo.getAddress();
        if(address == null){
            errors.rejectValue("address", "required");
        }
        if(address != null){
            errors.pushNestedPath("address");
            try{
                if(address.getZipcode() == null || address.getZipcode().trim().isEmpty()){
                    errors.rejectValue("zipcode", "required");
                }
                if(address.getAddress1()==null || address.getAddress1().trim().isEmpty()){
                    errors.rejectValue("address1", "required");
                }
            }finally{
                errors.popNestedPath();
            }
        }       
    }   
}

             SubmitReportValidator (10.예제 파일업로드)
package madvirus.spring.chap06.validator;

import madvirus.spring.chap06.model.MemberInfo;
import madvirus.spring.chap06.model.SubmitReportCommand;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class SubmitReportValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {

        return SubmitReportCommand.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
       
        //방식1.데이터가 없는경우 돌려보냄
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subject", "required");
       
        SubmitReportCommand command = (SubmitReportCommand)target;
       
        //방식2. 일반적인방법
        if(command.getReportFile() ==null || command.getReportFile().isEmpty())
            errors.rejectValue("reportFile", "required");
    }
}

          message
             validation.properties (7예제. 설정파일)
required=필수 항목입니다.
invalidIdOrPassword.logincommand=아이디({0})와 암호가 일치하지 않습니다.
required.loginCommand.userId=사용자 아이디는 필수 항목입니다.
required.password=암호는 필수 항목입니다.
typeMismatch.from=시작일 값 형식은 yyyy-MM-dd 여야 합니다.
typeMismatch.to=종료일 값 형식은 yyyy-MM-dd 여야 합니다.

      WebContent
          WEB-INF
              lib (스프링 다이나믹웹 프로젝트 라이브러리)         
          upload
          view
              account
                  created.jsp (7.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>계정 생성</title>
</head>
<body>
계정 생성됨
<ul>
 <li>아이디: ${command.id}</li>
 <li>이름: ${command.name}</li>
 <li>우편번호: ${command.address.zipcode}</li>
 <li>주소: ${command.address.address1} ${command.address.address2}</li>
</ul>
</body>
</html> 

                  creationForm.jsp (7.예제)
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>계정 생성</title>
</head>
<body>
<!-- 에러메세지를 처리하귀해서 Spring 사용 -->
<spring:hasBindErrors name="command" />
<form:errors path="command" />
<form method="post">
    아이디: <input type="text" name="id" value="${command.id}" />
    <form:errors path="command.id" />
    <br/>
    이름: <input type="text" name="name" value="${command.name}" />
    <form:errors path="command.name" />
    <br/>
    우편번호: <input type="text" name="address.zipcode" value="${command.address.zipcode}" />
    <form:errors path="command.address.zipcode" />
    <br/>
    주소1: <input type="text" name="address.address1" value="${command.address.address1}" />
    <form:errors path="command.address.address1" />
    <br/>
    주소2: <input type="text" name="address.address2" value="${command.address.address2}" />
    <form:errors path="command.address.address2" />
    <br/>
    <input type="submit" />
</form>
</body>
</html>

              article
                  newArticleForm.jsp (2.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>게시글 쓰기</title>
</head>
<body>
게시글 쓰기 입력 폼:
<form method="post">
    <input type="hidden" name="parentId" value="0" />
    제목: <input type="text" name="title" /><br/>
    내용: <textarea name="content"></textarea><br/>
    <input type="submit" />
</form>
</body>
</html>

                  newArticleSubmitted.jsp (2.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>게시글 쓰기</title>
</head>
<body>
게시글 등록됨:
<br/>
제목: ${command.title}
</body>
</html>

              cookie
                  made.jsp (4.예제 @CookieValue)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키</title>
</head>
<body>
쿠키 생성함
</body>
</html>

                  view.jsp (4.예제 @CookieValue)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키</title>
</head>
<body>
쿠키 확인
</body>
</html>

              error (에러체크)
                  exception.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>예외 발생</title>
</head>
<body>
요청을 처리하는 도중에 예외가 발생하였습니다:
${exception.message}
<%
    Throwable e = (Throwable) request.getAttribute("exception");
    e.printStackTrace();
%>
</body>
</html>

                  mathException.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>예외 발생</title>
</head>
<body>
연산 과정에서 예외가 발생하였습니다.
</body>
</html>

                  nullException.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>예외 발생</title>
</head>
<body>
요청을 처리하는 과정에서 예외(null)가 발생하였습니다.
</body>
</html>

              game
                  character
                           info.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>호출 테스트</title>
</head>
<body>
[info] 호출 가능
</body>
</html>

                  info.jsp (8.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>호출 테스트</title>
</head>
<body>
[info] 호출 가능
</body>
</html>

                   ist.jsp (8.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>호출 테스트</title>
</head>
<body>
[list]호출 가능
</body>
</html>

              header
                  pass.jsp (5.예제 @RequestHeader)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>헤더 검사 통과</title>
</head>
<body>
헤더 검사 통과
</body>
</html>
           
              math
                  result.jsp (11.예제 예외페이지)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>연산 성공</title>
</head>
<body>
연산 성공
</body>
</html>

              report
                  submitReportForm.jsp (10.예제 파일업로드)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>리포트 등록 폼</title>
</head>
<body>
<spring:hasBindErrors name="report"/>
<form action="submitReport.do" method="post" enctype="multipart/form-data">
<p>
    <label for="subject">제목</label>
    <input type="text" id="subject" name="subject" value="${report.subject}">
    <form:errors path="report.subject"/>
</p>
<p>
    <label for="reportFile">리포트파일</label>
    <input type="file" id="reportFile" name="reportFile">
    <form:errors path="report.reportFile"/>
</p>
<p>
    <input type="submit" vlaue="리포트전송">
<p>
</body>
</html>

                  submittedReport.jsp (10.예제 파일업로드)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>리포트 등록 완료</title>
</head>
<body>
리포트 '${report.subject}'를 동록했습니다.
</body>
</html>      

              search
                  external.jsp (3.예제 @RequestParam)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>외부 검색</title>
</head>
<body>
외부 검색
</body>
</html>

                  game.jsp (6.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>게임 검색결과</title>
</head>
<body>
인기 키워드 : <c:forEach var="popualrQuery" items="${popularQueryList}">${popularQuery}></c:forEach>
<form action="game.do">
<select name="type">
    <c:forEach var="searchType" items="${searchTypeList}">
        <option value="${serchType.code}"<c:if test="${command.type == searchType.code}">selected</c:if>>${searchType.text}</option>
    </c:forEach>
</select>
<input type="text" name="query" value="${command.query}"/>
<input type="submit" value="검색"/>
</form>
검색결과 : ${searchResult}
</body>
</html>

                  internal.jsp (3.예제 @RequestParam)  
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>내부 검색</title>
</head>
<body>
내부 검색
</body>
</html>

                  main.jsp (6.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>게임 검색 메인</title>
</head>
<body>
인기 키워드 : <c:forEach var="popualrQuery" items="${popularQueryList}">${popualrQuery}></c:forEach>
<form action="game.do">
<select name="type">
    <c:forEach var="searchType" items="${searchTypeList}">
        <option value="${serchType.code}">${searchType.text}</option>
    </c:forEach>
</select>
<input type="text" name="query" value=""/>
<input type="submit" value="검색"/>
</form>
</body>  
</html>

              hello.jsp (1.예제)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>인사</title>
</head>
<body>
인사말 :<strong>${greeting}</strong>
</body>
</html>

          dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>
   
    <!-- 기본설정 -->
    <bean id="helloController" class="madvirus.spring.chap06.controller.HelloController"/>
   
    <!-- 데이터를 전송하여 자바빈에 담기 -->
    <!-- <bean id="newArticleController" class="madvirus.spring.chap06.controller.NewArticleController" p:articleService-ref="articleService" /> -->
    <bean id="newArticleController" class="madvirus.spring.chap06.controller.NewArticleController"/>
   
    <bean id="articleService" class="madvirus.spring.chap06.service.ArticleService" />
   
    <!-- 파라미터로 전송된 데이터 처리 -->
    <bean id="searchController" class="madvirus.spring.chap06.controller.SearchController"/>
   
    <!-- @CookieValue 어노테이션을 이용한 쿠키 매핑 -->
    <bean id="cookieController" class="madvirus.spring.chap06.controller.CookieController"/>
   
    <!-- @RequestHeader 어노테이션을 이용한 쿠키 매핑 -->
    <bean class="madvirus.spring.chap06.controller.HeaderController"/>
       
    <!-- 뷰에 모델 데이터 전달하기 -->
    <bean class="madvirus.spring.chap06.controller.GameSearchController"/>
    <bean id="searchService" class="madvirus.spring.chap06.service.SearchService"/>
   
    <!-- 커멘드 객체 초기화 -->
    <bean class="madvirus.spring.chap06.controller.CreateAccountController"/>
   
    <!-- 요청 URI 매칭  -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="alwaysUseFullPath" value="true"/>
    </bean>   
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="alwaysUseFullPath" value="true"/>
    </bean>
    <bean class="madvirus.spring.chap06.controller.GameInfoController"/>
   
    <!-- @PathVariable 어노테이션을 이용한 URI 템플릿 -->
    <bean class="madvirus.spring.chap06.controller.CharacterInfoController"></bean>
   
    <!-- 파일 업로드 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    <bean class="madvirus.spring.chap06.controller.SubmitReportController"/>
   
    <!-- 예외처리 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.ArithmeticException">
                    error/mathException
                </prop>
                <prop key="java.lang.Exception">
                    error/exception
                </prop>
            </props>
        </property>
    </bean>   
    <bean class="madvirus.spring.chap06.controller.ArithmeticOperatorController"/>
   
    <!-- View 글로벌 설정  -->
    <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
   
    <!-- 리소스 번들 지정 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>messages.validation</value>
            </list>
        </property>
    </bean>
   
</beans>

          web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 
 <!-- 기본 설정 --> <!-- DispatcherServlet -->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
    <url-pattern>/game/*</url-pattern>
  </servlet-mapping>
  <!-- 캐릭터 인코딩 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

index.jsp (메인 링크페이지)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>예제 요청 URL</title>
</head>
<body>
<a href="http://localhost:8080/chap06/hello.do">HelloController</a><br/>
<a href="http://localhost:8080/chap06/article/newArticle.do">NewArticleController</a><br/>
<a href="http://localhost:8080/chap06/search/internal.do?query=spring">SearchController - 1</a><br/>
<a href="http://localhost:8080/chap06/search/external.do">SearchController - 2</a><br/>
<a href="http://localhost:8080/chap06/cookie/make.do">쿠키 생성</a><br/>
<a href="http://localhost:8080/chap06/cookie/view.do">쿠키값 읽기</a><br/>
<a href="http://localhost:8080/chap06/header/check.do">헤더정보 읽기</a><br/>
<a href="http://localhost:8080/chap06/search/main.do">GameSearchController</a><br/>
<a href="http://localhost:8080/chap06/account/create.do">CreateAccountController</a><br/>
<a href="http://localhost:8080/chap06/game/info.do">GameInfoController -1</a><br/>
<a href="http://localhost:8080/chap06/game/list.do">GameInfoController -2</a><br/>
<a href="http://localhost:8080/chap06/game/users/dragon/characters/1">CharacterInfoController</a><br/>
<a href="http://localhost:8080/chap06/report/submitReport.do">파일업로드 SubmitReportController</a><br/>
<a href="http://localhost:8080/chap06/math/divide.do?op1=3&op2=0">예외발생</a><br/>
<a href="http://localhost:8080/chap06/math/divide.do?op1=4&op2=2">연산성공</a><br/>
</body>      
</html>                                                                

=================================결과값====================================

1.예제

2.예제


3.예제 @RequestParam



4.예제 @CookieValue

5.예제 @RequestHeader

6.예제 @ModelAttribute 검색


7.예제 : Validator인터페이스를 이용한 폼 값 검증


8.예제 :



9.예제 restful서비스

10.예제 파일업로드
파일없이 쿼리전송시

11예제. 예외페이지


'스프링3.0' 카테고리의 다른 글

Spring3.0 DB  (0) 2012.05.14
Spring3.0 View error filedown  (0) 2012.05.14
Spring 3.0 AOP  (0) 2012.05.14
Spring3.0 DI 3  (0) 2012.05.14
스프링 3.0 @ 어노테이션 기반 설정  (0) 2012.05.14
Posted by 사라링
BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
VM-WARE (0)
디자인패턴 (1)
스크랩 (0)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
Total :
Today : Yesterday :