欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC学习(一)——环境搭建、请求参数

程序员文章站 2022-07-10 21:13:53
1...

原理图:

SpringMVC学习(一)——环境搭建、请求参数

环境搭建

pom.xml

<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>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>
      <scope>provided</scope>
    </dependency>

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

webapp/WEB-INF/web.xml:主要用于配置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>
    <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>



  <!--配置解决中文乱码的过滤器-->
  <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>

resources/springmvc.xml:上下文环境配置contextConfig,如:注解设置,配置视图解析器,处理器映射器,适配器。

<?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="cn.ispringmvc"/>

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

   
      <!-- 开启SpringMVC框架注解的支持并自动加载处理器映射器和处理器适配器 -->
      <mvc:annotation-driven />
</beans>

 建立Java类:控制器,用于处理请求,用到了@Controller注解和@RequestMapping注解

@Controller
public class HelleController {

    //建立请求URL与处理请求方法之间的对应关系
    @RequestMapping(path = "/hello")
    public String sayHello(){
        System.out.println("Hello StringMVC");
        return "success";
    }

   
}

注意:JSP文件内的参数请求路径开头无“/”符号,@RequestMapping注解也可应用于类上,用于分级参数请求路径

<a href="hello">入门程序</a>
@RequestMapping(path = "/hello")


请求参数绑定

(一)普通参数

<a href="hello?username=hehe&password=123">入门程序</a>
public String sayHello(String username ,String password)

(二)数据封装进javaBean类中

 1)其中封装类Account中包含引用属性user,uname和age为User属性,采用user.uname的形式表达

public class Account implements Serializable{

    private String username;
    private String password;
    private Double money;

    private User user;

//get,set,toString方法
}

 JSP文件:

   <%--把数据封装Account类中--%>
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
        用户姓名:<input type="text" name="user.uname" /><br/>
        用户年龄:<input type="text" name="user.age" /><br/>
        <input type="submit" value="提交" />
    </form>

 Controller类:

@Controller
@RequestMapping("/param")
public class ParamController {
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
    }
}

2)封装类中包含集合类型属性

    private List<User> list;
    private Map<String,User> map;

 JSP文件:uname和age封装成user放进list[0](map['one'])中

  用户姓名:<input type="text" name="list[0].uname" /><br/>
        用户年龄:<input type="text" name="list[0].age" /><br/>

        用户姓名:<input type="text" name="map['one'].uname" /><br/>
        用户年龄:<input type="text" name="map['one'].age" /><br/>

自定义类型转换器:用于实现对请求参数的类型转换,便于封装

请求参数是String类型,springMVC会自动进行许多已定义好的类型转换。

例: private Integer password在href="hello?username=hehe&password=123"时,123为String类型

1)类型转换器继承自接口Converter,举例String转Date

public class StringToDateConverter implements Converter<String,Date>{

    /**
     * String source    传入进来字符串
     * @param source
     * @return
     */
    public Date convert(String source) {
        // 判断
        if(source == null){
            throw new RuntimeException("请您传入数据");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // 把字符串转换日期
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("数据类型转换出现错误");
        }
    }

}

2)于springmvc.xml中配置自定义完成的类型转换器

  <!--配置自定义类型转换器,id可自定义,name="converters"为ConversionServiceFactoryBean的属性-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.ispringmvc.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>
   

    <!-- 开启SpringMVC框架注解的支持,使类型转换器生效-->
    <mvc:annotation-driven   conversion-service="conversionService"/>

 

本文地址:https://blog.csdn.net/ZhenHYang/article/details/107261598

相关标签: SpringMVC SpringMVC