각 서비스 객체를 생성해서 서버쪽을 컨트롤하는 ControllerServlet 클래스
package jun.mvc.servlet;
@WebServlet("/cont/*")
public class ControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
String uri = request.getRequestURI();// JavaWEB/login
String url = request.getRequestURL().toString();// http://localhost:7777/JavaWEB/login
// String cxtPath = request.getContextPath();// /JavaWEB
String cmd = uri.split("/cont/")[1];// login
try {
Service svc = (Service) Class.forName("jun.mvc.service." + cmd + "Service").newInstance();
/*String viewPath = svc.process(request);
RequestDispatcher rd = sc.getRequestDispatcher(viewPath);
rd.forward(request, response);*/
String json = svc.process(request);
PrintWriter pw = response.getWriter();
log(json);
pw.print(json);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Emp 관련 서비스를 처리하는 클래스
package jun.mvc.service;
public class EmpService implements Service {
@Override
public String process(HttpServletRequest request) {
String path = null;
String json = null;
if (request.getParameter("cmd").equals("empInfo")) {
json = this.empSearch(request);
} else if (request.getParameter("cmd").equals("empList")) {
json = this.empList(request);
} else if (request.getParameter("cmd").equals("deptList")) {
json = this.deptList(request);
} else if (request.getParameter("cmd").equals("deptInfo")) {
json = this.deptSearch(request);
}
return json;
}
@SuppressWarnings("unchecked")
private String deptSearch(HttpServletRequest request) {
EmpDao empDao = new EmpDao();
List<Emp> list = empDao.getDeptList(Integer.parseInt(request.getParameter("no")));
JSONArray jsonArr = new JSONArray();
for(int i = 0; i < list.size(); i++) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("empno", list.get(i).getNo());
jsonObj.put("ename", list.get(i).getName());
jsonObj.put("dname", list.get(i).getdName());
jsonObj.put("sal", list.get(i).getSal());
jsonObj.put("url", list.get(i).getUrl());
jsonArr.add(jsonObj);
}
String json = jsonArr.toJSONString();
return json;
}
@SuppressWarnings("unchecked")
private String deptList(HttpServletRequest request) {
EmpDao empDao = new EmpDao();
List<Emp> list = empDao.getDept();
JSONArray jsonArr = new JSONArray();
for(int i = 0; i < list.size(); i++) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("deptno", new Integer(list.get(i).getDeptno()));
jsonArr.add(jsonObj);
}
String json = jsonArr.toJSONString();
/*String json = "{\"list\":[";
for (int i = 0; i < list.size(); i++) {
if (i == list.size() - 1) {
json += String.format("{\"deptno\": \"%d\"}", list.get(i).getDeptno());
break;
}
json += String.format("{\"deptno\": \"%d\"},", list.get(i).getDeptno());
}
json += "]}";*/
return json;
}
private String empSearch(HttpServletRequest request) {
EmpDao empDao = new EmpDao();
int no = Integer.parseInt(request.getParameter("no"));
Emp emp = empDao.searchEmp(no);
// json 문자열을 만들어서 리턴해준다
String json =
"{\"empno\":\"" + emp.getNo() + "\",\"ename\":\"" + emp.getName() + "\",\"dname\":\"" + emp.getdName() + "\",\"sal\":\"" + emp.getSal() + "\"}";
return json;
}
private String empList(HttpServletRequest request) {
EmpDao empDao = new EmpDao();
List<Emp> list = empDao.getList();
String json = "{\"list\":[";
for (int i = 0; i < list.size(); i++) {
if (i == list.size() - 1) {
json += String.format("{\"empno\": \"%d\"}", list.get(i).getNo());
break;
}
json += String.format("{\"empno\": \"%d\"},", list.get(i).getNo());
}
json += "]}";
return json;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/jquery-2.2.2.min.js"></script>
<style type="text/css">
table td, th {
padding: 10px;
width: 120px;
text-align: center;
}
table {
clear: both;
border: 1px solid #ccc;
margin-top: 50px;
}
table th {
border-bottom: 4px double #ccc;
border-right: 1px solid #ccc;
}
table th:nth-child(5), table td:nth-child(5) {
border-right: none;
}
table td {
border-bottom: none;
border-right: none;
}
table td {
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
div {
width: 50px;
float: left;
text-align: center;
}
div:nth-child(1) {
width: 150px;
}
div:nth-child(1):before {
content: "부서번호 -> ";
}
img {
width: 100px;
}
</style>
<title>AJAX STD</title>
<script type="text/javascript">
$(function() {
$("table").append("<tr><th>사번</th><th>이름</th><th>부서</th><th>급여</th><th>사진</th></tr>");// 테이블 헤더부분 만듬
jQuery.ajax({
// 요청
type : "POST",// 요청시 POST방식으로 서버에 전달
url : "../cont/Emp",// url뒷부분에 붙어서 ControllerServlet에서 @WebServlet으로 인식해서 실행
data : {
cmd : "deptList"
},
dataType : "json",
// 응답
success : function(obj) {// 요청에 성공하면 함수 실행 data는 응답 데이터가 들어간다
for (var i = 0; i < obj.length; i++) {
$("body").prepend("<div></div>");// body 맨 처음에 div태그를 붙힌다
}
$("body").find("div").each(function(idx) {
$(this).text(obj[idx].deptno);// div 안에 서블릿에서 응답받은 jsonArray에 있는 deptno를 입력한다
});
},
complete : function(data) {// 응답이 종료되면 실행, 잘 사용하지않는다
},
error : function(xhr, status, error) {
alert("ERROR!!!");
console.log(status);
console.log(xhr);
console.log(error);
}
});
$(document).on("mouseleave", "table", mouseLeave);
$(document).on("mouseenter", "div", empInfo);
});
function mouseLeave() {
$("table tr").each(function(index) {
if (index != 0)
$(this).remove();
});
}
function empInfo() {// 부서번호에 마우스오버시 실행 되는 함수
var serData = $(this).text();
$("table tr").each(function(index) {
if (index != 0)
$(this).remove();
});
jQuery.ajax({
// 요청
type : "POST",
url : "../cont/Emp",// 컨트롤러 webservlet
data : {
no : serData,// 마우스오버된 부서번호를 전달
cmd : "deptInfo"// EmpService에서 해당 함수를 호출하기 위해서 명령어를 전달
},
dataType : "json",// 응답 타입을 json으로 설정
// 응답
success : function(obj) {// 요청에 성공하면 함수 실행 data는 응답 데이터가 들어간다
for (var i = 0; i < obj.length; i++) {
$("table").append("<tr></tr>");
}
$("table tr").each(function(idx) {
if (idx != 0) {
$(this).append("<td></td><td></td><td></td><td></td><td><img></td>");
}
});
$("table tr").each(function(idx) {
var index = idx + 1;
$("table tr:eq(" + index + ") td:eq(0)").text(obj[idx].empno);
$("table tr:eq(" + index + ") td:eq(1)").text(obj[idx].ename);
$("table tr:eq(" + index + ") td:eq(2)").text(obj[idx].dname);
$("table tr:eq(" + index + ") td:eq(3)").text(obj[idx].sal);
$("table tr:eq(" + index + ") td:eq(4) img").attr("src", "../images/" + obj[idx].url);
});
},
complete : function(data) {// 응답이 종료되면 실행, 잘 사용하지않는다
},
error : function(xhr, status, error) {
alert("ERROR!!!");
console.log(status);
console.log(xhr);
console.log(error);
}
});
}
</script>
</head>
<body>
<table></table>
</body>
</html>
'JQUERY > Basic' 카테고리의 다른 글
Jquery 이벤트 (0) | 2016.03.29 |
---|---|
PreventDefault()사용 예제 (0) | 2016.03.29 |