<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title>페이지 내용을 동적으로 바꾸는 예제</title>
<script language="JavaScript">
<!--
var xmlHttp;
var requestType;

// XHR 객체를 생성한다.
function createXMLHttpRequest() {
    if(window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if(window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
// 조회를 한다.
function doSearch() {
    requestType = document.getElementById("부서").value;
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "dynamicContent.xml", true);
    xmlHttp.send(null);
}
// 요청 처리 콜백 함수
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            clearPreviousResults();
            parseResults();
        }
    }
}
// 이전 결과를 지운다.
function clearPreviousResults() {
    var header = document.getElementById("header");
    if(header.hasChildNodes()) {
        header.removeChild(header.childNodes[0]);
    }
    var tableBody = document.getElementById("resultsBody");
    while(tableBody.childNodes.length > 0) {
        tableBody.removeChild(tableBody.childNodes[0]);
    }
}

// 요청의 결과를 테이블 형태로 동적으로 출력한다.
function parseResults() {
    var results = xmlHttp.responseXML;
    var code = "";
    var departmentName = "";
    var position = "";
    var name = "";
// 모든 사원노드를 배열로 가져옵니다.
    var staffs = results.getElementsByTagName("사원");
    for(var i = 0; i < staffs.length; i++) {
        // 부모노드의 부서 코드를 가져옵니다.
        code = staffs[i].parentNode.getAttribute("code");
        // 부서를 선택했을 경우 코드가 다르면 건너뜁니다.
        if(requestType != "all" && code != requestType) continue;
        // 부서명, 직위, 이름 정보를 가져옵니다.
        departmentName = staffs[i].parentNode.getAttribute("title");
        position = staffs[i].getAttribute("position");
        name = staffs[i].childNodes[0].nodeValue;
        addTableRow(departmentName, position, name);
    }
    var header = document.createElement("h2");
    var headerText = document.createTextNode("조회결과:");
    header.appendChild(headerText);
    document.getElementById("header").appendChild(header);
    document.getElementById("resultsTable").setAttribute("border", "1");
}
// 테이블의 TR 엘리먼트를 주어진 내용으로 생성한다.
function addTableRow(departmentName, position, name) {
    // 테이블 행 엘리먼트를 생성합니다.
    var row = document.createElement("tr");
    // 테이블 데이터 엘리먼트를 생성해서 추가합니다.
    var cell = createCellWithText(departmentName);
    row.appendChild(cell);
    cell = createCellWithText(position);
    row.appendChild(cell);
    cell = createCellWithText(name);
    row.appendChild(cell);
    // 테이블에 행을 추가합니다.
    document.getElementById("resultsBody").appendChild(row);
}
// 테이블의 TD 엘리먼트를 주어진 text 를 내용으로 하여 생성한다.
function createCellWithText(text) {
   // 테이블 데이터 엘리먼트를 생성합니다.
    var cell = document.createElement("td");
    var textNode = document.createTextNode(text);
    cell.appendChild(textNode);
    return cell;
}
//-->
</script>
</head><body>
<h3>페이지 내용을 동적으로 바꾸는 예제</h3>
<h1>부서별 조회</h1>
<form action="#">
부서
<select id="부서">
  <option value="all">전체</option>
  <option value="sale">영업부</option>
  <option value="insa">인사부</option>
</select>
<input type="button" value="Search" onclick="doSearch();"/>
</form>
<span id="header"></span>
<table id="resultsTable" width="500" border="0">
  <tbody id="resultsBody">
  </tbody>
</table></body></html>

 

 

 

 

 

 

 

 




『 단순한 파일 업로드 』

​<소스코드>

​* 컨트롤러 작성

 @Controller
@RequestMapping("/test/fileupload")
public class FileuploadController {
   
    @RequestMapping(method=RequestMethod.GET)
public void setupForm(Model model) {        
    }
   
