SpringMVC:接收请求参数和解决乱码和@RequestParam注解和对象接收参数(动力)

 

 

 

 

web.xml:添加过滤器,如果不添加,post请求如果提交中文接收会显示会发生乱码,Get请求不会乱码

<?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">

<!--    声明,注册springmvc的核心对象DispatcherServlet-->
    <servlet>
        <servlet-name>myweb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--        自定义springmvc读取的配置文件的位置-->
        <init-param>
            <!--springmvc的配置文件属性-->
            <param-name>contextConfigLocation</param-name>
            <!-- 指定自定义文件的位置-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

<!--        在tomcat启动后,创建Servlet对象
               load-on-startup:表示tomcat启动后创建对象的顺序,它的值是正数,数值越小 tomacat创建对象越早
-->
        <load-on-startup>1</load-on-startup>

    </servlet>

<!--    所有的*..do请求交给myweb中央处理器处理-->
    <servlet-mapping>
        <servlet-name>myweb</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--注册声明过滤器,解决post请求乱码问题-->
    <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>
        <!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
        <init-param>
            <param-name>forceReponsetEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
       <!--
          /*:表示强制所有的请求先通过过滤器处理
        -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

 springmvc.xml:

<?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 https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"/>

<!--    声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀:视图文件的路径-->
        <property name="prefix" value="/WEB-INF/view/"/>
        <!-- 后缀:视图文件的扩展名-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

逐个接收请求参数 

 MyController:

package com.bjpowernode.controller;

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;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class MyController {
    /*逐个接受请求参数:
      要求:处理器(控制器)方法的形参名和请求中的参数名必须一致
          同名的请求参数赋值给同名形参

      框架接收请求参数
      1.使用request对象接收请求参数
       String name=request.getParameter("name");
       String age=request.getParameter("age");
      2.springmvc框架通过DispatcherServlet调用MyController的doSome方法
        调用方法时,按名称对应,把接收的参数赋值给形参
        doSome(name,Integer.ValueOf(age))
        框架会提供类型转换功能,把String转换为int ,long,float等类型

      400的状态码是客户端错误,表示提交的请求参数过程中,发生了问题
      如果参数是String name,int age
      当提交的年龄为空时,空的字符串不能转换为int类型会报400
      String name,Integer age
      就可以提交空的age了 Integer可以接收null,但是不能提交abc
    */

    @RequestMapping(value ="/receiveproperty.do")   //value里面可以写多个名字进行访问
    public ModelAndView doSome(String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");

        //返回mv
        return mv;

    }

    //不在这里设置,使用过滤器设置字符编码
   /* public void doPost(HttpServletRequest request){
        //request.setCharacterEncoding("utf-8");
    }*/
}

 

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <h1>提交参数给Controller</h1>

  <form action="receiveproperty.do" method="post">
      姓名:<input type="text" name="name"><br>
      年龄:<input type="text" name="age"><br>
      <input type="submit" value="提交参数">
  </form>


</body>
</html>

show.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 19:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
 <h3>show.jsp,从request作用域中获取数据</h3>
  <h3>myname数据:${myname}</h3>
  <h3>myage数据:${myage}</h3>
</body>
</html>

 

 

 

解决请求参数和方法形参不一致问题: 

 index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <h1>提交参数给Controller</h1>

  <form action="receiveproperty.do" method="post">
      姓名:<input type="text" name="name"><br>
      年龄:<input type="text" name="age"><br>
      <input type="submit" value="提交参数">
  </form>

  <h1>请求参数和处理器方法的形参名不一致</h1>

  <form action="receiveparam.do" method="post">
      姓名:<input type="text" name="rname"><br>
      年龄:<input type="text" name="rage"><br>
      <input type="submit" value="提交参数">
  </form>


</body>
</html>

MyController:

package com.bjpowernode.controller;

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

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

@Controller
public class MyController {
    /*逐个接受请求参数:
      要求:处理器(控制器)方法的形参名和请求中的参数名必须一致
          同名的请求参数赋值给同名形参

      框架接收请求参数
      1.使用request对象接收请求参数
       String name=request.getParameter("name");
       String age=request.getParameter("age");
      2.springmvc框架通过DispatcherServlet调用MyController的doSome方法
        调用方法时,按名称对应,把接收的参数赋值给形参
        doSome(name,Integer.ValueOf(age))
        框架会提供类型转换功能,把String转换为int ,long,float等类型

      400的状态码是客户端错误,表示提交的请求参数过程中,发生了问题
      如果参数是String name,int age
      当提交的年龄为空时,空的字符串不能转换为int类型会报400
      String name,Integer age
      就可以提交空的age了 Integer可以接收null,但是不能提交abc
    */

    @RequestMapping(value ="/receiveproperty.do")   //value里面可以写多个名字进行访问
    public ModelAndView doSome(String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");

        //返回mv
        return mv;

    }


