1.File dataAction.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String firstName = request.getParameter("fname");
String lastName = request.getParameter("lname");
String idCard = request.getParameter("idcard");
String date = request.getParameter("date");
System.out.println("firstName : " + firstName);
System.out.println("lastName : " + lastName);
System.out.println("idCard : " + idCard);
System.out.println("date : " + date);
System.out.println("############################################");
%>
2.Class HtmlSubmitServlet.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class HtmlSubmitServlet {
// the hard-coded URL to the Service I want to invoke (should be injected of
// course)
private static final String BASE_URL = "http://localhost:8080/TestWEB/dataAction.jsp";
public static void main(String[] args) {
HtmlSubmitServlet h = new HtmlSubmitServlet();
String firstName = "Tester";
String lastName = "java";
String idCard = "123456678";
String date = "12/10/1985";
h.submitData(firstName, lastName, idCard, date);
}
public void submitData(String firstName, String lastName, String idCard, String date) {
try {
URL url = new URL(BASE_URL);
URLConnection con = url.openConnection();
// inform the connection that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
// Don't use a cached version of URL connection.
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// define a new PrintWriter on the output stream
PrintWriter outWriter = new PrintWriter(con.getOutputStream());
// send data to the servlet
outWriter.print("fname=" + firstName);
outWriter.print("&lanme=" + lastName);
outWriter.print("&idcard=" + idCard);
outWriter.print("&date=" + date);
outWriter.close();
InputStream input = con.getInputStream();
File outputFile = new File("z.txt");
FileOutputStream out = new FileOutputStream(outputFile);
boolean eof = false;
// read all bytes from the input and write them to the output
while (!eof) {
int byteValue = input.read(); // read the stream
out.write(byteValue);
if (byteValue == -1)
eof = true;
}
out.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
ขั้นตอนการทำงาน ให้ทำการ run file jsp ทิ้งไว้ จากนั้นให้มารัน .java เราจะเห็น output ที่ console
ผลลัพธ์ที่ได้…
firstName : Tester
lastName : java
idCard : 123456678
date : 12/10/1985
############################################