$("#pageSize").val($("#selectPageSize").val());    // 한페이지에서 볼 리스트수

$("#pageNum").val(pageNum);                          // 현재 페이지

fn_Search("cpCmsConfirmAjaxList.do", "CpCmsForm", function(result) {

if(result.searchList.length > 0) {

for(var i = 0; i < result.searchList.length; i++) {

inHtml += "<tr>";

inHtml += "<td onclick=\"javascript:fn_CmsView('"+ result.searchList[i].collect_id + "');\">" + result.searchList[i].registration_date_time + "</td>";

inHtml += "<td style=\"text-align:left;\" onclick=\"javascript:fn_CmsView('"+ result.searchList[i].collect_id + "');\">" + result.searchList[i].title + "</td>";

inHtml += "<td onclick=\"javascript:fn_CmsView('"+ result.searchList[i].collect_id + "');\">" + result.searchList[i].status + "</td>";

      inHtml += "</tr>";

      }

      } else {inHtml += "<tr id=\"N\"><td colspan=\"3\">검색결과가 없습니다.</td></tr>";}

inHtmlAppend(inHtml, result.totalCnt, result.pageing);    //HTML, 총개수, 페이징HTML

});

}

<%-- 리스트, 총개수 --%>

function inHtmlAppend(inHtml, totalCnt, pageing) {

$("#listTBL").empty();

$("#listTBL").append(inHtml);

$("#qntty").empty();

$("#qntty").append("총 건수 : " + numberFormat(totalCnt));

$(".nav_num").empty();

$(".nav_num").append(pageing);    // java에서 만들어서 가지고올 페이징 네비 Html

---------------------------



int totalCnt = cmsService.getCpCmsCnt(param);    // 리스트 총개수

resultMap.put("totalCnt", totalCnt);    

if(totalCnt > 0) {    // Mssql between 으로 시작 행과 끝행을 가져올것이므로 ,

      param.setFirstRow((param.getPageNum() - 1) * param.getPageSize() + 1);    // 시작행 (현재페이지 -1 * 화면 리스트(행) 갯수+1)

      param.setLastRow(param.getPageNum() * param.getPageSize() < totalCnt ? param.getPageNum() * param.getPageSize() : totalCnt); // 마지막 페이지 체크

      cmsList = cmsService.getCpCmsList(param);

      resultMap.put("pageing", util.getPageing(totalCnt, param.getPageNum(), param.getPageSize(), ""));    //아래 자세히 _ jsp 화면에 페이지 그릴 메소드

}


resultMap.put("searchList", cmsList);

try {

util.responseAjax(resultMap, response, "");

     } catch (IOException e) {

e.printStackTrace();

     }

mav.addObject("pageList", systemService.getCommonCode("94000"));

return mav;


-------------------------


public static String getPageing(int totalCnt, int pageNum, int pageSize, String fnName) throws DoException {

int pageCnt = (int)Math.ceil((double)totalCnt / pageSize);

// 이전, 다음

int prevPage = pageNum - 1;

prevPage = prevPage < 1?1:prevPage;

int nextPage = pageNum + 1;

nextPage = nextPage < pageCnt ? nextPage : pageCnt;

int firstPage = ((pageNum - 1) / 10) *10 + 1;

int lastPage = ((firstPage / 10) + 1) * 10;

lastPage = lastPage < pageCnt ? lastPage : pageCnt;

  

StringBuffer pageStr = new StringBuffer();

pageStr.setLength(0);

String fnStr = fnName == ""?"fn_ListSearch":fnName;

pageStr.append("<a href=\"javascript:" + fnStr + "('1');\" class=\"arr_pre1\">&lt;&lt;</a>");

pageStr.append("<a href=\"javascript:" + fnStr + "('" + prevPage + "')\" class=\"arr_pre2\">&lt;</a>");

  

for(int i = firstPage; i <= lastPage; i++) {

if(i == (pageNum)) {

pageStr.append("");

pageStr.append("<a href=\"javascript:\" class=\"active\">" + i + "</a>");

} else {

pageStr.append("<a href=\"javascript:" + fnStr + "('" + i + "')\" class=\"page\">" + i + "</a>");

}

}

pageStr.append("<a href=\"javascript:" + fnStr + "('" + nextPage + "')\" class=\"arr_next1\">&gt;</a>");

pageStr.append("<a href=\"javascript:" + fnStr + "('" + pageCnt + "')\" class=\"arr_next2\">&gt;&gt;</a>");

  

return pageStr.toString();

}

-------------------------

sql

블라블라...

WHERE ROWNUM BETWEEN #{firstRow} AND #{lastRow}





'Jsp' 카테고리의 다른 글

javascript - jstl 참조하기  (0) 2014.07.17
@Schedule Spring 스프링 스케쥴 설정법 & CronTab  (0) 2014.07.01
request 의 활용  (0) 2013.12.26
fmt:*date  (0) 2013.12.20
JSTL (JSP Standard Tag Library)  (0) 2013.12.08

 

실행순서가

 JAVA ==> JSLT ==> HTML ==> JAVASCRIPT 

라고 하기때문에 스크립트 변수를 jstl에다 쓸순 없다.

반대로 jstl값을

스크립트에서는 사용할수 있다

사용예)


