【Demo】一個用Servlet實現的Web專案
阿新 • • 發佈:2019-01-08
簡介
一個Web專案包括前端和後端,前端是用來顯示介面的,和使用者互動,後端是用來處理一系列邏輯的。基本的業務流程用一張圖表示:
環境配置
1.jdk,jre(如果沒有配置,那就去百度教程吧!)
2.apache-tomcat:
在解壓後的檔案中找到webapps-->新建資料夾test_servlet-->新建資料夾WEB-INF-->新建兩個資料夾(classes,lib),從conf中拷貝一個web.xml(其中的編碼將在程式碼實現中體現)
程式碼實現
1.login.html
<html>
<head>
<title>登入</title>
</head>
<body>
<form action="http://127.0.0.1:8080/test_servlet/loginServlet">
使用者名稱:<input type="text" name="username"></br>
密碼:<input type="password" name="password"></br>
<input type="submit" value="登入">
</form>
</body>
</html>
2.LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException{
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username="+username);
System.out.println("password="+password);
resp.setContentType("text/html;charset=GB18030");
// resp.getWriter().println("Login Success!!!");
resp.getWriter().println("登入成功!!!");
}
}
3.上述拷貝的web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.5">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
呼叫流程
總結