顯示具有 Servlet 標籤的文章。 顯示所有文章
顯示具有 Servlet 標籤的文章。 顯示所有文章

2017年3月15日 星期三

調派請求 servlet forward include sendRedirect

Reference
https://openhome.cc/Gossip/ServletJSP/DispatchRequest.html
https://www.javaworld.com.tw/jute/post/view?bid=6&id=50491&sty=1&tpg=1&age=1
https://read01.com/R3dy.html
http://fecbob.pixnet.net/blog/post/43270957-%5Bjsp%5D-servlet%E7%9A%84%E5%B9%BE%E7%A8%AE%E9%A0%81%E9%9D%A2%E8%B7%B3%E8%BD%89%E6%96%B9%E5%BC%8F

Sevlet 請求轉發主要的三種方式

redirect:
1.重定向,包含兩次瀏覽器請求,瀏覽器根據url請求一個新的頁面,所有的業務處理都轉到下一個頁面,url發生改變。
2.可以將頁面跳轉到任何頁面,不一定局限於本『web內部應用中』,如:
response.sendRedirect("HTTP://www.ycul.com");
3.跳轉後瀏覽器網址列變化。
這種方式要傳值出去的話,只能在url中帶parameter或者放在session中,無法使用request.setAttribute來傳遞。
response.sendRedirect("other.view");


forward:
1.轉發,將當前request和response對象保存,交給指定的url處理。並沒有表示頁面的跳轉,所以url不會發生改變。
2.頁面的路徑是相對路徑。forward方式『只能跳轉到本web應用中的頁面上。』
3.跳轉後瀏覽器網址列不會變化。
使用這種方式跳轉,傳值可以使用三種方法:url中帶
白話:就這樣了,我不會再對請求和回應做任何處理了
parameter,session,request.setAttribute
req.getRequestDispatcher("hello.jsp").forward(req, resp);


include
(通常不會在servlet內使用,而是應用在jsp<jsp:include>):

意為包含,將當前request和response對象保存,交給指定的url處理,沒有頁面的跳轉,所以url不會發生改變,但是會將include的Servlet回應包括至目前的回應之中。
例如:
1.servletA 若include→servletB
2.servletB forward→jsp
則jsp會含有servletA『轉向前&轉向後執行的所有資訊』+ servletB『轉向前的資訊』
白話:servletA請servletB幫忙,等他完成請求和回應後,我會再對最後的請求和回應進行處理
RequestDispatcher dispatcher = req.getRequestDispatcher("other.view");
dispatcher.include(req, resp);

小提示
1.如果路徑以斜線("/")開頭,Container會將他視為『從這個Web應用程式的根目錄算起』,如果該路徑不是斜線開頭,就會被視為『相對於原始的請求』,但不能誘騙Container至Web以外的路徑,這是行不通的
總結
1.redirect與include、forward的區別在於是不是同一個Request,redirect會有兩次交互。

2.include與forward的區別在於輸出的內容,include包含本身servlet與跳轉頁面內容的結果,而forward不包含本身servlet的內容。
---------------------------------------------------------------------------------
include 相關補充

Refrence
https://www.javaworld.com.tw/jute/post/view?bid=6&id=50491&sty=1&tpg=1&age=1

在JSP技術中,您可以選擇在
1.編譯時期include一個網頁 <%@include> 
2.執行時期include一個網頁 <jsp:include> 

include一個網頁表示暫時將response的權限交給被include的網頁,在include的網頁執行完畢或送出內容之後,response的權限會再度回到要求include的原網頁。

1.<%@include> 選擇在編譯時期(程式碼compile的時候)include網頁的好處是效能,JSP引擎不用再動態呼叫被include的網頁,被include的網頁被當作要求include的網頁的一部份,您可以使用指令元素include來於編譯時期include網頁
通常用來include『靜態的網頁』
(當進到該網頁的第一次時,沒有帶入任何動態參數時適用)
(但該include網頁中依然可以寫JSTL or EL 的語法,依據某些情況,接收參數)


例如:

2.<jsp:include>來於動態時期include網頁,並可搭配<jsp:param>動作元素來指定參數給被include的網頁,被include的網頁執行完後,response的權限會交回到要求include的網頁中,我們使用以下這個例子來說明:
user=Jstin 此參數,是動態時期給予的





2016年9月22日 星期四

Build Spring MVC

內容說明
- 建立Spring MVC
- 含有2種做法(1.一般 2. RequestMapping)

範例環境
- Intellj 13
- Spring 3.2.0
- Tomcat 7.0

前置作業
- 參考下列網址提供之 jar 檔下載
- 參考網址:
http://openhome.cc/Gossip/SpringGossip/FirstSpringMVC.html
http://blog.kenyang.net/2010/10/14/spring-mvcspringjar-spring-webmvc

