1. 程式人生 > >Servlet+JSP例子

Servlet+JSP例子

scrip com index.jsp 1.0 開發 ima stat let blog

前面兩節已經學習了什麽是Servlet,Servlet接口函數是哪些、怎麽運行、Servlet生命周期是什麽? 以及Servlet中的模式匹配URL,web.xml配置和HttpServlet。怎麽在Eclipse中新建一個Servlet工程項目。 今天這裏主要是創建一個Servlet+JSP的例子。

一、學習之前補充一下web.xml中配置問題

web.xml中<welcome-file-list>配置((web歡迎頁、首頁))

用於當用戶在url中輸入工程名稱或者輸入web容器url(如http://localhost:8080/)時直接跳轉的頁面.

welcome-file-list的工作原理是,按照welcome-file的.list一個一個去檢查是否web目錄下面存在這個文件如果存在,繼續下面的工作(或者跳轉到index.html頁面,或者配置有struts

的,會直接struts的過濾工作).如上例,先去webcontent(這裏是Eclipse的工程目錄根目錄)下是否真的存在index.html這個文件,如果不存在去找是否存在index.jsp這個文件,以此類推

還要說的是welcome-file不一定是html或者jsp等文件,也可以是直接訪問一個action。就像我上面配置的一樣,但要註意的是,一定要在webcontent下面建立一個index.action的空文件,然後使用struts配置去跳轉,不然web找不到index.action這個文件,會報404錯誤,

如果配置了servlet的url-pattern是/*,那麽訪問localhost:8080/會匹配到該servlet上,而不是匹配welcome-file-list;如果url-pattern是/(該servlet即為默認servlet),如果其他匹配模式都沒有匹配到,則會匹配welcome-file-list。

例如:

技術分享圖片

FirstServlet.java

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse; 11 //@WebServlet("/Firstservlet") 12 public class FirstServlet extends HttpServlet { 13 14 /* (non-Javadoc) 15 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 16 */ 17 @Override 18 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 19 System.out.println("處理get()的請求。。。"); 20 PrintWriter pw = resp.getWriter(); 21 pw.write("hello!"); 22 } 23 24 /* (non-Javadoc) 25 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 26 */ 27 @Override 28 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 29 30 } 31 }

web.xml 配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>ServletTest</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <servlet><servlet-name>ServletTest</servlet-name>
13   <servlet-class>servlet.FirstServlet</servlet-class>
14   </servlet>
15   <servlet-mapping>
16       <servlet-name>ServletTest</servlet-name>
17       <url-pattern>/*</url-pattern>
18   </servlet-mapping>
19 </web-app>

index.jsp

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <a href = "/ServletTest/FirstServlet">get this first servlet</a>
11 </body>
12 </html>

如果在上面web.xml裏面配置<url-pattern>/*</url-pattern>, 在瀏覽器輸入:直接匹配到Servlet

技術分享圖片

如果在上面web.xml裏面配置<url-pattern>/</url-pattern>, 在瀏覽器輸入:可以看出匹配到index.jsp

技術分享圖片

正常在web.xml裏面配置<url-pattern>/FirstServlet</url-pattern>,會先匹配到index.jsp

技術分享圖片

二、Servlet+JSP

直接加例子:

技術分享圖片

 1 package com.ht.servlet;
 2 
 3 public class AccountBean {
 4     private String username;
 5     private String password;
 6     /**
 7      * @return the username
 8      */
 9     public String getUsername() {
10         return username;
11     }
12     /**
13      * @param username the username to set
14      */
15     public void setUsername(String username) {
16         this.username = username;
17     }
18     /**
19      * @return the password
20      */
21     public String getPassword() {
22         return password;
23     }
24     /**
25      * @param password the password to set
26      */
27     public void setPassword(String password) {
28         this.password = password;
29     }
30 }
31 
32 package com.ht.servlet;
33 
34 import java.io.IOException;
35 
36 import javax.servlet.ServletException;
37 import javax.servlet.annotation.WebServlet;
38 import javax.servlet.http.HttpServlet;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import javax.servlet.http.HttpSession;
42 
43 /**
44  * Servlet implementation class AccountBean
45  */
46 @WebServlet("/CheckAccount")
47 public class CheckAccount extends HttpServlet {
48     private static final long serialVersionUID = 1L;
49        
50     /**
51      * @see HttpServlet#HttpServlet()
52      */
53     public CheckAccount() {
54         super();
55         // TODO Auto-generated constructor stub
56     }
57 
58     /**
59      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
60      */
61     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
62         HttpSession sessionzxl = request.getSession();
63         AccountBean account = new AccountBean();
64         String username = request.getParameter("username");
65         String pwd = request.getParameter("pwd");
66         account.setPassword(pwd);
67         account.setUsername(username);
68         System.out.println("username :"+ username + " password :" + pwd);
69         if((username != null)&&(username.trim().equals("jspp"))) {
70             System.out.println("username is right!");
71                if((pwd != null)&&(pwd.trim().equals("1"))) {
72                    System.out.println("success");
73                    sessionzxl.setAttribute("account", account);
74                    String login_suc = "success.jsp";
75                    response.sendRedirect(login_suc);
76                    return;
77                }
78         }
79         System.out.println("fail!");
80         String login_fail = "fail.jsp";
81         response.sendRedirect(login_fail);
82         return;        
83     }
84 
85     /**
86      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
87      */
88     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
89         
90         doGet(request, response);
91     }
92 
93 }

