zoukankan      html  css  js  c++  java
  • SpringMVC基础-03

    请求参数

    Address.java:

     1 package com.atguigu.book;
     2 
     3 public class Address {
     4     
     5     private String province;
     6     private String city;
     7     private String street;
     8     /**
     9      * @return the province
    10      */
    11     public String getProvince() {
    12         return province;
    13     }
    14     /**
    15      * @param province the province to set
    16      */
    17     public void setProvince(String province) {
    18         this.province = province;
    19     }
    20     /**
    21      * @return the city
    22      */
    23     public String getCity() {
    24         return city;
    25     }
    26     /**
    27      * @param city the city to set
    28      */
    29     public void setCity(String city) {
    30         this.city = city;
    31     }
    32     /**
    33      * @return the street
    34      */
    35     public String getStreet() {
    36         return street;
    37     }
    38     /**
    39      * @param street the street to set
    40      */
    41     public void setStreet(String street) {
    42         this.street = street;
    43     }
    44     /* (non-Javadoc)
    45      * @see java.lang.Object#toString()
    46      */
    47     @Override
    48     public String toString() {
    49         return "Address [province=" + province + ", city=" + city + ", street="
    50                 + street + "]";
    51     }
    52     
    53     
    54 
    55 }

    Book.java:

      1 package com.atguigu.book;
      2 
      3 /**
      4  * 书名:<input type="text" name="bookName"/><br/>
      5     作者:<input type="text" name="author"/><br/>
      6     价格:<input type="text" name="price"/><br/>
      7     库存:<input type="text" name="stock"/><br/>
      8     销量:<input type="text" name="sales"/><br/>
      9  * @author lfy
     10  *
     11  */
     12 public class Book {
     13     
     14     private String bookName;
     15     private String author;
     16     private Double price;
     17     private Integer stock;
     18     private Integer sales;
     19     private Address address;
     20     
     21     //一定有无参构造器
     22     
     23     
     24     
     25     /**
     26      * @return the bookName
     27      */
     28     public String getBookName() {
     29         return bookName;
     30     }
     31     /**
     32      * @return the address
     33      */
     34     public Address getAddress() {
     35         return address;
     36     }
     37     /**
     38      * @param address the address to set
     39      */
     40     public void setAddress(Address address) {
     41         this.address = address;
     42     }
     43     /**
     44      * @param bookName the bookName to set
     45      */
     46     public void setBookName(String bookName) {
     47         this.bookName = bookName;
     48     }
     49     /**
     50      * @return the author
     51      */
     52     public String getAuthor() {
     53         return author;
     54     }
     55     /**
     56      * @param author the author to set
     57      */
     58     public void setAuthor(String author) {
     59         this.author = author;
     60     }
     61     /**
     62      * @return the price
     63      */
     64     public Double getPrice() {
     65         return price;
     66     }
     67     /**
     68      * @param price the price to set
     69      */
     70     public void setPrice(Double price) {
     71         this.price = price;
     72     }
     73     /**
     74      * @return the stock
     75      */
     76     public Integer getStock() {
     77         return stock;
     78     }
     79     /**
     80      * @param stock the stock to set
     81      */
     82     public void setStock(Integer stock) {
     83         this.stock = stock;
     84     }
     85     /**
     86      * @return the sales
     87      */
     88     public Integer getSales() {
     89         return sales;
     90     }
     91     /**
     92      * @param sales the sales to set
     93      */
     94     public void setSales(Integer sales) {
     95         this.sales = sales;
     96     }
     97     /* (non-Javadoc)
     98      * @see java.lang.Object#toString()
     99      */
    100     /* (non-Javadoc)
    101      * @see java.lang.Object#toString()
    102      */
    103     @Override
    104     public String toString() {
    105         return "Book [bookName=" + bookName + ", author=" + author + ", price="
    106                 + price + ", stock=" + stock + ", sales=" + sales
    107                 + ", address=" + address + "]";
    108     }
    109 }

    HelloController.java:

      1 package com.atguigu.controller;
      2 
      3 import java.io.IOException;
      4 import org.springframework.stereotype.Controller;
      5 import org.springframework.web.bind.annotation.CookieValue;
      6 import org.springframework.web.bind.annotation.RequestHeader;
      7 import org.springframework.web.bind.annotation.RequestMapping;
      8 import org.springframework.web.bind.annotation.RequestParam;
      9 
     10 import com.atguigu.book.Book;
     11 
     12 import javax.servlet.http.HttpServletRequest;
     13 import javax.servlet.http.HttpServletResponse;
     14 import javax.servlet.http.HttpSession;
     15 
     16 @Controller
     17 public class HelloController {
     18 
     19     /**
     20      * request.getParameter("").....
     21      *
     22      * @return
     23      */
     24     @RequestMapping("/hello")
     25     public String handle01() {
     26         System.out.println("handle01...");
     27         return "success";
     28     }
     29 
     30     /**
     31      * SpringMVC如何获取请求带来的各种信息 默认方式获取请求参数: 直接给方法入参上写一个和请求参数名相同的变量。这个变量就来接收请求参数的值;
     32      * 带:有值,没带:null;
     33      *
     34      * @RequestParam:获取请求参数的;参数默认是必须带的;
     35      * @RequestParam("user")String username username =
     36      *                             request.getParameter("user")
     37      *
     38      *
     39      * @RequestParam("user")
     40      * @PathVariable("user")
     41      *                       /book/【{user}pathvariable】?【user=admin(requestparam)
     42      *                       】
     43      *
     44      *                       value:指定要获取的参数的key required:这个参数是否必须的
     45      *                       defaultValue:默认值。没带默认是null;
     46      *
     47      *
     48      * @RequestHeader:获取请求头中某个key的值; request.getHeader("User-Agent");
     49      * @RequestHeader("User-Agent")String userAgent userAgent =
     50      *                                    request.getHeader("User-Agent")
     51      *                                    如果请求头中没有这个值就会报错; value() required()
     52      *                                    defaultValue()
     53      *
     54      * @CookieValue:获取某个cookie的值; 以前的操作获取某个cookie; Cookie[] cookies =
     55      *                            request.getCookies(); for(Cookie c:cookies){
     56      *                            if(c.getName().equals("JSESSIONID")){ String
     57      *                            cv = c.getValue(); } }
     58      * value()
     59      * required()
     60      * defaultValue()
     61      */
     62     @RequestMapping("/handle01")
     63     public String handle02(
     64             @RequestParam(value = "user", required = false, defaultValue = "你没带") String username,
     65             @RequestHeader(value = "AHAHA", required = false, defaultValue = "她也没带") String userAgent,
     66             @CookieValue(value="JSESSIONID",required=false)String jid) {
     67         System.out.println("这个变量的值:" + username);
     68         System.out.println("请求头中浏览器的信息:" + userAgent);
     69         System.out.println("cookie中的jid的值"+jid);
     70         return "success";
     71     }
     72 
     73     /**
     74      * 如果我们的请求参数是一个POJO;
     75      * SpringMVC会自动的为这个POJO进行赋值?
     76      * 1)、将POJO中的每一个属性,从request参数中尝试获取出来,并封装即可;
     77      * 2)、还可以级联封装;属性的属性
     78      * 3)、请求参数的参数名和对象中的属性名一一对应就行
     79      *
     80      *
     81      * 提交的数据可能有乱码:
     82      * 请求乱码:
     83      *         GET请求:改server.xml;在8080端口处URIEncoding="UTF-8"
     84      *         POST请求:
     85      *             在第一次获取请求参数之前设置
     86      *             request.setCharacterEncoding("UTF-8");
     87      *             自己写一个filter;SpringMVC有这个filter
     88      *
     89      * 响应乱码:
     90      *         response.setContentType("text/html;charset=utf-8")
     91      * @param book
     92      * @return
     93      */
     94     @RequestMapping("/book")
     95     public String addBook(Book book){
     96         System.out.println("我要保存的图书:"+book);
     97         return "success";
     98     }
     99 
    100     /**
    101      * SpringMVC可以直接在参数上写原生API;
    102      *
    103      * HttpServletRequest
    104      * HttpServletResponse
    105      * HttpSession
    106      *
    107      *
    108      * java.security.Principal
    109      * Locale:国际化有关的区域信息对象
    110      * InputStream:
    111      *         ServletInputStream inputStream = request.getInputStream();
    112      * OutputStream:
    113      *         ServletOutputStream outputStream = response.getOutputStream();
    114      * Reader:
    115      *         BufferedReader reader = request.getReader();
    116      * Writer:
    117      *         PrintWriter writer = response.getWriter();
    118      *
    119      * @throws IOException
    120 
    121      *
    122      *
    123      */
    124     @RequestMapping("/handle03")
    125     public String handle03(HttpSession session,
    126                            HttpServletRequest request, HttpServletResponse response) throws IOException {
    127         request.setAttribute("reqParam", "我是请求域中的");
    128         session.setAttribute("sessionParam", "我是Session域中的");
    129 
    130         return "success";
    131     }
    132 
    133 }

    springmvc.xml:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:context="http://www.springframework.org/schema/context"
     5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
     7 
     8     <!-- 扫描所有组件 -->
     9     <context:component-scan base-package="com.atguigu"></context:component-scan>
    10 
    11     <!-- 配置一个视图解析器 ;能帮我们拼接页面地址-->
    12     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    13         <property name="prefix" value="/WEB-INF/pages/"></property>
    14         <property name="suffix" value=".jsp"></property>
    15     </bean>
    16 </beans>

    web.xml:

     1 <!DOCTYPE web-app PUBLIC
     2         "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     3         "http://java.sun.com/dtd/web-app_2_3.dtd" >
     4 
     5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     6          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     7          id="WebApp_ID" version="3.0">
     8     <display-name>4.SpringMVC_request</display-name>
     9     <welcome-file-list>
    10         <welcome-file>index.jsp</welcome-file>
    11     </welcome-file-list>
    12 
    13     <!-- The front controller of this Spring Web application,
    14     responsible for handling all application requests -->
    15     <servlet>
    16         <servlet-name>springDispatcherServlet</servlet-name>
    17         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    18 
    19         <init-param>
    20             <!-- contextConfigLocation:指定SpringMVC配置文件位置 -->
    21             <param-name>contextConfigLocation</param-name>
    22             <param-value>classpath:springmvc.xml</param-value>
    23         </init-param>
    24         <load-on-startup>1</load-on-startup>
    25     </servlet>
    26 
    27     <!-- Map all requests to the DispatcherServlet for handling -->
    28     <servlet-mapping>
    29         <servlet-name>springDispatcherServlet</servlet-name>
    30         <url-pattern>/</url-pattern>
    31     </servlet-mapping>
    32 
    33     <!-- 配置一个字符编码的Filter;一定注意:字符编码filter一般都在其他Filter之前-->
    34     <!--配置字符集编码的Filter-->
    35     <filter>
    36         <filter-name>CharacterEncodingFilter</filter-name>
    37         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    38         <!-- encoding:指定解决POST请求乱码 -->
    39         <init-param>
    40             <param-name>encoding</param-name>
    41             <param-value>UTF-8</param-value>
    42         </init-param>
    43         <init-param>
    44             <!-- forceEncoding:顺手解决响应乱码;response.setCharacterEncoding(this.encoding); -->
    45             <param-name>forceEncoding</param-name>
    46             <param-value>true</param-value>
    47         </init-param>
    48     </filter>
    49     <filter-mapping>
    50         <filter-name>CharacterEncodingFilter</filter-name>
    51         <url-pattern>/*</url-pattern>
    52     </filter-mapping>
    53 
    54     <!--支持Rest风格的Filter(开启PUT、DELETE请求)-->
    55     <filter>
    56         <filter-name>HiddenHttpMethodFilter</filter-name>
    57         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    58     </filter>
    59     <filter-mapping>
    60         <filter-name>HiddenHttpMethodFilter</filter-name>
    61         <url-pattern>/*</url-pattern>
    62     </filter-mapping>
    63     <!-- 使用SpringMVC前端控制器写完就直接写字符编码过滤器;
    64 Tomcat一装上,上手就是server.xml的8080处添加URIEncoding="UTF-8"
    65      -->
    66 
    67 </web-app>

    index.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2          pageEncoding="UTF-8"%>
     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=UTF-8">
     7     <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <a href="hello">hello</a><br/>
    11 <a href="handle01?username=tomcat">handle01</a><br/>
    12 <form action="book" method="post">
    13     书名:<input type="text" name="bookName"/><br/>
    14     作者:<input type="text" name="author"/><br/>
    15     价格:<input type="text" name="price"/><br/>
    16     库存:<input type="text" name="stock"/><br/>
    17     销量:<input type="text" name="sales"/><br/>
    18     <hr/>
    19     省:<input type="text" name="address.province"/>
    20     市:<input type="text" name="address.city"/>
    21     街道:<input type="text" name="address.street"/><br/>
    22     <input type="submit"/>
    23 </form>
    24 </body>
    25 </html>

    success.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2          pageEncoding="UTF-8"%>
     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=UTF-8">
     7     <title>Insert title here</title>
     8 </head>
     9 <body>
    10 <h1>成功!</h1>
    11 请求:${requestScope.reqParam }<br/>
    12 session:${sessionScope.sessionParam }<br/>
    13 </body>
    14 </html>
  • 相关阅读:
    VMware Workstation安装CentOs7固定ip地址
    使用阿里云oss
    使用Yapi展示你的api接口
    .net core使用MQTT
    CentOS 7服务器安装brook和bbr加速
    博客主题
    自定义控件
    winform数据绑定
    is as 运算符
    反射
  • 原文地址:https://www.cnblogs.com/116970u/p/13154734.html
Copyright © 2011-2022 走看看