본문 바로가기

회고록(TIL&WIL)

TIL 2023.02.09 jQuery3 Servlet

jQuery

carousel

//--------------------------- css -----------------------------------------
<style type="text/css" rel="stylesheet">
    div{
        width: 400px;
        height: 100px;
        overflow: hidden;
    }
    div>ul{
        padding: 0px;
        width: 700px;
        height: 100px;
        margin-top: 0px;
        margin-left: -150px;
        list-style: none;
        overflow: hidden;
    }
    div>ul>li{
        float: left;
    }
    div>ul>li>img{
        width: 100px;
        height: 100px;
    }
</style>
//---------------------------- script --------------------------------------
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        $('#nxt').click(function(){
            $('div>ul')
            .animate({marginLeft: '-250px'}, 1000, 'linear', function(){
                $('div>ul').css('margin-left', -150);
                $('li').eq(0).appendTo('ul');
                $(this).clearQueue();
            });
        })
        $('#prv').click(function(){
            $('div>ul')
            .animate({marginLeft: '-50px'}, 1000, 'linear', function(){
                $('div>ul').css('margin-left', -150);
                $('li').eq(6).prependTo('ul');
                $(this).clearQueue();
            })
        })
    });
</script>
<style>
        div{
            width: 600px;
            height: 120px;
            overflow: hidden;
        }
        div>ul{
            width: 600px;
            list-style: none;
            margin: 0px;
            padding: 0px;
            margin-left: -100px;
        }
        div>ul>li{
            float: left;
        }
        div>ul>li>img{
            width: 100px;
        }
    </style>
    <script>
        $(function(){
            var target = $('<li/>').width(100).height(100).prependTo('ul');
            var nextCallback=function(){
                $('li').eq(1).appendTo('ul');
                target.show();
            };
            
            $('a').click(function(){
                return false;
            }).first().click(function(){
                console.log('first');
            }).next().click(function(){
                console.log('next');
                target.hide(1000,nextCallback);
            });

            $('<a href="#">&lt;</a>').click(function(){
                $('div a').first().click();
                return false;
            }).insertBefore('div');
            $('<a href="#">&gt;</a>').click(function(){
                $('div a').last().click();
                return false;
            }).insertBefore('div');
        });
    </script>

JSP Servlet

jsp의 단점 소스코드가 실행코드라서 보안상 매우 취약함 자바의 장점을 살릴 수 없음
Servlet은 Java의 장점을 모두 살릴 수 있느나 만들기에는 불편한 점이 있다.
요청-> 톰캣이 가장 먼저 받음
톰캣에서 URL을 확인함 받은 URL이 web.xml에 servlet 매핑 되어있는지 확인
일치하는 URL에 해당하는 servlet을 확인하여 해당하는 클래스의 객체를 생성해야함
이 때 객체 생성도 가능하고 메서드도 호출할 수 있어야하는데 자바의 다형성을 이용해서
Servlet 객체를 구현하도록 하여 객체 생성도 가능하고 메서드 호출도 가능할 수 있도록 하는 것

web.xml



  day45
  
    ex01.html
  
  
  	step01
  	/ex05.html
  
  
  	step01
  	com.bit.step01.Ex01Controller
  

Servlet

public class Ex01Controller implements Servlet{
	ServletConfig config;
	
	@Override
	public void destroy() {
		// 이 클래스를 통해 생성된 객체가 없어질 때(서버를 죽일 때)
		System.out.println("destory");
	}

	@Override
	public ServletConfig getServletConfig() {
		System.out.println("config");
		return config;
	}

	@Override
	public String getServletInfo() {
		System.out.println("info");
		return "테스트삼아 작성하지만 출력되진 않는다";
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		// 객체를 생성할 때 당시 하고 싶은 일을 명세
		System.out.println("init");
		config=arg0;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// 실제로 퍼포먼스를 보일 일들을 명세
		System.out.println("service");
	}
	
}

GenericServlet - 추상화

// == GenericServlet
public abstract class Ex03Controller implements Servlet {
	ServletConfig config;
	
	@Override
	public void destroy() {}

