How to servlet get data from page JSP.

Hôm nay mình hướng dẩn các bạn một số bài tập Servlet vs JSP.

Bài tập hôm nay đơn giản hướng dẩn chúng ta cách lấy data từ trang JSP và xử lí chúng như thế nào. Qua bài tập cơ bản + – * / với 2 số.

Thiết lập trang calculator.jsp như sau :

d1

 


<body>
 <form action="CalculationServlet">
 <table border="1">
 <tr>
 <td>Input A : </td>
 <td><input type="text" name="txtA"/></td>
 </tr>
 <tr>
 <td>Input B : </td>
 <td><input type="text" name="txtB"/></td>
 </tr>
 <tr>
 <td colspan="2" align="right">
 <button type="submit" name="cal" value="+"> + </button>
 <button type="submit" name="cal" value="-"> - </button>
 <button type="submit" name="cal" value="*"> * </button>
 <button type="submit" name="cal" value="/"> / </button>
 </td>
 </tr>
 </table>
 </form>
</body>

 

OK….giờ chúng ta khi nhập 2 số a vs b sau đó chúng ta nhấn phép tính . Thì sẻ hiển thi kết quả lên :

chúng ta tạo trang servlet CalculationServlet.java và thiết lập trong method doget như sau :


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 PrintWriter out = response.getWriter();
 Double a = Double.parseDouble(request.getParameter("txtA").toString());
 Double b = Double.parseDouble(request.getParameter("txtB").toString());
 String cal = request.getParameter("cal").toString();
 switch (cal) {
 case "+": out.println("Result : "+(a+b)+"");break;
 case "-": out.println("Result : "+(a-b)+"");break;
 case "*": out.println("Result : "+(a*b)+"");break;
 case "/": out.println("Result : "+(a/b)+"");break;
 }
 }

Ok….khá là đơn giản và kết quả của chúng ta khi nhập 2 số và nhấn phép tình sẻ có kết quả như sau :

d1

 

o k chúc các bạn thành công .

Lưu Trữ Danh Sách Giá Trị (HttpSession)

Bài này trình bày đơn giản cách chúng ta lưu trữ các giá trị trong một Collection . Thao tác với đối tượng HttpsSession .

Cấu trúc của project đơn giản chỉ gồm 1 trang Shopping.jsp và 1 Servlet ShowOrder.java

FILE : Shopping.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Shopping</title>
</head>
<body>
 <center>
 <h1>Shopping : </h1>
 <form action="show" method="post">
 Choose : <select name="items">
 <option value="Dress">Dress</option>
 <option value="Skirt">Skirt</option>
 <option value="Hat">Hat</option>
 <option value="Trousers">Trousers</option>
 </select>
 <input type="submit" value="Show Order">
 </form>

 </center>
</body>
</html>
<pre>

ShowOrder.java

package thaihoanghai.wordpress.com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

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 javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ShowOrder
 */
@WebServlet("/show")
public class ShowOrder extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		synchronized (session) {
			@SuppressWarnings("unchecked")
			ArrayList<String> items =
			(ArrayList<String>) session.getAttribute("items");
			if(items == null)
				items = new ArrayList<String>();
			String newItem = request.getParameter("items");
			if(newItem != null && !newItem.trim().equals(""))
				items.add(newItem);
			session.setAttribute("items", items);
			//=======================================
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			String title = "Items Purchased";
			String docType =
					"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
							"Transitional//EN\">\n";
			out.println(docType +
					"<HTML>\n" +
					"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
					"<BODY BGCOLOR=\"#FDF5E6\">\n" +
					"<H1>" + title + "</H1>");
			if(items.size() == 0){
				out.println("<I don't want to buy anything !!!>");
			}else{
				out.println("<UL>");
				for(String obj : items){
					out.println("<LI>" + obj);

				}

			}

			out.println("<br>Do You want to buy ???" + "<a href=\"Shopping.jsp\">Click Here</a>");
			out.println("</BODY></HTML>");

		}
	}

}


Part 2 : Client gửi dữ liệu đến Server / Server Phản Hồi [Servlet]

Hôm nay chúng ta sẻ bước qua một vài thao tác cơ bản cho việc dữ liệu từ những Form của User được gửi đến Server.

Bước 1: Các bạn đả tạo Sẳn 1 Project Servlet mà mình đả giới thiệu ở bài 1.

Bước 2: Tạo 1 file html  có tên là NhanVien.html ( Mình không giải thích nhiều về HTML ở đây các bạn có thể ôn lại HTML tại các trang web http://www.w3schools.com/html/html_intro.asp

Hình ảnh của File NhanVien HTML trên :

Bước 3 : Mình tạo ra một file MyServlets.java trong phương thức doGet ta thực hiện 1 vài phương thức của interface HttpServletRequest và Http SerletReponse các bạn có thể đọc thêm nhưng phương thức của 2 interface trên tại  docs.Oracle

Mình củng đả chú thích khá rỏ ràng trong bài.

Bước 4: Ta điều chỉnh là để Build hàm main thực thi. Ta Chỉnh sửa 1 tý trong file web.xml như sau

Bước 5 : Run ……………………

Xong thế là Server có thể lấy được dữ liệu từ các form mùh web client thao tác.

=====================================================

Tiếp theo là phản hồi của Server.

Tạo 1 Servlet ResponseToClient.java trong doGet ta thực hiện. Mở luồn đọc và gửi đi , đóng luồng lại.

Build lại và chạy.

Xong ^^! cùng nhau thưởng thức 1 tí =]] =]]

Part1: Các Bước Tạo Servlets.

Để bắt đầu tạo 1 servlets project ta sẻ thực hiện các bước sau !!!

Bước 1 : File – > New Project

Next -> Đặt tên cho project.

Next -> Finish .

Giao diện khi ta vừa tạo xong project. Đến giờ ta tạo Servlets.

File -> New File  -> Web -> Servlet

Next tiếp : click Add (web.xml) -> Finish

Tạo xong ta sẻ thực hiện in ra một vài dòng cơ bản !!!

 

Giờ trước khi chạy ta phải sửa lại ben file web.xml lại

 

Build lại main và run :

Xong các bạn cùng nhau thử yh ház….^^!