一個簡單的Java Web專案
阿新 • • 發佈:2019-01-29
一、效果
一個簡單的Java Web例子:
web介面:
登入成功:
登入失敗:
二、過程(jsp+Servlet)
1、建立一個預設的Web Application專案,則預設生成:index.jsp,web.xml等檔案
2、編輯index.jsp程式碼,使用表單實現登入介面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Millet</title>
</head>
<body>
<form action="LoginServlet.action" method="post">
<table>
<tr>
<td>使用者名稱:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密碼:</td>
<td ><input type="password" name="password"></td>
</tr>
<tr>
<td>
<input type="submit" value="登入">
</td>
<td>
<input type="reset" value="取消">
</td>
</tr >
</table>
</form>
</body>
</html>
重點是:action屬性的設定,method請求方法的設定
3、編寫Servlet程式碼
LoginServlet.java程式碼
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String _userName = req.getParameter("username");
String _passWord = req.getParameter("password");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter _printWriter = resp.getWriter();
_printWriter.println("<html><body>");
if ("admin".equals(_userName) && "admin".equals(_passWord)) {
_printWriter.println("登入成功!歡迎您," + _userName);
} else {
_printWriter.println("對不起!您的使用者名稱或者密碼不正確!");
}
_printWriter.println("</body></html>");
}
}
4、在web.xml中配置jsp和servlet關係
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- servlet名稱,與servlet-mapping中的servlet-name必須一致 -->
<servlet-name>LoginServlet</servlet-name>
<!--Servlet類的位置-->
<servlet-class>millet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- servlet名稱,與上面中的servlet-name必須一致 -->
<servlet-name>LoginServlet</servlet-name>
<!-- servlet名稱,與上面中的servlet-name必須一致 -->
<url-pattern>/LoginServlet.action</url-pattern>
</servlet-mapping>
</web-app>
5、注意,在Serlvet3.0新特性註解@WebServlet
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet.action"})
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String _userName = req.getParameter("username");
String _passWord = req.getParameter("password");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter _printWriter = resp.getWriter();
_printWriter.println("<html><body>");
if ("admin".equals(_userName) && "admin".equals(_passWord)) {
_printWriter.println("登入成功!歡迎您," + _userName);
} else {
_printWriter.println("對不起!您的使用者名稱或者密碼不正確!");
}
_printWriter.println("</body></html>");
}
}