springmvc之擷取參數,springmvc擷取

來源:互聯網
上載者:User

springmvc之擷取參數,springmvc擷取

1.導包,四大核心包,一個切麵包(AOP),logging,web,springmvc

2.設定檔,核心代碼如下:

   web.xml

<servlet>        <servlet-name>springDispatcherServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:springmvc.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>        <!-- Map all requests to the DispatcherServlet for handling -->    <servlet-mapping>        <servlet-name>springDispatcherServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>            <!--字元編碼的filter一定要放在最前面  -->      <filter>          <filter-name>CharacterEncodingFilter</filter-name>        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>        <!-- 配置encoding,告訴我們指定的編碼格式 -->        <init-param>            <param-name>encoding</param-name>            <param-value>utf-8</param-value>        </init-param>        <!-- 解決響應亂碼 -->        <init-param>            <param-name>forceEncoding</param-name>            <param-value>true</param-value>        </init-param>      </filter>      <filter-mapping>          <filter-name>CharacterEncodingFilter</filter-name>          <url-pattern>/</url-pattern>      </filter-mapping>          <!-- 支援rest的filter -->      <filter>          <filter-name>HiddenHttpMethodFilter</filter-name>        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>      </filter>          <filter-mapping>          <filter-name>HiddenHttpMethodFilter</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>

springmvc.xml

<context:component-scan base-package="com.atguigu"></context:component-scan>        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 視圖分析器 -->            <property name="prefix" value="/WEB-INF/pages/"></property>            <property name="suffix" value=".jsp"></property>        </bean></beans>

 

 

index.jsp: 首頁進入

<body>    <a href="hello">hello</a><br/>    <a href="handle01?user=123456">擷取請求參數</a><br/>    <a href="handle02">擷取要求標頭</a><br/>    <form action="saveBook" method="post">        圖書id<input type="text" name="id"/><br/>        圖書name<input type="text" name="name"/><br/>        圖書author<input type="text" name="author"/><br/>        圖書price<input type="text" name="price"/><br/>        圖書sales<input type="text" name="sales"/><br/>        圖書stock<input type="text" name="stock"/><br/>        <hr/>        <!-- 級聯屬性來封裝值 -->        作者name;<input type="text" name="person.name"/><br/>        作者address;<input type="text" name="person.address"/><br/>        <input type="submit" value="儲存圖書"/>    </form>    <hr/>    <h2>給頁面攜帶資料</h2>    <a href="output01">output01</a></body>

 

3./WEB-INF/pages    跳轉後的內容

  1).success.jsp

<body>    <h1>成功!</h1>    ${msg}===${reMsg}</body>

  2).testScope.jsp

<body>    <h1>測試資料帶在了哪個scope</h1>    request:${requestScope.msg }<br />     session:${sessionScope.msg }<br />     application:${applicationScope.msg}</body>

4.src/bean包   Author.java  

public class Author {     private String name;     private String address;

