[Java] 網頁前端傳資料給後端,透過Ajax

筆記一下前端傳值給後端的寫法


前端.html

<body>
<script type="text/javascript">
    $.ajax({
    	url:"./autocomplete",
    	dataType: "json",
    	type: "POST",
    	async: false,
    	timeout: 5000,
    	data: {
    		standardQ: "ABC"    //傳給API的參數
    	},
    	success: function(data){
    		//成功的話,執行此區塊
                alert("success");
    	},
    })
</script>
</body>


後端.java

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AutoCompleteServlet")
public class AutoCompleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public AutoCompleteServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");		//設定request編碼
		response.setCharacterEncoding("UTF-8");		//設定response編碼
		
		String apiPath = "https://xxx.jsp";	//API之URL
		//API的參數,依API的條件而定
		//此為抓取前端的"ABC"參數
		//如果參數為中文字,請參考:https://yijay131724.blogspot.com/2020/07/java-400.html
		String standardQ = request.getParameter("standardQ");
		//API的參數,依API的條件而定
		String rows = "10";
		//String urlString = "https://xxx.jsp?standardQ=我&rows=10";
		String urlString = apiPath + "?standardQ=" + standardQ + "&rows=" + rows;

		try {
			URL url = new URL(urlString);	//把urlString轉為httpURLConnection使用的URL型態
			System.out.println(url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();	//開啟連線
			conn.setConnectTimeout(5000);	//設定5秒後愈時
			conn.setRequestMethod("GET");	//使用GET方法請求API
			conn.connect();					//連線
			int responseCode = conn.getResponseCode();	//存放連線後的HTTP狀態碼

			if (responseCode == 200) {		//200為連線成功,並執行自己的需求
				PrintWriter writer = response.getWriter();
				writer.print(standardQ);	//網頁畫面顯示standarQ參數
				writer.close();
				conn.disconnect();

			}else
				System.err.println("Robot responseCode: " + responseCode);
			
		} catch (IOException e) {
			e.printStackTrace();

		} 
	}
}


web.xml

<servlet>
    <servlet-name>AutoComplete</servlet-name>
    <servlet-class>idv.ycc.servlet.AutoCompleteServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AutoComplete</servlet-name>
    <url-pattern>/autocomplete</url-pattern>
  </servlet-mapping>


留言

這個網誌中的熱門文章

[面試] 日月光 設備工程師

[日文] Google日文輸入法 簡單安裝說明

[Windows] 還我 win7 相片檢視器!!