一個拚積木呀....
環境 Tomcat 7.0+ Eclipse Luna 2
(原本享用Tomcat 8.0+Eclipse MARS,不過CentOS還沒研究怎麼裝Tomcat 8.0)
小習題
Input : name
Output : Hello world +name
實作過程,透過 Servlets and JSP
利用HTML表單POST(GET)傳遞參數給JAVA,JAVA再遞給JSP呈現。
當然,也能用兩個JSP檔案間互傳解決這問題,不過沒甚麼意義就是了。
使用與研究的函數
doPost
doGet
setAttribute
req.getParameter
req.setAttribute("user", user)
req.getRequestDispatcher("hello.jsp").forward(req, resp)
//Hello.java 以下為Hello.java的程式碼
package hellotest;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns={"/Hello"}) //接收html action="Hello"
public class Hello extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String user = req.getParameter("user"); // 取得請求參數
req.setAttribute("user", user); // 設定請求屬性
req.getRequestDispatcher("hello.jsp").forward(req, resp); // 轉發至 JSP
}
}
//hello.jsp
<%@ 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">
<title>${user}</title>
</head>
<body>
<body>
<h1>Hello World, ${user}</h1>
</body>
</body>
</html>
</body>
</html>
//input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="BIG5">
<title>Insert title here</title>
</head>
<body>
<form action="Hello" method="post">
<input type="text" name="user" maxlength="15" size="15"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
沒有留言:
張貼留言