環境
Eclipse Java EE(4.4.1)
JRE 1.8.0_25
Tomcat 6.0
1.File-->New-->Dynamec Web Project
2.建立一個testServlet專案
3.在testServlet底下的WebContem按右鍵New-->Other-->Web-->JSP File
4.建立名為testFile.jsp的jsp file
5.我們可由meta這邊修改編碼,或新增其他資訊。請參考html meta介紹
6.告訴網頁哪裡有定義好的jquery
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
7.實作一個簡單的範例,在頁面上按下Button後用GET方式丟給Servlet,回傳HELLO。Ajax用法 : JQuery中Ajax參數用法
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td height="16" width="7%">input</td>
<td width="60%"><input name="input" type="text" id="input"/></td>
</tr>
</table>
<input type="button" id="sendout" value="submit"style="font-size: 10pt; width: 50px; height: 25px;">
</br></br>
<td height="16" ><label id="output" /></td>
<script type="text/javascript">
$("#sendout").click(function() {
$("#input").val();
alert("true : "+$("#input").val());
$.ajax({
type :"GET",
url : "/testServlet/myServlet",
data : {
datafromtestFile : $("#input").val(),
},
dataType: "text",
success : function(happy) {
$("#output").html(happy);
}
})
});
</script>
</body>
</html>
8.實作頁面
9.建立Server 點選下方Servers-->New-->Server
10.選擇Tomcat 6.0,並新增Server's host name
11. 建立Servlet 在Servers處右鍵New-->Server
10.選擇對應的Tomcat,這邊Tomcat6.0,及Server's host name
11.在testServlet底下的WebContem按右鍵New-->Servlet
12.建立Class name為myServlet
13.建立完成後自動產生
14.因為我們請求方式是GET,所以在doGet底下給一個String送回給testFile.jsp
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF8");
response.setCharacterEncoding("UTF8");
System.out.println(request.getParameter("datafromtestFile"));
String happyString="Hello";
PrintWriter out = response.getWriter();
out.print(happyString);
out.flush();
out.close();
}
15.實作頁面,按下submit顯示Hello
完畢。
文章標籤
全站熱搜

感謝 非常好懂好閱讀的範例