登錄的jsp頁面如下Login.jsp

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <%
 5 String path = request.getContextPath();
 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 7 %>
 8 
 9 <html>
10 <head>
11 <base href="<%=basePath%>">
12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
13 <title>My JSP ‘login.jsp‘ starting page</title>
14 </head>
15 <body>
16     This is my JSP page. <br>
17     <form action="login">
18     username:<input type="text" name="username"><br>
19     password:<input type="password" name="pwd"><br>
20     <input type="submit" value="Submit">
21     </form>
22 </body>
23 </html>

登錄成功界面如下success.jsp:

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <%@ page import="com.ht.servlet.AccountBean"%>
 5 
 6 <%
 7 String path = request.getContextPath();
 8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 9 %>
10 
11 <html>
12 <head>
13 <base href="<%=basePath%>">
14 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
15 <title>My JSP ‘success.jsp‘ starting page</title>
16 </head>
17 <body>
18 <%AccountBean account = (AccountBean)session.getAttribute("account");%>
19 username:<%= account.getUsername()%> <br>
20 password:<%= account.getPassword() %> <br>
21 basePath: <%=basePath%><br>
22 path:<%=path%><br>
23 </body>
24 </html>

登錄失敗的jsp頁面如下:fail.jsp

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <%
 5 String path = request.getContextPath();
 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 7 %>
 8 
 9 <html>
10 <head>
11 <base href="<%=basePath%>">
12 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
13 <title>My JSP ‘fail.jsp‘ starting page</title>
14 </head>
15 <body>
16     Login Failed! <br>
17     basePath: <%=basePath%><br>
18     path:<%=path%><br>
19 </body>
20 </html>

web.xml配置如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>ServletTest</display-name>
 4   <welcome-file-list>
 5     <welcome-file>Login.jsp</welcome-file>
 6   </welcome-file-list>
 7   
 8   <servlet>
 9        <description>This is the description of my J2EE component</description>
10        <display-name>This is the display name of my J2EE component</display-name>
11     <servlet-name>CheckAccount</servlet-name>
12     <servlet-class>com.ht.servlet.CheckAccount</servlet-class>
13   </servlet>
14   <servlet-mapping>
15     <servlet-name>CheckAccount</servlet-name>
16     <url-pattern>/login</url-pattern>
17   </servlet-mapping>
18 </web-app>

描述一下上面運行過程:

在瀏覽器輸入:http://localhost:8080/ServletTest/ 會通過歡迎頁面welcome-file-list找到登錄頁面Login.jsp, 界面顯示如下:

技術分享圖片

在登錄頁面輸入用戶名和密碼,點擊登錄,找到對應的action, 會去運行/login其對應的servlet, 找到doGet()方法,判斷用戶名和密碼

如果用戶名密碼不是jspp和1,就會跳轉到失敗頁面fail.jsp

技術分享圖片

如果用戶名等於jspp和1,則跳轉到成功頁面success.jsp

技術分享圖片

Session

上面就是一個最簡單的JSP和servlet例子。在運行上面例子中,有一個概念session.

在checkAccount.java中,直接通過request獲取session

HttpSession sessionzxl = request.getSession();

後面將定義的變量存儲到session中:sessionzxl.setAttribute("account", account);

在jsp中怎麽獲取session?

在success.jsp中,有這麽一行<%AccountBean account = (AccountBean)session.getAttribute("account");%>,那麽session來至於哪兒?

查看資料後得知,session是jsp隱式對象

JSP隱式對象是JSP容器為每個頁面提供的Java對象,開發者可以直接使用它們而不用顯式聲明。JSP隱式對象也被稱為預定義變量。

JSP所支持的九大隱式對象:

對象描述
request HttpServletRequest 接口的實例
response HttpServletResponse 接口的實例
out JspWriter類的實例,用於把結果輸出至網頁上
session HttpSession類的實例
application ServletContext類的實例,與應用上下文有關
config ServletConfig類的實例
pageContext PageContext類的實例,提供對JSP頁面所有對象以及命名空間的訪問
page 類似於Java類中的this關鍵字
Exception Exception類的對象,代表發生錯誤的JSP頁面中對應的異常對象
    session是jsp的內置對象,所以你可以直接寫在jsp的  
    <%  
    session.setAttribute("a",  b);  //把b放到session裏,命名為a,  
    String M = session.getAttribute(“a”).toString(); //從session裏把a拿出來,並賦值給M  
    %> 


下節添加一個Servlet+jsp+SQL例子。

https://blog.csdn.net/superit401/article/details/51974409

Servlet+JSP例子