function doInit() {

<c:set value="${ searchDate.strDay}" var = "strDay"/>      //서버에서 받은값

   <c:set value="${ searchDate.endDay}" var = "endDay"/>  //서버에서 받은값

var endDay       = today();                                       //스크립트에서 처리한값

var strDay       = beforeDay();                                         //스크립트에서 처리한값

    $('#searchDay1').val(strDay); 

    $('#searchDay2').val(endDay);

    <c:if test="${serachStrDate != ''}">                              

     $('#reg_dttm1').val(<c:out value="${serachStrDate}"/>);

    </c:if>

    <c:if test="${serachEndDate != ''}">

        $('#reg_dttm2').val(<c:out value="${serachStrDate}"/>);

    </c:if>

}


출처 - http://blog.naver.com/PostView.nhn?blogId=jinbbak&logNo=191868224





// java

HashMap<Object, Object> map = new HashMap<Object, Object>();

map.put("name""홍길동");

map.put("city""서울");

map.put("age", 30);

 

ArrayList<Object> list = new ArrayList<Object>();

list.add("hong@naver.com");

list.add("gil@daum.net");

list.add("dong@nate.com");

 

ArrayList<HashMap<Object, Object>> arrayListMap = new ArrayList<HashMap<Object, Object>>();

arrayListMap.add(map);

 

HashMap<Object, ArrayList<Object>> lMultiData = new HashMap<Object, ArrayList<Object>>();

lMultiData.put("email", list);

 

mav.addObject("list_map", arrayListMap);

mav.addObject("map_list", lMultiData);

 

 

// javascript

var list1 = new Array();

<c:forEach items="${list_map}" var="item1">

list1.push("${item1.name}");

list1.push("${item1.city}");

list1.push("${item1.age}");

</c:forEach>

for ( var i = 0; i < list1.length; i++) {

    alert(list1[i]);

}

 

var list2 = new Array();

<c:forEach items="${map_list.email}" var="item2">

list2.push("${item2}");

</c:forEach>

for ( var i = 0; i < list2.length; i++) {

    alert(list2[i]);

}


출처 -  http://blog.naver.com/PostView.nhn?blogId=typeofb&logNo=191469973

 

'Jsp' 카테고리의 다른 글

JSP 페이징  (0) 2014.11.07
@Schedule Spring 스프링 스케쥴 설정법 & CronTab  (0) 2014.07.01
request 의 활용  (0) 2013.12.26
fmt:*date  (0) 2013.12.20
JSTL (JSP Standard Tag Library)  (0) 2013.12.08

********************************************************************************************************

스프링 MVC 에서 

일정 시간 주기적으로 작업하는 스케쥴러를 만들어 본다.

 

일단 root-context.xml을 수정한다.

 

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

<beans xmlns="http://www.springframework.org/schema/beans"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"

 xmlns:task="http://www.springframework.org/schema/task"

 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd

        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean id="careerAlarmService" class="kwon.app.profile.AlarmTask" />

 <task:scheduler id="gsScheduler" pool-size="10" />

 <task:executor id="gsTaskExecutor" pool-size="10" />

 <task:annotation-driven executor="gsTaskExecutor"

  scheduler="gsScheduler" />


 <!-- Root Context: defines shared resources visible to all other web components -->

</beans>

 

위 처럼 변경한다.

class는 실제 class파일이 있는 위치 잡아주면 된다.

 

 

원래는

 

 <!-- <beans xmlns="http://www.springframework.org/schema/beans" 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"> -->


이것만 적혀 잇엇을거다. 그리고 나선

 

