第2,8章 servlet 開發技術(12課時)

weixin_34402408發表於2018-11-08

第2章 servlet開發技術

Servlet是什麼

servlet是基於java語言的web伺服器端程式設計技術。按照一定規則定義的java類。他有約定好的一些方法。get post init destroy

servlet作用

無論是get/post方法都至少有兩個引數,一個叫HttpServletRequest(請求物件),一個叫HttpServletResponse(響應物件)
他對外暴露一個地址,可以用於頁面訪問的。

servlet如何建立和定義

第一種方式:servlet2.5以前是手動建立

1)寫一個servlet類(java)繼承HttpServlet

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }

}

2)web.xml裡配置對外暴露的地址。
web.xml在WebContent\WEB-INF\web.xml

 <servlet>
 <servlet-name>TestServlet</servlet-name>
 <servlet-class>com.neuedu.javaweb.chap02.TestServlet</servlet-class>
  </servlet>
 <servlet-mapping>
 <servlet-name>TestServlet</servlet-name>
 <url-pattern>/test.do</url-pattern>
 </servlet-mapping>

servlet3.0自動建立

包名-new -servlet-輸入servlet檔名稱-下一步-urlmapping裡可以更改對映地址-finish

@WebServlet("/regServlet")
public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doGet被呼叫");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

servlet生命週期關鍵方法

init()初始化方法
service()服務方法
doGet()
doPost()
......根據method不同,service將請求分發到不同方法
destory()銷燬方法

注意:init()和destory()方法整個生命週期中只執行一次。service等方法可以執行多次

初始化帶引數以及init裡獲取引數

@WebServlet(value="/regServlet",initParams={@WebInitParam(name="driver",value="com.mysql.jdbc.Driver"),
        @WebInitParam(name="userName",value="root"),
        @WebInitParam(name="passWord",value="root")}
)
public class RegServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}

    

    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println(config.getInitParameter("userName"));
        super.init(config);
    }



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("doGet被呼叫");
    //response.getWriter().append("Served at: ").append(request.getContextPath());
    PrintWriter out=response.getWriter();
    out.println("success");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

註冊程式

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>註冊頁面</title>
</head>
<body>
註冊頁面<br>
<form action="regServlet" method="post">
賬號:<input type="text" name="username"/><br>
密碼:<input type="password" name="password"/><br>
愛好:<input type="checkbox" name="hobby" value="1">打籃球
<input type="checkbox" name="hobby" value="2">踢足球
<input type="checkbox" name="hobby" value="3">燙頭
<input type="submit" value="註冊"/>
</form>
</body>
</html>

servlet

package com.neuedu.javaweb.chap02;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegServlet
 */
@WebServlet(value="/regServlet",initParams={@WebInitParam(name="driver",value="com.mysql.jdbc.Driver"),
        @WebInitParam(name="userName",value="root"),
        @WebInitParam(name="passWord",value="root")}
)
public class RegTestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
/**
 * @see HttpServlet#HttpServlet()
 */
public RegTestServlet() {
super();
// TODO Auto-generated constructor stub
}

    

    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println(config.getInitParameter("userName"));
        super.init(config);
    }



    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost方法被呼叫");
        //獲取前臺輸入的資訊
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        //checkbox資料
    String[] hobbys=request.getParameterValues("hobby");
    System.out.println(name);
        System.out.println(password);
        System.out.println(hobbys);
        //doGet(request, response);
    }
}

解決中文亂碼問題

request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");

request裡能獲取什麼

應用程式上下文 request.getContextPath()
客戶端ip request.getRemoteAddr()
客戶端埠 request.getRemotePort()
本地地址 request.getLocalAddr()
相對路徑 request.getRequestURI()
請求方式 request.getMethod()
頭資訊(瞭解,是列舉型別)
request.getHeaderNames()

    //上下文路徑
    System.out.println("應用程式上下文"+request.getContextPath());
    System.out.println("客戶端ip"+request.getRemoteAddr());
    System.out.println("埠"+request.getRemotePort());
    System.out.println("本地addr"+request.getLocalAddr());
    System.out.println("相對路徑"+request.getRequestURI());
    System.out.println("請求方式"+request.getMethod());
    //以下了解
    System.out.println(request.getHeaderNames());
    Enumeration<String> headers=request.getHeaderNames();
    while(headers.hasMoreElements()){
        String key=headers.nextElement();
        String value=request.getHeader(key);
        System.out.println("key--->"+key);
        System.out.println("value--->"+value);
        
    }

列印結果:

應用程式上下文/myproject
客戶端ip0:0:0:0:0:0:0:1
埠51784
本地addr0:0:0:0:0:0:0:1
相對路徑/myproject/loginServlet
請求方式POST
org.apache.tomcat.util.http.NamesEnumerator@3c32a826
key---->host
value-->localhost:8081
key---->connection
value-->keep-alive
key---->content-length
value-->31
key---->cache-control
value-->max-age=0
key---->origin
value-->http://localhost:8081
key---->upgrade-insecure-requests
value-->1
key---->content-type
value-->application/x-www-form-urlencoded
key---->user-agent
value-->Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.16 Safari/537.36
key---->accept
value-->text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
key---->referer
value-->http://localhost:8081/myproject/login.html
key---->accept-encoding
value-->gzip, deflate, br
key---->accept-language
value-->zh-CN,zh;q=0.9
key---->cookie
value-->Webstorm-a327319a=cc9d0535-8c62-45c6-91d2-ba803bc9a72d

轉發和重定向

轉發:只發一次請求 位址列的地址不變 只能轉發到內部地址 效率高 request轉發 request可以帶引數
重定向:兩次請求 位址列地址會變化 可以請求外部地址 效率低 responset重定向 只能在url地址裡帶引數(如果重定向到的頁是用html的IFRAME開發的,只能用redirect)
應用技巧:
如果請求外部地址或者跳轉時不需要攜帶原始請求用重定向。否則用轉發
重定向時加上上下文路徑

response.sendRedirect(request.getContextPath()+"/user/index.html");

轉發寫法

request.getRequestDispatcher("/login.html").forward(request, response);

程式碼詳見第2章程式碼樣例(註冊登入)

相關文章