範例實作
目標:
在index.jsp頁面輸入"字串",透過Spring MVC 將"字串"導到hello.jsp


0.檔案目錄結構












1.Tomcat 運行

2.Spring jar 檔匯入

3.web.xml設定

- 注意事項
a.設定『Tomcat』一啟動要進入的url(可自行決定是否加入)
<welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
</welcome-file-list>

b.只要任何url後面為.do(例如:http://localhost:8080/hello.do),就會被『導入』到名稱為mvc-dispatcher的servlet

c.該servlet會在進入/WEB-INF/mvc-config.xml 該設定檔讀取設定(servlet-mapping會去找相同名稱的servlet此範例為name=mvc-dispatcher)

d.
如果今天想要強迫Web Container啟動時
1.就要載入特定的Servlet
2.並且指定載入的順序
那麼就需要<load-on-startup>標籤了
<?xml version="1.0" encoding="UTF-8"?>
<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>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>
4.mvc-config.xml 設定

注意:請直接參考code的內容註釋
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--要使用RequestMapping要有下面這句,url進來,到指定的資料夾中找,有設定RequestMapping的Controller-->
    <context:component-scan base-package="main"/>
    <!--RequestMapping結束-->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--InternalResourceViewResolver的"prefix"、"suffix"屬性會與ModelAndView返回的路徑資訊結合-->
        <!--在servlet requestMapping都會把路徑寫好,所以 打 / 就好)-->
<property name="prefix">
            <value>/</value>
        </property>
        <!--讀取"副檔名".jsp開頭的檔案-->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <!--第一種MyController沒有用RequestMapping,要特別指定,哪個url進來,要進到哪個controller-->
    <!--若有使用RequestMapping,則不需下面這段-->
    <!--網址為/hello.do進來的request,要進到哪一個controller-->
    <bean name="/hello.do" class="main.MyController">
    </bean>
</beans>
InternalResourceViewResolver 的設定不是必要的,如果沒設,處理請求的元件就必須以字串告知 spring-webmvc,接下來由哪個 URL 組織畫面進行回應,也就是你必須傳回如 "hello.jsp" 這樣的字串,這樣會比較沒有彈性,如上設定 InternalResourceViewResolver 的話,你只要傳回 "hello" 字串,InternalResourceViewResolver 會自動根據 prefix 與 suffix 設定,得知目前實際上要以 "/hello.jsp" 來進行『畫面回應』,將來若想要改為其他回應技術,就只需要修改 XML 檔案。

重點:
所以最後是return『response』回應給傳進來的request

而這個『response』是透過ModeAndView進行組織的,
而『Model 參數』用來攜帶『回應頁面』要用到的資料

5.index.jsp設定
<html>
  <head>
    <title></title>
  </head>
  <body>
      <form action="/hello.do">
        請輸入名子:<input type="text" name="nameInput">
          <input type="submit" value="傳送到一般的Spring">
      </form>

      <form action="/hello2.do">
          請輸入名子:<input type="text" name="nameInput2">
          <input type="submit" value="傳送到requestMapping">
      </form>

  </body>
</html>
6.hello.jsp設定
<html>
<head>
    <title></title>
</head>
<body>
    <h1>This is Form Normal Spring:Hello  ${nameInput}</h1><br>

    <h1>This is From RequestMapping:Hello   ${nameInput2}</h1>
</body>
</html>
7.使用基本Spring MVC 的Controller
package main;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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

/**
 * Created by ytchen on 2016/9/22.
 */
public class MyController implements Controller{
    public ModelAndView handleRequest(HttpServletRequest req,
                                      HttpServletResponse res)
            throws Exception {
        //取得index.jsp輸入的名子
        String name = req.getParameter("nameInput");

        //參數1:要傳到哪個jsp;參數2:該物件的屬性名稱(前台取值用)參數3:要傳遞的物件或值
        return new ModelAndView("hello", "nameInput", name);
    }
}
8.使用@RequestMapping Spring 的Controller

- 注意事項
- @RequestMapping 有2種標註方式,一種是標在class,一種是標在method。
- Class類別使用@Controller 標記為Controller
- 請參考:
http://www.blogjava.net/fancydeepin/archive/2014/08/15/springmvc-tutorial-02.html
http://www.cnblogs.com/zhangshitong/p/5195746.html
package main;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by ytchen on 2016/9/22.
 */
@Controller
public class MyController2 {

    @RequestMapping(value = "/hello2.do", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView hello(HttpServletRequest request) {

        //取得index.jsp輸入的名子
        String name = request.getParameter("nameInput2");

        //將request傳到指定jsp
        ModelAndView mav = new ModelAndView("hello");
        mav.addObject("nameInput2", name);
        return mav;
    }
}
9.運行畫面
a.index.jsp





b.按下傳送到一般的Spring





c.按下傳送到requestMapping