public class AlarmTask {

 

private static final Logger logger = LoggerFactory.getLogger(AlarmTask.class);

 

@Scheduled(cron="*/30 * * * * *") 

public void scheduleRun(){

 Calendar calendar = Calendar.getInstance();

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 //System.out.println("스케줄 실행 : " + dateFormat.format(calendar.getTime()));

 logger.info("스케줄 실행 : " + dateFormat.format(calendar.getTime()));

 //System.out.println("Request " + getCurrentRequest());

}

 

}

 

클래스를 만들어 준다.

 

이러면 30초마다 실행되는 것이다.

@Scheduled(cron="*/30 * * * * *") 

 


********************************************************************************************************

 

스프링에서는 간편하고 프레임워크안에서 스케쥴링 하던 quatz 를 annotation 으로 더 간단하게 설정 할 수 있다.


applicationContext.xml 같은 bean 을 설정하는 설정파일에

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.0.xsd

<task:annotation-driven />

 

구문을 입력하면 된다.

EX) 별도의 context-schedule.xml 로 관리(첨부파일 확인)

파일명 : context-schedule.xml  ( context-schedule.xml)

 

 

스케쥴링 할 메소드위에 @scheduled 어노테이션을 입력한 후에 시간설정하면 끝

 

3. 시간 설정 @scheduled(cron=" ")  * 리눅스 crontab 과 같은 설정방법

ex> @Scheduled(cron="0 0 02 * * ?") = 매일 새벽2시에 실행

ex> @Scheduled(cron="0 0 02 2,20 * ?") = 매월 2일,20일 새벽2시에 실행

 


********************************************************************************************************


스케쥴러 cron 양식

 

초 0-59 , - * / 

분 0-59 , - * / 

시 0-23 , - * / 

일 1-31 , - * ? / L W

월 1-12 or JAN-DEC , - * / 

요일 1-7 or SUN-SAT , - * ? / L # 

년(옵션) 1970-2099 , - * /

* : 모든 값

? : 특정 값 없음

- : 범위 지정에 사용

, : 여러 값 지정 구분에 사용

/ : 초기값과 증가치 설정에 사용

L : 지정할 수 있는 범위의 마지막 값

W : 월~금요일 또는 가장 가까운 월/금요일

# : 몇 번째 무슨 요일 2#1 => 첫 번째 월요일

 

예제) Expression Meaning 

초 분 시 일 월 주(년)

 "0 0 12 * * ?" : 아무 요일, 매월, 매일 12:00:00

 "0 15 10 ? * *" : 모든 요일, 매월, 아무 날이나 10:15:00 

 "0 15 10 * * ?" : 아무 요일, 매월, 매일 10:15:00 

 "0 15 10 * * ? *" : 모든 연도, 아무 요일, 매월, 매일 10:15 

 "0 15 10 * * ? : 2005" 2005년 아무 요일이나 매월, 매일 10:15 

 "0 * 14 * * ?" : 아무 요일, 매월, 매일, 14시 매분 0초 

 "0 0/5 14 * * ?" : 아무 요일, 매월, 매일, 14시 매 5분마다 0초 

 "0 0/5 14,18 * * ?" : 아무 요일, 매월, 매일, 14시, 18시 매 5분마다 0초 

 "0 0-5 14 * * ?" : 아무 요일, 매월, 매일, 14:00 부터 매 14:05까지 매 분 0초 

 "0 10,44 14 ? 3 WED" : 3월의 매 주 수요일, 아무 날짜나 14:10:00, 14:44:00 

 "0 15 10 ? * MON-FRI" : 월~금, 매월, 아무 날이나 10:15:00 

 "0 15 10 15 * ?" : 아무 요일, 매월 15일 10:15:00 

 "0 15 10 L * ?" : 아무 요일, 매월 마지막 날 10:15:00 

 "0 15 10 ? * 6L" : 매월 마지막 금요일 아무 날이나 10:15:00 

 "0 15 10 ? * 6L 2002-2005" : 2002년부터 2005년까지 매월 마지막 금요일 아무 날이나 10:15:00 

 "0 15 10 ? * 6#3" : 매월 3번째 금요일 아무 날이나 10:15:00



Linux CronTab

예) 40 3 * * * root /home/mysql/mysql_backup.sh


맨 앞의 40은 40분을 의미함 (분을 의미:0~59)

그 뒤의 3은 03시를 의미함 (시를 의미:0~23)

그 뒤의 * 은 매일을 의미함 (일을 의미:1~31)

그 뒤의 * 은 매월을 의미함 (월을 의미:1~12)

그 뒤의 * 은 매주를 의미함(요일을 의미 1:월요일~7:일용일)

그 뒤의 root /home/mysql/mysql_backup.sh 는 root  계정으로 mysql_backup.sh을 실행하라는 의미