    // 하나의 파일을 업로드함
    @RequestMapping(value="single", method=RequestMethod.POST)
    public ModelAndView doAction(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {

if(!file.getOriginalFilename().isEmpty() && !file.isEmpty()) {
            File uploadFile = new File("d:/upload/", file.getOriginalFilename());
            //서버내의 다른 장소에 업로드함
            file.transferTo(uploadFile);            
            ModelAndView mav = new ModelAndView("/test/complete");
            mav.addObject("filename", file.getOriginalFilename());
            mav.addObject("filesize", FileUtils.byteCountToDisplaySize(file.getSize()));
            return mav;
           
        } else {
            ModelAndView mav = new ModelAndView("/test/fail");
            return mav;
        }
    }
}


 

 

 

 

 

 




『 단순한 파일 업로드 』

​<소스코드>


* JSP 작성

​form속성에 enctype="multipart/form-data“ 추가

<h4>파일 업로드</h4>
<form action="${appUrl}/test/fileupload/single.html" method="post" enctype="multipart/form-data">
   
    <input type="file" name="file" />
   
    <input type="submit"/>
</form>


 

 

 

 

 

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <servlet>
        <servlet-name>ValidationServlet</servlet-name>
        <servlet-class>validation.ValidationServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ValidationServlet</servlet-name>
        <url-pattern>/validation</url-pattern>
    </servlet-mapping>
</web-app>


 

 

 

 

'자바 > JAVA...Spring' 카테고리의 다른 글

dynamicUpdate.html  (0) 2015.12.29
[/Web-INF/src/validation/ ValidationServlet .java]  (0) 2015.12.28
[form_test.html]  (0) 2015.12.28
[ajax_test.html]  (0) 2015.12.24
[oraclejava.xml]  (0) 2015.12.24

 



<파일 업로드>

​- CommonsFileUpload 준비

- Spring MVC 3.1 + Servlet 3.0 멀티파트 기능 준비

- 단순한 파일 업로드

- 멀티 파일 업로드

- 파일 사이즈 초과시 처리방법


 

 

 

 

 

 



<수치형 바인드 처리>

​<JSP 작성>

<h4>수치형 바인드 처리</h4>
<form:form modelAttribute="command" action="${appUrl}/test/customizeNumberBind.html" method="post">
   
    <p>
        <form:label path="amount">합계</form:label>
        <form:input path="amount" />
        <form:errors path="amount" cssClass="errors" />
    </p>
   
    <p>
        <form:label path="average">평균</form:label>
        <form:input path="average" />
        <form:errors path="average" cssClass="errors" />
    </p>
   
    <input type="submit"/>
</form:form>
 

 

 

 

 

 



<수치형 바인드 처리> 


<controller 작성>


import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
 
@Controller
@RequestMapping("/test/customizeNumberBind")
public class CustomizeNumberBindController {    
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
       
        // 이름을 지정하여 바인드 처리
        NumberFormat amountFormat = NumberFormat.getInstance();
        binder.registerCustomEditor(Long.class, "amount",
                new CustomNumberEditor(Long.class, amountFormat, true));
       
        // 타입을 지정하여 바인드 처리
        DecimalFormat doubleFormat = new DecimalFormat("###,###.###");
        binder.registerCustomEditor(Double.class,
                new CustomNumberEditor(Double.class, doubleFormat, true));
                 //DecimalFormat도 사용가능하다
              }
   
    // @RequestMapping 등 생략


 

 

 

 

 



『 날짜형 바인드 』

​- Command 클래스 작성

- 컨트롤러 작성

- JSP 작성

- 에러 메시지 정의

​▷ Command 클래스 작성

 

import java.io.Serializable;
import java.util.Date;
 
import org.apache.commons.lang.builder.ToStringBuilder;
 
public class CustomizeDateBindCommand implements Serializable {
 
    private static final long serialVersionUID = 1L;
   
    private Date startDate;
   
    private Date endDate;
   
    public CustomizeBindCommand() {
    }
   
    // getter、setter 생략
   
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}


 

 

 


+ Recent posts