<button id="btncsv">csv데이터 가져오기</button>
<div id="csvcontainer"></div>
<script>
$("#btncsv").click(e=>{
$.ajax({
url:"<%=request.getContextPath()%>/ajax/csvdata.do",
dataType:"text",
success:data=>{
const actors=data.split("\n");
console.log(actors);
const table=$("<table>");
const header="<tr><th>이름</th><th>전화번호</th><th>프로필</th></tr>";
table.html(header);
actors.forEach(e=>{
const tr=$("<tr>");
const actor=e.split(",");
const name=$("<td>").text(actor[0]);
const phone=$("<td>").text(actor[1]);
const profile=$("<td>").append($("<img>").attr({
"src":"<%=request.getContextPath()%>/images/"+actor[2],
"width":100,
"height":100
}));
tr.append(name).append(phone).append(profile);
table.append(tr);
});
$("#csvcontainer").html(table);
}
})
})
</script>
package com.ajax.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ajax.model.vo.Actor;
@WebServlet("/ajax/csvdata.do")
public class CsvDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CsvDataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Actor> actors=List.of(Actor.builder().name("박보검").phone("01043259874")
.profile("parkBogum.jpg").build(),
Actor.builder().name("쥴리아로버츠").phone("01023486637")
.profile("juliaRoberts.jpg").build(),
Actor.builder().name("멧데이먼").phone("01012331432")
.profile("mattDamon.jpg").build()
);
String csv="";
for(int i=0; i<actors.size(); i++) {
if(i!=0)csv+="\n";
csv+=actors.get(i);
}
System.out.println(csv);
response.setContentType("text/csv;charset=utf-8");
response.getWriter().print(csv);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.ajax.model.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Actor {
private String name;
private String phone;
private String profile;
@Override
public String toString() {
return name+","+phone+","+profile;
}
}
- 실행 결과