搭建SpringMvc框架,接收参数

目录

导入Maven依赖:

在resources目录下创建一个SpringMvc的xml文件:

在WebInf目录下创建一个前端控制器开启SpringMvc拦截:

编写代码:控制器

参数的传递:

接收普通数据类型参数:

接收数组或集合:

接收自定义的参数类型:

对象套对象:


导入Maven依赖:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.xrc</groupId>
  <artifactId>java_SpringMVC</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>java_SpringMVC Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--配置版本锁定-->
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--servlet的坐标需要加scope范围为provided,表示仅仅提供编译使用,不会发布到war包中,
    因为tomcat中已经有servlet的jar了,否则会冲突,启动就会报错。-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>


  <build>
    <plugins>
      <!--tomcat插件-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <port>8080</port><!--端口号-->
          <path>/</path><!--项目路径-->
          <uriEncoding>UTF-8</uriEncoding>
        </configuration>
      </plugin>
      <!--jdk版本插件-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <target>1.8</target>
          <source>1.8</source>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

创建一个静态页面用来访问

在resources目录下创建一个SpringMvc的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!--开启注解扫描-->
    <context:component-scan base-package="com"></context:component-scan>


    <!--放行静态资源-->
    <!--开启注解驱动-->
    <mvc:annotation-driven/>

    <!--配置放行资源路径mapping:访问路径,location:资源路径-->
    <!--<mvc:resources mapping="/img/**" location="/img/"/>
    &lt;!&ndash;比如还有其他的,太多的话,就要写很多,mvc提供了一个简单地写法&ndash;&gt;
    <mvc:resources mapping="/js/**" location="/js/"/>-->

    <!--springMVC提供了一个通用的放行方式,用于取代上面繁琐的静态资源放行代码-->
    <mvc:default-servlet-handler/>


在WebInf目录下创建一个前端控制器开启SpringMvc拦截:

爆红不是错误,不影响运行,只是写的顺序不对

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--利用前端控制器 读取配置文件springmvc.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--设置servlet实例化时间  1为服务器时启动  不再是请求-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

编写代码:控制器

test01的方法上面添加RequestMapper相当于子路径,

package com.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/*编写关于user增删改查控制器
接受前端请求,跳转到对应页面
* */
@Controller//创建注解,放到spring容器里
//@RequestMapping("/user")//指明访问路径,完整路径:类路径+方法路径,这里把类路径注释了,是为了方便请求,
public class UserController {
    @RequestMapping("/add")
    public String test01(){
        System.out.println("添加user");
        return "success.jsp"; //这个是跳转到创建的页面
    }
    @RequestMapping("/delete")
    public String test02(){
        System.out.println("删除user");
        return "success.jsp";
    }
}

参数的传递:

接收普通数据类型参数:

参数名一样:

//1.接受普通参数
    //1.1参数名称相同,直接绑定
    //http://localhhost:8080/test01?name=jack
    @RequestMapping("/test01")
    public String test01(String name){
        System.out.println("name = " + name);
        return "success.jsp";
    }

参数名不一样:

//请求参数与形参名不同时,需要绑定依赖于注解,
    //RequestParam加了这个注解,就要携带参数,不然后面就要跟一个require
    // require;默认为true,必须携带参数,false可以不用带参数,
    //defaultValue:自己带的参数,如果你携带参数就用携带的,如果没有就用我自己定义的赋值给形参
    //http://localhhost:8080/test01?name=jack
    @RequestMapping("/test02")
    public String test02(@RequestParam(name = "name",required = true,defaultValue = "xrc") String username){
        System.out.println("name = " + username);
        return "success.jsp";
    }

有多个参数:

//多个参数的情况
    //http://localhhost:8080/test01?name=jack&age=12&address=北京
    @RequestMapping("/test03")
    public String test03(@RequestParam(name = "name",required = true,defaultValue = "xrc") String username,Integer age,String address){
        System.out.println(username);
        System.out.println(age);
        System.out.println(address);
        return "success.jsp";
    }

接收数组或集合:

数组:

//2.接受数组/集合
    //http://localhhost:8080/test01?nicks=jack&nicks=tom&nicks=siri
    //数组赋值只需要保证请求参数名称一样和形参一样一致即可,然后key一样的键值对就会被封装到数组中
    @RequestMapping("/test03")
    public String test04(String[] nicks){
        System.out.println(Arrays.toString(nicks));
        return "success.jsp";
    }

集合:

//list集合
    //接受list集合,写法和集合一样,但是需要添加注解,只写一个属性的话,可以把name省略
    //http://localhhost:8080/test01?list=jack&list=tom&list=siri
    @RequestMapping("/test05")
    public String test05(@RequestParam("list") List<String> list){
        System.out.println(list);
        return "success.jsp";
    }

接收自定义的参数类型:

student定义的类是name和age