문자 : 각 필드에 해당하는 모든 숫자를 의미

문자 : 각 필드자리에 하이픈 문자가 올수 있음

ex) 일 필드자리에 11-15 (11,12,13,14,15일을 의미)

문자 : 각 필드자리에 콤마문자가 올수 있음

ex) 일 필드자리에 1,11,21 (1일,11일 21일을 의미)


1/1000 초 설정법

@Scheduled(fixedDelay=1000)

 1000 적으면 1초 인것이다!!!!

 30초 하려면 1000 * 30 하면 되지 뭐. 



'Jsp' 카테고리의 다른 글

JSP 페이징  (0) 2014.11.07
javascript - jstl 참조하기  (0) 2014.07.17
request 의 활용  (0) 2013.12.26
fmt:*date  (0) 2013.12.20
JSTL (JSP Standard Tag Library)  (0) 2013.12.08

■ local의 기본 정보 (IP, Name, Port)
Local IP : <%=request.getLocalAddr()%>
Local Name : <%=request.getLocalName()%>
Local Port : <%=request.getLocalPort()%>

■ 클라이언트의 정보
Remote IP : <%=request.getRemoteAddr()%>
Remote Host : <%=request.getRemoteHost()%>
Remote Port : <%=request.getRemotePort()%>

■ 서버 이름과 포트 (일반적으로 local 기본정보와 동일)
Server Name : <%=request.getServerName()%>
Server Port : <%=request.getServerPort()%>

■ 지역 정보 (대부분 한국을 의미하는 ko가 나옴)
Locale : <%=request.getLocale()%>

 

■ 사용하는 프로토콜 ("프로토콜/메이저버전.마이너버전" 의 형태)
Protocol : <%=request.getProtocol()%>

■ http, https, ftp와 같은 것을 의미
Scheme : <%=request.getScheme()%>

 

■ https와 같은 보안 채널의 사용 여부 (true/false 값으로 되어 있음)
Secure Channel : <%=request.isSecure()%><br>

 

■ 요청에 대한 URI, URL, 컨텍스트 경로, 서블릿 경로, GET/POST등의 메소드
Request's URI : <%=request.getRequestURI()%>
Request's URL : <%=request.getRequestURL()%>
Context Path : <%=request.getContextPath()%>
Servlet Path : <%=request.getServletPath()%>

Method : <%=request.getMethod()%>

■ 세션 ID에 대한 정보
Session ID : <%=request.getRequestedSessionId()%>
Session ID from Cookie : <%=request.isRequestedSessionIdFromCookie()%>
Session ID from URL : <%=request.isRequestedSessionIdFromURL()%>
Session ID is still valid : <%=request.isRequestedSessionIdValid()%>

■ Header 정보
<%
Enumeration eHeader = request.getHeaderNames();
while (eHeader.hasMoreElements()) {
    String hName = (String)eHeader.nextElement();
    String hValue = request.getHeader(hName);

    out.println(hName + " : " + hValue + "<br>");
}
%>

■ Request 객체를 통해서 쿠키 정보를 보는 방식
<%
Cookie cookies[] = request.getCookies();
for (int i=0; i < cookies.length; i++) {
    String name = cookies[i].getName();
    String value = cookies[i].getValue();

    out.println(name + " : " + value + "<br>");
}
%>

 

    /**
    * cookie 값을 설정하는 메소드.
    * @param HttpServletResponse response
    * @param String cookieName
    * @param String cookieValue
    */
    public void setCookie(HttpServletResponse response, String cookieName, String cookieValue) {
        int maxAge = (60 * 60 * 24 * 15); // 15day
        setCookie(response, cookieName, cookieValue, maxAge);
    }

 

    /**
    * cookie 값을 설정하는 메소드.
    * @param HttpServletResponse response
    * @param String cookieName
    * @param String cookieValue
    * @param int maxAge
    */
    public void setCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
        cookieValue = URLEncoder.encode(cookieValue);
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

 

    /**
    * cookie 값을 찾아서 리턴하는 메소드.
    * @param HttpServletRequest request
    * @param String cookieName
    * @return String
    */
    public String getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        String cookieValue = null;
        for (int i = 0; i < cookies.length; i++) {
            if (cookieName.equals(cookies[i].getName())) {
                cookieValue = URLDecoder.decode(cookies[i].getValue());
                break;
            }
        }
        return cookieValue;
    }

