wiki:waue/2010/0608

Version 5 (modified by waue, 14 years ago) (diff)

--

jsp + servlet + javabean
教材1

一. 下載資源

1.A 用 virtualbox 虛擬機器

1.B 自行下載資源

  1. 下載 pdf 手冊
  1. 下載tomcat 6.5
  1. 下載 eclipse 3.5 linux版

二. 實做簡單的 servlet 範例

已將tomcat 安裝於 /opt/tomcat/ 目錄下

2.1 建立目錄

cd /opt/tomcat/webapps/
mkdir -p /opt/tomcat/webapps/FirstServlet/WEB-INF/classes
mkdir /opt/tomcat/webapps/FirstServlet/WEB-INF/lib

2.2 第一個程式:HelloServlet?.java

cd /opt/tomcat/webapps/FirstServlet/WEB-INF/classes
gedit HelloServlet.java
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 HelloServlet extends HttpServlet {                  
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
                      throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");             
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");   
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hello Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1> Hello! " + name + " !</h1>");
    out.println("</body>");                                       
    out.println("</html>");
    out.close();
  }
}

2.2 編譯:HelloServlet?.java檔

cd /opt/tomcat/webapps/FirstServlet/WEB-INF/classes
javac -classpath /opt/tomcat/lib/servlet-api.jar ./HelloServlet.java 

2.3 製作佈署描述檔:web.xml

cd /opt/tomcat/webapps/FirstServlet/WEB-INF/
gedit web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello.do</url-pattern>
    </servlet-mapping>
</web-app>

2.4 啟動web容器:tomcat

cd /opt/tomcat
bin/startup.sh

2.5 用瀏覽器測試

http://localhost:8080/FirstServlet/hello.do?name=caterpillar

ps: ?name=caterpillar 可以改成你的名子來測試是否成功