SpringMVC环境搭建及参数传递

2019-04-01  本文已影响0人  Unclezs

一、环境搭建

1.创建maven-web工程:目录结构

在这里插入图片描述

2.导入maven坐标

<properties>
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <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>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
    </dependency>
  </dependencies>

3.编写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.unclezs.controller"/>
    <!--视图解析器-->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--开启mvc注解支持-->
    <mvc:annotation-driven/>
</beans>

4.编写web.xml

<!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>
  <!--过滤器解决中文乱码-->
  <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>
  <!--拦截器初始化-->
  <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:springmvc.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>

5.控制类

@Controller
public class HelloController {
    @RequestMapping(path = "/hello")
    public String sayHello(){
        System.out.println("hello springMvc");
        return "success";
    }
}

6.测试

访问http://localhost:8080/hello即可跳转success.jsp

二、参数绑定

SpringMVC的参数绑定只需要再Controller的方法参数上写对应的参数名字即可

1.普通参数

接收提交的参数,并绑定到控制器方法的参数上

控制器类
@Controller
public class HelloController {
    @RequestMapping(path = "/hello")
    public String sayHello(String username,String password){
        System.out.println("username:"+username+"-- password:"+password);
        return "success";
    }
}
参数提交格式
<form action="/hello" method="post">
    <input type="text" name="username"/>
    <input type="text" name="password"/>
    <button type="submit">提交</button>
</form>

2.普通JacaBean参数

参数对象User.java
public class User {
    private String username;
    private String password;
    //getter setter 省略
 }
控制器对应方法
  @RequestMapping(path = "/user")
    public String bindParams(User user){
        System.out.println(user);
        return "success";
    }
参数提交方式
<form action="/user" method="post">
    <input type="text" name="username"/>
    <input type="text" name="password"/>
    <button type="submit">提交</button>
</form>

3.POJO参数(plain ordinary java object)

实体类
public class User {
    private String username;
    private String password;
    private List<Account> accounts;
    private Map<String,Account> accountMap;
}
public class Account {
    private int id;
    private double money;
}
表单提交格式
<form action="/user" method="post">
    <input type="text" name="username"/>
    <input type="text" name="password"/>
    <input type="text" name="accounts[0].id"/>
    <input type="text" name="accounts[0].money"/>
    <input type="text" name="accountMap['one'].id"/>
    <input type="text" name="accountMap['one'].money"/>
    <button type="submit">提交</button>
</form>
控制器
 @RequestMapping(path = "/user")
    public String bindParams(User user){
        System.out.println(user);
        return "success";
    }
结果集
User{username='15023814323', password='uncle924', accounts=[Account{id=123, money=213.0}], accountMap={one=Account{id=312, money=312.0}}}

4.获取原生servlet-API

与参数绑定相同格式,只需要将需要的api当作参数写在Controller参数列表即可

    @RequestMapping(path = "/servlet_api")
    public String bindParams(HttpServletRequest request){
        System.out.println(request);
        return "success";
    }

5.自定义类型转换器

转换器类

需要实现Converter接口

public class MyDateConvert implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        if(StringUtils.isEmpty(source)){
            throw new RuntimeException("数据不能为空");
        }
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return df.parse(source);
        } catch (ParseException e) {
            throw new RuntimeException("时间字符串解析错误");
        }
    }
}

注册转换器

再springmvc.xml中添加

<!--注册转换器-->
    <bean id="ConversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.unclezs.convert.MyDateConvert"/>
            </set>
        </property>
    </bean>
    <!--开启mvc注解支持-->
    <mvc:annotation-driven conversion-service="ConversionService"/>
上一篇 下一篇

猜你喜欢

热点阅读