//接受自定义数据类型
    //我们用的参数必须和自定义类型的属性一样例如:name,age,如果类型不一样,那么参数就传不进去
    //http://localhhost:8080/test01?name=jack&age=12
    @RequestMapping("/test06")
    public String test06(student student){
        System.out.println(student);
        return "success.jsp";
    }
//如果多出一个形参与对象属性名一致,那么会给他们同时赋值
    //http://localhhost:8080/test01?name=jack&age=12
    @RequestMapping("/test07")
    public String test07(student student,Integer age){
        System.out.println(student);
        return "success.jsp";
    }

对象套对象:

student也是一个对象 ,teacher里面包含了一个student对象

//封装复杂的数据类型,对象里面还有对象
    //对象套对象:属性名.属性名=value
    //http://localhhost:8080/test01?className=jack&gender=man&stu.name=tom&stu.age=20
    @RequestMapping("/test08")
    public String test08(Teacher teacher){
        System.out.println(teacher);
        return "success.jsp";
    }

对象里套集合:

//对象里套集合
    //如果集合中装的是普通字符串,写法:属性名【索引】=xxx
    //http://localhhost:8080/test01?className=jack&gender=man&strs[0]=aa&strs[1]=bb
    @RequestMapping("/test09")
    public String test09(Teacher teacher){
        System.out.println(teacher);
        return "success.jsp";
    }

如果集合中套的是另一个对象:

 //对象里套集合,集合里套对象,写法:大属性名【索引】.小属性名=xxx
    //http://localhhost:8080/test01?className=jack&gender=man&stuList[0].name=tom&stuList[0].age=12&stuList[1].name=jack
    //stuList[0].name=tom&stuList[0].age=12&&stuList[1].name=jack
    @RequestMapping("/test10")
    public String test10(Teacher teacher){
        System.out.println(teacher);
        return "success.jsp";
    }

对象套map集合:

//对象套map集合,写法:属性名[“key”]=value
    //http://localhhost:8080/test11?maps["1"]=tom&maps["2"]=jack
    @RequestMapping("/test11")
    public String test11(Teacher teacher){
        System.out.println(teacher);
        return "success.jsp";
    }

后面太多了,懒得写了,随用随查吧

哎,还是简写一下吧!

map集合的value里是对象:

        写法:大属性名【“key”】.小属性名=value

//http://localhhost:8080/test11?maps["0"].name=tom&maps["0"]age=12&maps["1"].name=jack&maps["1"]age=12

传入日期类型: 

//传入日期类型,默认解析格式:yyyy/MM/dd
    //http://localhhost:8080/test12?date=2023/5/23成功
    //http://localhhost:8080/test12?date=2023-5-23失败
    //解决:前提是开启了注解驱动
    //有两种解决方式
    //1.使用注解重新声明解析原则
    @RequestMapping("/test12")
    public String test12(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date){
        System.out.println(date);
        return "success.jsp";
    }

2.自定义类型转换器

//传入日期类型,默认解析格式:yyyy/MM/dd
    //http://localhhost:8080/test12?date=2023/5/23成功
    //http://localhhost:8080/test12?date=2023-5-23失败
    //解决:前提是开启了注解驱动,有两种方法
    //1.使用注解重新声明解析原则
    //2.自定义类型转换器
    //2.1编写java类,实现Converter接口,自定义转换规则
    //2.2将自定义类型转换器,注册为bean(spring容器中的对象)
    //2.3将自定义类型转换器加载带conversionServiceFactoryBean类
    //2.4将Converter加载到注解驱动中
    @RequestMapping("/test12")
    public String test12(/*@DateTimeFormat(pattern = "yyyy-MM-dd")*/ Date date){
        System.out.println(date);
        return "success.jsp";
    }

自定义类型转换器

package com.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

/*
* 自定义类型转换器,实现Converter接口,<接受的数据类型,要转换成的数据类型>
convert方法:编写转换规则
* */
public class MyConvertrer implements Converter<String,Date> {


    @Override
    public Date convert(String source) {
        //如果字符串==null或者长度为0返回null
        if (source==null || source.length()==0){
            return null;
        }

        //通过校验
        SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleFormatter.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            //如果与异常直接转换失败
            return null;
        }
        return date;
    }
}

配置文件:

 获取request,response,session

//获取request。response,session
    @RequestMapping("/test12")
    public String test13(HttpRequest request, HttpResponse response, HttpSession session){
        System.out.println(request);
        System.out.println(response);
        System.out.println(session);
        return "success.jsp";
    }

获取请求头信息:

//获取请求头信息
    @RequestMapping("/test12")
    public String test14(@RequestHeader("Accept-Language") String head){
        
        System.out.println(head);
        return "success.jsp";
    }

获取cookie:

 //获取cookie
    //CookieValue将指定的cookie信息取出来,复制给cookie形参
    @RequestMapping("/test12")
    public String test15(@CookieValue("JSESSIONID") String cookie){

        System.out.println(cookie);
        return "success.jsp";
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值