1. 程式人生 > >史上最簡單的servlet專案例項

史上最簡單的servlet專案例項

在網上找了很久的java+jsp專案例項,介紹的都大同小異,然而沒有一個自己真正執行成功的專案。幾經周折,終於整理出了自己認為最簡單的一個servlet例項。

首先新建一個web專案,這個網上有很多教程,我就不在這裡囉嗦了,直接上程式碼。

-------------------------------------------------------------------------------------------------------------------------------------------------------

index.jsp頁面程式碼:
<html>
<head>
<%@ page contentType="text/html;charset=UTF-8"%>
<title>QIMITY</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login">
<input type="text" name="user"/>
<input type="text" name="password"/>
<input type="submit" value="登入"/>
</form>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------------------------
Login.java類程式碼:
package com;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Login extends HttpServlet{


private static final long serialVersionUID = 356393290108927194L;

public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
         System.out.println("OK!");
    } 
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
web.xml配置檔案資訊:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
  <servlet-name>entry</servlet-name>
  <servlet-class>com.Login</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>entry</servlet-name>
  <url-pattern>/login</url-pattern>
 </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
----------------------------------------------------------------------------------------------------------------------------------------------------------
三個檔案都建立好了之後執行tomcat,在登入頁面點選登入按鈕,如果在eclipse的後臺輸出了"OK!"則說明專案執行成功!