   Book.java:  

public class Book {    private int id;    private String name;    private double price;    private int sales;    private int stock;    private Author person;    private String imgPath = "static/img/default.jpg";    private String author;

src/controller 包, HelloController.java:  如果不加,則不能訪問

import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class HelloController {        @RequestMapping("/hello") //串連地址必須加上"/hello"    public String hello(){        return "success";            }}

    TestParamController.java

@Controllerpublic class TestParamController {        /**     * 1、直接給方法的參數位置寫上一個和請求帶來的參數的名字相同的變數     * 2、這個變數就封裝的是帶來的參數的值     *  user = request.getParameter("user")     * 3、如果沒有就是null     *       * @RequestParam("user"):指定擷取哪個參數的值     * 1、預設發送請求必須帶上這個參數;     *         否則:HTTP Status 400 - Required String parameter 'user' is not present     * 2、required=false可以設定不是必須的;沒帶null     * 3、defaultValue="未命名"指定沒帶時的預設值;     *         user = request.getParameter("user");     */        @RequestMapping("/handle01")    public String handle01(            @RequestParam(value = "user", required = false, defaultValue = "未命名") String user) {        System.out.println("擷取的User:" + user);        return "success";    }        /**     * 擷取要求標頭;     *         request.getHeader("User-Agent")     * 註解做了下面這些事情     * @RequestHeader("User-Agent")String userAgent;     *         userAgent = request.getHeader("User-Agent");*/    @RequestMapping("/handle02")    public String handle02(            @RequestHeader(value = "User-Agent", required = false, defaultValue = "沒有的") String userAgent) {        System.out.println("User-Agent:" + userAgent);        return "success";    }        /**     * 擷取某個cookie的值;     * JSESSIONID=B05C018F82AA1B0BD3845831FADFE49A     * @CookieValue("JSESSIONID")String jid     * 註解做了下面這些事情     *   Cookie[] cookies = request.getCookies();     *   for(Cookie c:cookies){     *       if(c.getName().equals("JSESSIONID")){     *           jid = c.getValue();     *       }     *   }*/    @RequestMapping("/handle03")    public String handle03(            @CookieValue(value = "JSESSIONID", required = false, defaultValue = "hhhhh") String jid) {        System.out.println("jid:" + jid);        return "success";    }    /*傳入POJO;直接幫我們封裝頁面的值;  方便簡單,少寫很多代碼,實現代碼分離,解耦和     * 1、book = new Book();     * 2、把book對象中的每一個屬性的值查出來,request.getParameter(屬性);     * 3、把這個值設定進去     * 注意:因為SpringMVC會進行類型轉換,所以提交的資料一定要是合法的,否則400錯誤*/    @RequestMapping("/saveBook")    public String handle04(Book book) {        System.out.println("book的值:" + book);        return "success";    }    @RequestMapping("/handle05")    // pringMVC還允許我們在請求參數上使用原生的ServletAPI HttpServletRequest HttpServletResponse    // HttpSession    public String handle05(HttpSession session, HttpServletRequest request,            HttpServletResponse response) {        session.setAttribute("msg", "哈哈哈");        request.setAttribute("reqMsg", "嘿嘿嘿");        return "success";    }}

src/dataout/   DataOutPutController.java  給頁面攜帶資料

@Controller //給頁面攜帶資料public class DataOutPutController {    /**     * 1、傳回值改為ModelAndView(包含模型資料(Model)和要去的頁面地址(View));     *         資料放在請求域中;     * 2、在請求參數上傳入Model、Map、ModelMap都行;給他們裡面儲存的資料會放在請求域中     * Model、Map、ModelMap最終其實都是再有用BindingAwareModelMap;     * 相當於給BindingAwareModelMap中儲存資料就是給請求域中儲存     * Model          Map     *     ||            ||     *     ||            \/     *     ||        ModelMap     *     \/            \/     *     ExtendedModelMap【隱含模型】 extends ModelMap implements Model     *         \/     *     BindingAwareModelMap     * @return     */    @RequestMapping("/output04")    public String output04(ModelMap model){        //視圖解析器會對視圖名進行拼串        model.addAttribute("msg","output04");        System.out.println(model.getClass());        return "testScope";            }    @RequestMapping("/output03")    public String output03(Model model){        model.addAttribute("msg", "output03");        System.out.println(model.getClass());        return "testScope";    }    @RequestMapping("/output02")    public String output02(Map<String,Object>map){        //視圖解析器會對視圖名進行拼串        map.put("msg", "output02");        System.out.println(map.getClass());        return "testScope";    }    @RequestMapping("/output01")    public ModelAndView output01(){        //視圖解析器會對視圖名進行拼串        ModelAndView modelAndView = new ModelAndView();        modelAndView.setViewName("testScope");        modelAndView.addObject("msg", "output01");        return modelAndView;            }}

 

  

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.