jquery_ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){//웹페이지가 로딩되면 자동 실행
$("button").click(function(){
//id가 target인 태그에 test.txt 파일 내용 출력
//alert("1");
//비동기식 호출
$("#target").load("test.txt");
//alert("2");
//id가 p1 인 태그의 innerHTML 영역 내용 변경
$("#p1").html("문단 영역...");
//alert("3");
});
});
</script>
<style type="text/css">
#target{
width:300px;
height:500px;
border:1px solid black;
overflow:scroll;
}
</style>
</head>
<body>
<p id="p1"></p>
<div id="target"></div>
<button>확인</button>
</body>
</html>
test.txt
<!DOCTYPE html> |
출력 =>
ajax1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){//웹페이지가 로딩되면 자동 호출
$("#button1").click(function(){
//id가 dan 인 태그에 입력된값
var dan=$("#dan").val();
var name =$("#name").val();
//비동기식 호출 함수
//type: get/post, url: 요청주소, data:파라미터
//success:call back 함수 (처리가 완료되었을 때 실행함)
$.ajax({
type:"post",
url:"result1.jsp",
data:"dan="+dan+"&name="+name,
success:function(value){
//id가 result 인 태그의 내용 변경
$("#result").html(value);
}
});
});
});
</script>
</head>
<body>
<h2>동기식 (single thread)</h2>
<form action="result1.jsp">
단을 입력하세요
<input name="dan">
<input type="submit" value="전송">
</form>
<hr style="border:2px red solid" >
<h2>비동기식(multi thread)</h2>
<p></p>
단 입력 : <input id="dan"> <p>
이름 입력 : <input id="name" >
<input type="button" id="button1" value="확인">
<div id="result">결과 출력 영역</div>
</body>
</html>
result1.jsp
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<%
//request.getParameter("태그의 name")
request.setCharacterEncoding("utf-8");
int dan =Integer.parseInt(request.getParameter("dan"));
String name =request.getParameter("name");
out.print("<h2> "+dan + " 단</h2>");
out.print("<h3>작성자 :" + name +"</h3>");
for(int i=1; i<=9; i++){
out.print( dan + "*" + i + " = " + (dan*i) +"<br/>");
}
%>
</body>
</html>
출력 >
DB 와 연동
sever.xml
<Context docBase="web02_javascript" path="/web02_javascript"
reloadable="true" source="org.eclipse.jst.jee.server:web02_javascript" >
<Resource name="mysqlDB"
auth="Container"
type="javax.sql.DataSource"
maxTotal="100"
maxIdle="30"
maxWaitMillis="10000"
username="java"
password="1111"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3305/java?characterEncoding=utf8"/>
</Context>
SQL
CREATE TABLE member
(
userid varchar(50),
passwd varchar(50),
name varchar(50)
)
alter table member change `pwd` `passwd` varchar(50);
insert into member (userid, passwd, name)
VALUES ('kim', '1111', '홍길동');
create table keywords(
keyword varchar(50)
);
insert into keywords values( "java1");
insert into keywords values( "jav111");
insert into keywords values( "java34");
insert into keywords values( "jspp");
insert into keywords values( "javefe");
insert into keywords values( "javsc");
insert into keywords values( "javar31");
insert into keywords values( "javases1");
insert into keywords values( "java1");
insert into keywords values( "자바");
insert into keywords values( "자바북스");
insert into keywords values( "자바라");
insert into keywords values( "자바라스");
select * from keywords;
class DB
package common;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DB {
public static Connection getConn(){
DataSource ds=null; //javax.sql.DataSource
Connection conn=null;
try {
//context.xml 파일을 분석하는 객체
Context context = new InitialContext();
// context.xml 파일의 Resource 태그의 name 속성 검색
// java:comp/env/리소스태그의name
ds=(DataSource)context.lookup("java:comp/env/mysqlDB");
// 커넥션풀에서 커넥션을 리턴받음
conn=ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
System.out.println(DB.getConn());
}
}
KeywordDAO
package keyword;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import common.DB;
public class KeywordDAO {
public List<String> list(String keyword){
List<String> items=new ArrayList<String>();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
conn = DB.getConn();
String sql=
"select * from keywords where keyword like ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "%"+keyword+"%");
rs = pstmt.executeQuery();
while( rs.next() ){
items.add(rs.getString("keyword"));
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if( rs!= null ) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if( pstmt!= null ) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if( conn != null ) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return items;
}
}
class MemberDAO
package member;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import common.DB;
//MVC pattern : Model, View, Controller
//dao : Data Access Object(데이터 접근, 데이터 처리)
public class MemberDAO {
public String login(MemberDTO dto){
String result=null;
Connection conn=null; //DB 접속
PreparedStatement pstmt=null; // SQL실행
ResultSet rs=null; // select 명령어의 결과셋을 레코드 단위로 조회
try {
conn = DB.getConn();
String sql=
"select * from member where userid=? and passwd=?";
/* String sql=
"select * from member "
+ " where userid='"+dto.getUserid()+"' "
+ " and passwd='"+dto.getPasswd()+"'"; */
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getUserid());
pstmt.setString(2, dto.getPasswd());
rs = pstmt.executeQuery();
if( rs.next() ) { //1개의 레코드를 조회함
result= rs.getString("name");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt!=null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
}
class MemberDTO
package member;
public class MemberDTO {
private String userid;
private String passwd;
private String name;
//getter,setter,toString(),생성자
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MemberDTO [userid=" + userid + ", passwd=" + passwd + ", name=" + name + "]";
}
public MemberDTO() {
}
public MemberDTO(String userid, String passwd, String name) {
this.userid = userid;
this.passwd = passwd;
this.name = name;
}
}
ajax2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
//$("#btnLogin").click(function(){
$("#pwd").keyup(function(){// 키입력이 끝나면
id=$("#id").val();
pwd=$("#pwd").val();
param="id="+id+"&pwd="+pwd;
//백그라운드에서 실행
$.ajax({
type:"post",
url:"result2.jsp",
data:param,
success:function(data){
$("#div1").html(data);
}
});
});
});
</script>
</head>
<body>
<h2>일반적이 방식(동기식)</h2>
<form action="result2.jsp" method="post">
아이디 : <input name="id"> <br>
비번 <input type="password" name="pwd"><br>
<input type="submit" value="로그인" >
</form>
<hr style="border:2px red solid" >
<h2>비동기적인 방식</h2>
아이디 <input id="id"><br>
비번 <input type="password" id="pwd"><br>
<input type="button" id="btnLogin" value="로그인" >
<div id="div1"></div>
</body>
</html>
result2.jsp
<%@page import="member.MemberDTO"%>
<%@page import="member.MemberDAO"%>
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<%
//사용자의 입력값
request.setCharacterEncoding("utf-8");
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
MemberDAO dao =new MemberDAO();
MemberDTO dto =new MemberDTO();
dto.setUserid(id);
dto.setPasswd(pwd);
String result=dao.login(dto);
/* if(id.equals("kim")&&pwd.equals("1234")){
out.println("홍길동님 환영합니다.");
}else{
out.println("아이디 또는 비밀번호가 일치하지 않습니다.");
}
*/
if(result!=null){
out.println( result +"님 환영합니다.");
}else{
out.println("아이디 또는 비밀번호가 일치하지 않습니다.");
}
%>
</body>
</html>
ajax3.jsp
<%@ 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">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script type="text/javascript">
$(function(){
$("#search").keyup(function(){//페이지가 로딩되면 자동 호출
search=$("#search").val();//입력값
if(search.length==0){//글자수가 0이면
$("#div1").css("visibility", "hidden");//숨김
}else{
$("#div1").css("visibility", "visible");//표시
//비동기적인 방식으로 호출
$.ajax({
type:"post",
url:"result3.jsp",
data:"keyword="+search,
success:function(data){
//콜백함수(서버의 응답을 처리하는 함수)
$("#div1").html(data);
}
});
}
});
});
</script>
</head>
<body>
키워드를 입력하세요
<input id="search">
<div id="div1"></div> <!-- 키워드 목록이 출력될 부분 -->
</body>
</html>
result3.jsp
<%@page import="java.util.List"%>
<%@page import="keyword.KeywordDAO"%>
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<%
//한글 인코딩 설정
request.setCharacterEncoding("utf-8");
KeywordDAO dao =new KeywordDAO();//dao 객체 생성
//사용자가 입력한 키워드
String keyword=request.getParameter("keyword");
//키워드 목록을 테이블에서 조회
List<String> items=dao.list(keyword);
//화면에 출력
for(String str : items){
out.println(str + "<br>");
}
%>
</body>
</html>
=>출력창
키워드를 입력하세요
java1 |
댓글 ( 4)
댓글 남기기