Lee87
Tổng số bài gửi : 71 Points : 107 Reputation : 5 Join date : 10/07/2009 Age : 37 Đến từ : Hà Nội
| Tiêu đề: Chapter 2 Example 14/8/2009, 4:20 pm | |
| Các bạn vô đây tham khảo nhé: FirstLastName.java - Code:
-
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class FirstLastName extends HttpServlet { private static final String FULL_NAME_PARAM = "fullName"; private static final char SPACE = ' '; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); // lay full name tu phia client int index; String fullName = request.getParameter(FULL_NAME_PARAM); System.out.println(" -------------- " + fullName);
if ( fullName == null || fullName.trim().length() == 0 ) { out.println("Ten nhap vao ko hop le"); } else if ( (index = fullName.indexOf(SPACE)) < 0) { out.println("Ten chi co mot tu la: " + fullName.trim() ); } else { String firstName = fullName.substring( 0, index ).trim(); String lastName = fullName.substring( index ).trim(); out.println("First name: [b]" + firstName + "[/b] "); out.println("Last name: [b]" + lastName + "[/b]"); } // end else
out.println(""); out.println(""); } finally { out.close(); } }
// @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }// }
index.html - Code:
-
[center] Hello [/center]
Nhap ten tu nguoi su dung. In ra First Name va Last Name.
Cach lam: [list=1] [*]Tao trang HTML de nhap file: su dung the FORM, INPUT de tao form nhap [*]Phia server. Su dung request.getParamter(String) de lay duoc tham so [*]Su dung StringTokenizer de tach String hoac dung String.indexOf(" ") [/list]
Nhap ten:
Chúc các bạn học tốt. :lol!: | |
|