■ HTML 폼을 통해 넘어온 데이터를 받는 부분
<%
Enumeration eParam = request.getParameterNames();
while (eParam.hasMoreElements()) {
    String pName = (String)eParam.nextElement();
    String pValue = request.getParameter(pName);

    out.println(pName + " : " + pValue + "<br>");
}
%>

■ 미리 설정한 attribute를 가져오는 부분
<%
Enumeration eAttr = request.getAttributeNames();
while (eAttr.hasMoreElements()) {
    String aName = (String)eAttr.nextElement();
    String aValue = request.getHeader(aName);

    out.println(aName + " : " + aValue + "<br>");
}
%>

 

request.XXX

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

// 클라이언트 정보 및 서버정보 읽기

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

String  getRemoteAddr()               웹서버에 연결한 클라이언트의 IP 주소를 가져온다.

long     getContentLength()          클라이언트가 전송한 요청 정보의 길이를 구해온다.

String  getCharacterEncoding()     클라이언트가 요청 정보를 전송할 때 사용한 캐릭터

                                                      의  인코딩을 구해온다.

String  getContentType()              클라이언트가 요청 정보를 전송할 때 사용한 컨텐츠

                                                      의 타입을 구해온다.

String  getProtocol()                     클라이언트가 요청한 프로토콜을 구한다.

String  getMethod()                      웹 브라우저가 정보를 전송할 때 사용한 방식을 구한다.

String  getRequestURI()               웹 브라우저가 요청한 URL에서 경로를 구한다.

String  getContextPath()              JSP페이지가 속한 웹 어플리케이션의 콘텍스트 경로를

                                                    구한다.

String  getServerName()              연결할 때 사용한 서버 이름을 구한다.

String  getServerPort()                서버가 실행 중인 포트 번호를 구한다.

 

 

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

//HTML폼과 요청파라미터 처리

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

String  getParameter(String name)                          이름이 name인 파라미터의 값을 구한다                                                                      (Request("name") 과 동일)

String[]  getParameterValues(String name)            이름이 name인 모든 파라미터의 값을                                                                         배열로 가져온다.

java.util.Enumeration  getParameterNames()         웹브라우저가 전송한  파라미터의

                                                                                이름을 구한다.

java.util.Map  getParameterMap()                           웹브라우저가 전송한 파라미터의

                                                                                맵을 구한다.

 

ex> name파람 = request.getParameter("name")

      Enumeration enum = request.getParameterNames();

         while(enum.hasMoreElements)

              String name = (String)enum.nextElement();

 

 

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

//요청 헤더 정보의 처리

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

String  getHeader(String name)                              지정한 이름의 헤더값을 구한다.

java.util.Enumeration  getHeasers(String name)    지정한 이름의 헤더 목록을 구한다.

java.util.Enumeration  getHeaderName()                모든 헤더의 이름을 구한다.

int  getIntHeader(String name)                               지정한 헤더의 값을 정수값으로

                                                                                읽어온다.

long getDateHeader(String name)                      지정한 헤더의 값을 시간값으로

                                                                            읽어온다 (1970년1월1일 이후로

                                                                            흘러간 1/1000초 단위로 읽어온다.)

ex> Enumeration enum = request.getHeaderNames();

        while(enum.hasMoreElements()){

            String headerName = (String)enum.nextElement();

            String headerValue = request.getHeader(headerName);

        }

 

 

 

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

//값 설정하기(Attribute)

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

void  setAttribute(String name, Object values)   이름이 name인 속성의 값을 values로 저장한다.

Object getAttribute(String name)                        이름이 name인 속성의 값을 구한다.

void removeAttribute(String name)                     이름이 name인 속성을 삭제한다.

java.util.Enumeration getAttributeNames()         속성의 이름 목록을 구한다.

 

## 주의 : setAttribute 에서 값이 Object이기 때문에 int, double과 같은 기본 데이터 타입은 속성값에 할당 할 수 없다. 이유는 Object가 아니기 때문이다. 이 경우엔 레퍼 클래스를 사용해야 한다.

      Integer intValue = new Integer(100);

      request.setAttribute("radio", intValue); 

      ...

      Integer intValue = (Integer)request.getAttribute("radio");

      int value = intValue.intValue();

[출처] Request 활용|작성자 고구마


'Jsp' 카테고리의 다른 글

JSP 페이징  (0) 2014.11.07
javascript - jstl 참조하기  (0) 2014.07.17
@Schedule Spring 스프링 스케쥴 설정법 & CronTab  (0) 2014.07.01
fmt:*date  (0) 2013.12.20
JSTL (JSP Standard Tag Library)  (0) 2013.12.08

+ Recent posts