SringMVC 获取请求参数

1. 参数类型

  • 基本类型
  • POJO类型
  • 数组类型
  • 集合类型
  • json字符串
  • Restful风格
  • 日期类型
  • servlet api
  • 请求头

2. 编写代码测试

2.1 添加依赖

<dependencies>
        <!-- webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.11.3</version>
        </dependency>
    </dependencies>

2.2 编写实体类

/**
 * 实体类User
 */
public class User
{
    private String username;
    private Integer age;

    public User()
    {

    }

    public User(String username,Integer age)
    {
        this.username = username;
        this.age = age;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public Integer getAge()
    {
        return age;
    }

    public void setAge(Integer age)
    {
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

/**
 * 实体类VO
 */
public class Vo
{
    private List<User> users;

    public List<User> getUsers()
    {
        return users;
    }

    public void setUsers(List<User> users)
    {
        this.users = users;
    }

    @Override
    public String toString()
    {
        return "Vo{" +
                "users=" + users +
                '}';
    }
}

2.3 编写日期转换器

/**
 * 日期转换器
 */
public class DateConverter implements Converter<String, Date>
{
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    public Date convert(String s)
    {
        Date date = null;
        try
        {
            date = sdf.parse(s);
        } catch (ParseException e)
        {
            e.printStackTrace();
        }
        return date;
    }
}

2.4 编写Spring核心配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描Controller包 -->
    <context:component-scan base-package="site.zhouyun.controller" />

    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/jsp/"></property>
       <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 注解驱动 -->
    <mvc:annotation-driven conversion-service="conversionService"/>

    <!-- 找不到资源默认就交给tomcat容器查找 -->
    <mvc:default-servlet-handler />

    <!-- 声明日期转换器 -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="site.zhouyun.converter.DateConverter"></bean>
            </list>
        </property>
    </bean>

</beans>

2.5 修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 解决请求乱码 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- dispatcherServlet -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.6 编写Controller

/**
 * 数据请求Controller
 */
@Controller
@RequestMapping("request")
public class DataRequestController
{
    /**
     * 基本类型
     */
    @ResponseBody
    @RequestMapping("method01")
    public void method01(String username, Integer age)
    {
        System.out.println("username=" + username + ", age=" + age);
    }

    /**
     * POJO类型
     */
    @ResponseBody
    @RequestMapping("method02")
    public void method02(User user)
    {
        System.out.println(user);
    }

    /**
     * 数组类型
     */
    @ResponseBody
    @RequestMapping("method03")
    public void method03(String[] strs)
    {
        System.out.println(Arrays.asList(strs));
    }

    /**
     * 集合类型, 需要封装成一个对象
     */
    @ResponseBody
    @RequestMapping("method04")
    public void method04(Vo vo)
    {
        System.out.println(vo);
    }

    /**
     *  json字符串
     */
    @RequestMapping(value = "method05", method = RequestMethod.POST)
    @ResponseBody
    public void method05(@RequestBody List<User> users)
    {
        System.out.println(users);
    }

    /**
     * @RequestParam: 当请求的参数名称与Controller的业务方法名称不一致时, 可以通过@RequestParam注解显示绑定.
     *              value: 请求参数名词
     *              required: 指定参数是否必须包括, 默认为true.
     *              defaultValue: 默认值, 当没有指定请求参数时, 则使用指定的默认值.
     * @param username
     */
    @ResponseBody
    @RequestMapping("method06")
    public void method06(@RequestParam(value = "name", required = false, defaultValue = "cloud") String username)
    {
        System.out.println(username);
    }

    /**
     * Restful风格: url + 请求方式.
     *          GET: 获取资源.
     *          POST: 新建资源.
     *          PUT: 更新资源.
     *          DELETE: 删除资源.
     * @PathVariable: 获取路径上的值
     *
     */
    @ResponseBody
    @RequestMapping("method07/{username}")
    public void method07(@PathVariable String username)
    {
        System.out.println(username);
    }

    /**
     * 日期类型
     */
    @ResponseBody
    @RequestMapping("method08")
    public void method08(Date date)
    {
        System.out.println(date);
    }

    /**
     * servlet api
     */
    @RequestMapping("method09")
    public void method09(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException
    {
        String username = request.getParameter("username");
        session.setAttribute("username", username);
        System.out.println(username);
        // 重定向
        response.sendRedirect("/jsp/success.jsp");
    }

    /**
     * 获取请求头
     * @RequestHeader: 获取请求头, key-value格式
     * @CookieValue: 获取请求头中的Cookie, key-value格式
     */
    @ResponseBody
    @RequestMapping("method10")
    public void method10(@RequestHeader("User-Agent") String user_agent, @CookieValue("JSESSIONID") String jsessionid)
    {
        System.out.println("User-Agent: " + user_agent);
        System.out.println("JSESSIONID: " + jsessionid);
    }
}

2.7 添加jQuery

  • 在webapp目录下创建js文件夹, 然后将jQuery放入.

2.8 添加jsp文件

  • 在webapp目录下创建jsp文件夹, 然后将jsp文件放入.
ajax.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!-- 引入jQuery -->
<script src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
<script>

    // 测试json字符串方式, 在浏览器访问 http://localhost:8080/jsp/ajax.jsp 然后查看控制台就能看到效果了
    var users = new Array();
    // 构造数据
    users.push({username:"zhangsan",age:18});
    users.push({username:"lisi",age:20});
    
    $.ajax({
        type: "post",
        url: "${pageContext.request.contextPath}/request/method05",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(users)
    });
</script>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Hello ${sessionScope.username}</h1>
</body>
</html>
user.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <!-- 测试数组方式 -->
    <form method="post" action="${pageContext.request.contextPath}/request/method04">
        用户1:<br/>
        <input type="text" name="users[0].username" placeholder="用户名"><br/>
        <input type="number" name="users[0].age" placeholder="年龄"><br/><br/>

        用户2:<br/>
        <input type="text" name="users[1].username" placeholder="用户名"><br/>
        <input type="number" name="users[1].age" placeholder="年龄"><br/><br/>

        用户3:<br/>
        <input type="text" name="users[2].username" placeholder="用户名"><br/>
        <input type="number" name="users[2].age" placeholder="年龄"><br/><br/>

        <input type="submit" value="提交">
    </form>
</body>
</html>

3. 查看效果

  • 启动项目打开浏览器访问http://localhost:8080/request/method(01~10)就可以看到效果了.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值