• Java--SpringMVC之RequestMapping请求映射和处理器方法参数


    1、新建一个maven的web项目,选择

    maven-archetype-webapp

    2、pom.xml文件加入依赖

    spring-webmvc依赖,间接把spring的依赖都加入到项目;jsp,servlet依赖

    1. <properties>
    2. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    3. <maven.compiler.source>1.8maven.compiler.source>
    4. <maven.compiler.target>1.8maven.compiler.target>
    5. properties>
    6. <dependencies>
    7. <dependency>
    8. <groupId>junitgroupId>
    9. <artifactId>junitartifactId>
    10. <version>4.11version>
    11. <scope>testscope>
    12. dependency>
    13. <dependency>
    14. <groupId>org.springframeworkgroupId>
    15. <artifactId>spring-webmvcartifactId>
    16. <version>5.2.5.RELEASEversion>
    17. dependency>
    18. <dependency>
    19. <groupId>javax.servletgroupId>
    20. <artifactId>javax.servlet-apiartifactId>
    21. <version>3.1.0version>
    22. <scope>providedscope>
    23. dependency>
    24. dependencies>
    25. <build>
    26. <resources>
    27. <resource>
    28. <directory>src/main/javadirectory>
    29. <includes>
    30. <include>**/*.propertiesinclude>
    31. <include>**/*.xmlinclude>
    32. includes>
    33. <filtering>falsefiltering>
    34. resource>
    35. resources>
    36. build>

    3、新建web.xml文件,并在该配置文件中注册SpringMVC框架的核心对象DispatcherServlet

    1. "1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <servlet>
    7. <servlet-name>mywebservlet-name>
    8. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    9. <init-param>
    10. <param-name>contextConfigLocationparam-name>
    11. <param-value>classpath:springmvc.xmlparam-value>
    12. init-param>
    13. <load-on-startup>1load-on-startup>
    14. servlet>
    15. <servlet-mapping>
    16. <servlet-name>mywebservlet-name>
    17. <url-pattern>*.dourl-pattern>
    18. servlet-mapping>
    19. web-app>

    4、创建一个发起请求的页面 index.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Titletitle>
    5. head>
    6. <body>
    7. <p>SpringMVC项目p>
    8. <p> <a href="menu/some.do">发起some.do的GET请求a> p>
    9. <br/>
    10. <form action="menu/other.do" method="post">
    11. <input type="submit" value="post请求other.do">
    12. form>
    13. <br/>
    14. <p> <a href="menu/noMethod.do">发起noMethod.do的GET请求a> p>
    15. <br/>
    16. <form action="menu/noMethod.do" method="post">
    17. <input type="submit" value="post请求noMethod.do">
    18. form>
    19. body>
    20. html>

    5、创建控制器(处理器)类

    6、创建一个结果的 show.jsp,显示处理结果

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Titletitle>
    5. head>
    6. <body>
    7. <h3>/WEB-INF/view/show.jsp从request作用域获取数据h3>
    8. <h3>msg数据:${msg}h3><br/>
    9. <h3>fun数据:${fun}h3>
    10. body>
    11. html>

     7、创建SpringMVC的配置文件(和spring的配置文件一样)

    工程的类路径即 src 目录下创建 SpringMVC 的配置文件 springmvc.xml

    1. "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
    6. http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context
    8. https://www.springframework.org/schema/context/spring-context.xsd">
    9. <context:component-scan base-package="com.mycompany.controller" />
    10. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    11. <property name="prefix" value="/WEB-INF/view/" />
    12. <property name="suffix" value=".jsp" />
    13. bean>
    14. beans>

    8、启动Tomcat,或者未修改Java代码,只修改 jsp 代码,重启资源即可配置如下 

    选择Edit Configurations...

    点击添加,选择Tomcat Server ----> Local

     

    如果这里没有Tomcat Server 选项 ;有可能是tomcat插件没启用,我们点击

    file---->setting---->搜索tomcat---->勾选上

    (3)配置Tomcat的信息

    (4)点击Deployment----加号➕----Artifact...,配置访问路径

    对应web.xml文件中的url-pattern 访问的路径 

    启动Tomcat,输入的访问地址为 网址+端口号+工程名+访问的路径;如:

     输入 :http://localhost:8888/spring-web/

    一、@RequestMapping请求映射规则 

    @RequestMapping 注解可以定义处理器对于请求的映射规则。该注解可以注解在方法上,也可以注解在类上

    1、value 属性

    value属性值常以 "/" 开始

    @RequestMapping 的 value 属性用于定义所匹配请求的 URI。一个@Controller 所注解的类中,可以定义多个处理器方法。不同的处理器方法所匹配的 URI 是不同的,不同的 URI 被指定在注解于方法之上的@RequestMapping 的value 属性中。但若这些请求具有相同的 URI 部分,则这些相同的 URI,可以被抽取到注解在类之上的@RequestMapping 的 value 属性中。此时的这个 URI 表示模块的名称。URI 的请求是相对于 Web 的根目录

    (1)@RequestMapping放在类上面,就是请求地址的公共部分(模块名称)

    (2)@RequestMapping放在方法上面,结合类上的RequestMapping的value值即是模块的某个方法请求

    2、method属性

    Method 属性的取值为 RequestMethod 枚举常量。常用的为 RequestMethod.GET 与RequestMethod.POST,分别表示提交方式的匹配规则为 GET 与 POST 提交

    注:

    (1)指定了GET请求,就不能使用POST请求,不然报错

    (2)不指定请求方式,没有限制,GET和POST皆可

    1. import org.springframework.stereotype.Controller;
    2. import org.springframework.web.bind.annotation.RequestMapping;
    3. import org.springframework.web.bind.annotation.RequestMethod;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. import javax.servlet.http.HttpSession;
    8. /**
    9. * @RequestMapping
    10. * value:放在类上就是请求地址的公共部分(模块名称)
    11. */
    12. @Controller
    13. @RequestMapping("/menu")
    14. public class MyController {
    15. /**
    16. * @RequestMapping :请求映射
    17. * 属性:method,表示请求的方式,值为RequestMethod枚举值
    18. * Get请求方式,RequestMethod.GET
    19. * POST请求方式,RequestMethod.POST
    20. *
    21. * 指定了请求方式,如Get,使用POST请求会报错:
    22. * HTTP Status 405 - Request method 'POST' not supported
    23. */
    24. //指定some.do使用get请求方式
    25. @RequestMapping(value = "/some.do",method = RequestMethod.GET)
    26. public ModelAndView doSome(){ // doGet()----service请求处理
    27. //处理 some.do请求,相当于service调用处理完成
    28. ModelAndView mdv = new ModelAndView();
    29. mdv.addObject("msg","欢迎使用SpringMVC做web开发");
    30. mdv.addObject("fun","执行的是doSome方法");
    31. mdv.setViewName("show");
    32. return mdv;
    33. }
    34. //指定other.do是post请求方式
    35. @RequestMapping(value = "/other.do",method = RequestMethod.POST)
    36. public ModelAndView doOther(){
    37. ModelAndView mv = new ModelAndView();
    38. mv.addObject("msg","====欢迎使用SpringMVC做web开发====");
    39. mv.addObject("fun","执行的是doOther方法");
    40. mv.setViewName("other");
    41. return mv;
    42. }
    43. //不指定请求方式,没有限制
    44. @RequestMapping(value = "/noMethod.do")
    45. public ModelAndView doNoMethod(HttpServletRequest request,
    46. HttpServletResponse response,
    47. HttpSession session){
    48. ModelAndView mv = new ModelAndView();
    49. mv.addObject("msg","====欢迎使用SpringMVC做web开发====" + request.getParameter("name"));
    50. mv.addObject("fun","执行的是doNoMethod方法");
    51. mv.setViewName("other");
    52. return mv;
    53. }
    54. }

    二、处理器方法参数

    1、逐个参数接收

    (1)请求参数名与该请求处理方法的参数名相同

    index.jsp页面

    1. <p>提交参数给Controllerp>
    2. <form action="receiveproperty.do" method="post">
    3. 姓名:<input type="text" name="name"> <br/>
    4. 年龄:<input type="text" name="age"> <br/>
    5. <input type="submit" value="提交参数">
    6. form>

    MyController.java处理器类

    1. /**
    2. * 1、逐个接收请求参数
    3. * 处理器(控制器)方法的形参名和请求中参数名必须一致;同名请求参数赋值给同名形参
    4. *
    5. * SpringMVC框架接收请求参数
    6. * (1)使用request对象接收请求参数
    7. * String strName = request.getParameter("name");
    8. * String strAge = request.getParameter("age");
    9. * (2)SpringMVC框架通过DispatcherServlet调用 MyController的doSome()方法
    10. * 调用方法时,按名称对应,把接收的参数赋值给形参
    11. * doSome(strName,Integer.valueOf(strAge))
    12. * 框架会提供类型转换的功能,能把String转为 int ,long , float, double等类型
    13. */
    14. @RequestMapping(value = "/receiveproperty.do")
    15. public ModelAndView doSome(String name,Integer age){
    16. System.out.println("doSome, name="+name+" age="+age);
    17. //处理 some.do请求,相当于service调用处理完成
    18. ModelAndView mdv = new ModelAndView();
    19. mdv.addObject("myname",name);
    20. mdv.addObject("myage",Integer.valueOf(age));
    21. mdv.setViewName("show");
    22. return mdv;
    23. }

    (2)请求参数名与该请求处理方法的参数名不相同

    若请求 URL 所携带的参数名称与处理方法中指定的参数名不相同时,则需在处理方法参数前,添加一个注解@RequestParam(“请求参数名”),指定请求 URL 所携带参数的名称

    index.jsp页面

    1. <br/>
    2. <p>请求参数名和处理器方法的形参名不一样p>
    3. <form action="receiveparam.do" method="post">
    4. 姓名:<input type="text" name="rname"> <br/>
    5. 年龄:<input type="text" name="rage"> <br/>
    6. <input type="submit" value="提交参数">
    7. form>

    MyController.java处理器类

    1. /**
    2. * 逐个接收请求参数
    3. *
    4. * 请求中参数名和处理器方法的形参名不一样
    5. * @RequestParam : 逐个接收请求参数中,解决请求中参数名形参名不一样问题
    6. * 属性:1、value 请求中的参数名称
    7. * 2、required boolean类型,默认是true
    8. * true请求中必须包含此参数
    9. * 位置:在处理器方法的形参定义前面
    10. */
    11. @RequestMapping(value = "/receiveparam.do")
    12. public ModelAndView receiveParams(@RequestParam(value = "rname",required = false) String name,
    13. @RequestParam(value = "rage",required = false) Integer age){
    14. System.out.println("receiveparam, name="+name+" age="+age);
    15. ModelAndView mv = new ModelAndView();
    16. mv.addObject("myname",name);
    17. mv.addObject("m yage",age);
    18. //show是视图文件的逻辑名称(文件名称)
    19. mv.setViewName("show");
    20. return mv;
    21. }

    2、对象接收

    将处理器方法的参数定义为一个对象,保证请求参数名与这个对象的属性同名即可

    Java对象Student.java类
    1. public class Student {
    2. // 属性名和请求中参数名一样
    3. private String name;
    4. private Integer age;
    5. }

    index.jsp页面

    1. <br/>
    2. <p>使用java对象接收请求参数p>
    3. <form action="receiveobject.do" method="post">
    4. 姓名:<input type="text" name="name"> <br/>
    5. 年龄:<input type="text" name="age"> <br/>
    6. <input type="submit" value="提交参数">
    7. form>
    MyController.java处理器类
    1. /**
    2. * 对象接收请求参数
    3. */
    4. @RequestMapping(value = "/receiveobject.do")
    5. public ModelAndView receiveObject(Student student){
    6. System.out.println("receiveParam, name=" + student.getName() + " age=" + student.getAge());
    7. //可以在方法中直接使用 name , age
    8. //处理some.do请求了。 相当于service调用处理完成了。
    9. ModelAndView mv = new ModelAndView();
    10. mv.addObject("myname",student.getName());
    11. mv.addObject("myage",student.getAge());
    12. mv.addObject("mystudent",student);
    13. //show是视图文件的逻辑名称(文件名称)
    14. mv.setViewName("show");
    15. return mv;
    16. }

    这里需要注意一个问题,我们使用POST请求,如果参数中包含中文,会出现乱码情况

    使用GET请求不会出现此问题,我们需要在 web.xml 配置文件中注册字符集过滤器:spring-web-5.2.5.RELEASE.jar 的org.springframework.web.filter 包下的 CharacterEncodingFilter

    1. public class CharacterEncodingFilter extends OncePerRequestFilter {
    2. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    3. String encoding = this.getEncoding();
    4. if (encoding != null) {
    5. if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
    6. request.setCharacterEncoding(encoding);
    7. }
    8. if (this.isForceResponseEncoding()) {
    9. response.setCharacterEncoding(encoding);
    10. }
    11. }
    12. filterChain.doFilter(request, response);
    13. }
    14. }
    1. <filter>
    2. <filter-name>characterEncodingFilterfilter-name>
    3. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    4. <init-param>
    5. <param-name>encodingparam-name>
    6. <param-value>utf-8param-value>
    7. init-param>
    8. <init-param>
    9. <param-name>forceRequestEncodingparam-name>
    10. <param-value>trueparam-value>
    11. init-param>
    12. <init-param>
    13. <param-name>forceResponseEncodingparam-name>
    14. <param-value>trueparam-value>
    15. init-param>
    16. filter>
    17. <filter-mapping>
    18. <filter-name>characterEncodingFilterfilter-name>
    19. <url-pattern>/*url-pattern>
    20. filter-mapping>

  • 相关阅读:
    DataX从入门实战到精通一文搞定
    vue3+elementui实现表格样式可配置
    交叉编译嵌入式openssl,关键是在config中指定编译器前缀
    Qt---day4---9.20
    洛谷刷题C语言:数字反转、再分肥皂水、三角形面积、Apples Prologue/苹果和虫子、数的性质
    FASTRTPS(publisher-subscriber)实践及问题
    第5章-宏观业务分析方法-5.3-主成分分析法
    linux系统Docker容器Dockerfile简单描述
    设计模式(12)状态模式
    气传导和骨传导耳机哪个好?骨传导耳机优点更多
  • 原文地址:https://blog.csdn.net/MinggeQingchun/article/details/123586046