    /*
    请求参数和处理器方法的形参名不一致
    使用注解@RequestParam:逐个接收请求参数中,解决请求中参数名不一致的问题
      属性:value 请求中的参数名称
           required 是一个bnoolean 默认是true:表示请求中必须包含此参数
                                       false :表示参数可以有可以没有
      位置:在处理器方法形参定义的前面
    * */
    @RequestMapping(value ="/receiveparam.do")   //value里面可以写多个名字进行访问
    public ModelAndView receiveParam(@RequestParam(value = "rname") String name,
                                     @RequestParam("rage") Integer age){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");

        //返回mv
        return mv;

    }


    //不在这里设置,使用过滤器设置字符编码
   /* public void doPost(HttpServletRequest request){
        //request.setCharacterEncoding("utf-8");
    }*/
}

 

逐个接收参数,当参数少的时候比较方便,当参数多的时候,就不够方便了,框架还有一种接收方式,用Java对象接收,一次接收过个请求参数

对象接收请求参

Student:

package com.bjpowernode.vo;
//保存请求参数的一个普通类
public class Student {
    //属性名和请求中的参数名一样
    private String name;
    private Integer age;

    public Student() {
        System.out.println("===Student===的无参构造方法");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("SetName="+name);
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        System.out.println("SetAge="+age);
        this.age = age;
    }

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

MyController:

 

package com.bjpowernode.controller;

import com.bjpowernode.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
public class MyController {
    /*逐个接受请求参数:
      要求:处理器(控制器)方法的形参名和请求中的参数名必须一致
          同名的请求参数赋值给同名形参

      框架接收请求参数
      1.使用request对象接收请求参数
       String name=request.getParameter("name");
       String age=request.getParameter("age");
      2.springmvc框架通过DispatcherServlet调用MyController的doSome方法
        调用方法时,按名称对应,把接收的参数赋值给形参
        doSome(name,Integer.ValueOf(age))
        框架会提供类型转换功能,把String转换为int ,long,float等类型

      400的状态码是客户端错误,表示提交的请求参数过程中,发生了问题
      如果参数是String name,int age
      当提交的年龄为空时,空的字符串不能转换为int类型会报400
      String name,Integer age
      就可以提交空的age了 Integer可以接收null,但是不能提交abc
    */

    @RequestMapping(value ="/receiveproperty.do")   //value里面可以写多个名字进行访问
    public ModelAndView doSome(String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");

        //返回mv
        return mv;

    }


    /*
    请求参数和处理器方法的形参名不一致
    使用注解@RequestParam:逐个接收请求参数中,解决请求中参数名不一致的问题
      属性:value 请求中的参数名称
           required 是一个bnoolean 默认是true:表示请求中必须包含此参数
                                       false :表示参数可以有可以没有
      位置:在处理器方法形参定义的前面
    * */
    @RequestMapping(value ="/receiveparam.do")   //value里面可以写多个名字进行访问
    public ModelAndView receiveParam(@RequestParam(value = "rname") String name,
                                     @RequestParam("rage") Integer age){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("调用Sevice后:");//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");

        //返回mv
        return mv;

    }


    /*
      处理器方法形参是java对象,这个对象的属性名和请求中的参数名一样
         把同名的参数赋值给同名的属性
      框架会创建形参的java对象,给属性赋值,请求中的参数是name,框架会调用setName()
    * */
    @RequestMapping(value ="/receiveobject.do")   //value里面可以写多个名字进行访问
    public ModelAndView receiveObject(Student myStudent){ //doSome相当于doGet()---调用Service请求处理
        System.out.println("receiveParam,name="+myStudent.getName()+"   age="+myStudent.getAge());//这里先不调用,简化处理
        ModelAndView mv=new ModelAndView();

        //添加数据,框架在请求的最后把数据放入到request作用域。
        //request.setAttribute("msg","欢迎使用mvc开发")
        mv.addObject("myname",myStudent.getName());
        mv.addObject("myage",myStudent.getAge());
        mv.addObject("mystudent",myStudent);

        mv.setViewName("show");

        //返回mv
        return mv;

    }



    //不在这里设置,使用过滤器设置字符编码
   /* public void doPost(HttpServletRequest request){
        //request.setCharacterEncoding("utf-8");
    }*/
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <h1>提交参数给Controller</h1>

  <form action="receiveproperty.do" method="post">
      姓名:<input type="text" name="name"><br>
      年龄:<input type="text" name="age"><br>
      <input type="submit" value="提交参数">
  </form>

  <h1>请求参数和处理器方法的形参名不一致</h1>

  <form action="receiveparam.do" method="post">
      姓名:<input type="text" name="rname"><br>
      年龄:<input type="text" name="rage"><br>
      <input type="submit" value="提交参数">
  </form>

  <h1>使用对象接收请求参数</h1>

  <form action="receiveobject.do" method="post">
      姓名:<input type="text" name="name"><br>
      年龄:<input type="text" name="age"><br>
      <input type="submit" value="提交参数">
  </form>


</body>
</html>

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值