	@Override
	public ServletConfig getServletConfig() {return config;}

	@Override
	public String getServletInfo() {return "";}

	@Override
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}
	@Override
	public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
}
public class Ex04Controller extends GenericServlet{

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		try {
			out.println("<h1>ex07</h1>");
		} finally {
			if(out!=null) out.close();
		}
	}

}

HttpServlet - HTTP메서드에 따라 재정의해서 사용하기 쉽도록

// == HttpServlet
public class Ex05Controller extends GenericServlet {

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// JSP와 같은 객체이나 부모객체로 받아 오기 때문에 다운캐스팅이 필요하다.
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		System.out.println(request.getMethod());
		if("GET".equals(request.getMethod())) {
			doGet(request, response);
		} else if ("POST".equals(request.getMethod())) {
			doPost(request, response);
		}
	}
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
		res.setStatus(405);// method not allowed
	};
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{};
}

public class Ex06Controller extends HttpServlet {
	// 원하는 메서드를 오버 라이딩해서 작성해야한다.
//	@Override
//	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//		PrintWriter out = res.getWriter();
//		try {
//			out.println("<h1>DoGet page</h1>");
//		} finally {
//			if(out!=null) out.close();
//		}
//	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		try {
			out.println("<h1>DoPost page</h1>");
		} finally {
			if(out!=null) out.close();
		}
	}
}

javascript - xhr

<script type="text/javascript">
var xhr;
window.onload = function(){
	xhr = new XMLHttpRequest();
	xhr.onreadystatechange()=function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			console.log(xhr.responseXML);
		}
	};
	xhr.open('get', 'ex11.xml');
	xhr.send();
}
</script>

xml

public class Xml01Controller extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("call Xml01Controller");
		String param = req.getParameter("cnt");
		if(param == null) param = "1";
		int cnt = Integer.parseInt(param);
		PrintWriter out = resp.getWriter();
		try {
			out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			out.println("<stus>");
			for(int i = 0; i < cnt; i++) {
				out.println("<stu>");
				out.println("	<num>"+(i+1)+"</num>");
				out.println("	<name>user"+(i+1)+"</name>");
				out.println("	<kor>9"+(i+1)+"</kor>");
				out.println("	<eng>8"+(i+1)+"</eng>");
				out.println("	<math>7"+(i+1)+"</math>");
				out.println("</stu>");
			}
			out.println("</stus>");
		} finally {
			if(out!=null) out.close();
		}
	}
}
------------------------- html ---------------------------
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
	var callback = function(data,resultText,xhrObject){
		console.log(typeof data); // xml로 받으면 object 기본은 String
		//console.log(data,resultText,xhrObject);
		$(data).find('stu').each(function(idx, ele){
			//console.log(ele);
			var tr = $('<tr/>').appendTo('tbody');
			$(ele).children().each(function(idx,ele){
				tr.append('<td>'+$(ele).html()+'</td>')
				
			});
		});
	};
// 	$.get('ex11.xml?cnt=6', callback);
	$.post('ex11.xml', {cnt:5}, callback, "xml");
});
</script>

json

public class JsonController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json");
		PrintWriter out = resp.getWriter();
		try {
			out.println("{\"stu\":[");
			for(int i = 0; i < 6; i++) {
				if(i!=0) out.print(",");
				out.println("{\"num\":"+(i+1)+", \"name\":\""+(i+1)+"\",\"kor\":9"+(i+1)+",\"eng\":8"+(i+1)+",\"math\":7"+(i+1)+"}");
			}
			out.println("]}");
		} finally {
			if(out!=null) out.close();
		}
	}
}
------------------------- html -----------------------------------
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
	$.get('ex13.json', function(data){
		data.stu.forEach(function(ele,idx){
			console.log(ele.num, ele.name, ele.kor, ele.eng, ele.math);
			$('<tr/>').appendTo('tbody')
				.append($('<td/>').html(ele.num))
				.append($('<td/>').html(ele.name))
				.append($('<td/>').html(ele.kor))
				.append($('<td/>').html(ele.eng))
				.append($('<td/>').html(ele.math));
			
		});
	}, "json")
});
</script>