SpringMVC笔记1

2019-08-09 00:00:00 笔记 SpringMvc

SpringMVC是一个一种基于Java的实现MVC设计模型的请求驱动类型的轻量级web框架

SpringMVC的入门案例

《SpringMVC笔记1》

2.导入相关jar包

<?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>cn.itcast</groupId>
  <artifactId>springmvc_day01_01_start</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day01_01_start 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>

      <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>
    <finalName>springmvc_day01_01_start</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3,在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>

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

4.编写控制器类

package cn.itcast.controller;

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

//控制器类
@Controller
public class HelloController {
    //用来接收请求
    @RequestMapping(path = "/hello")
    public String sayHello(){
        System.out.println("Hello SpringMVC");
        return "success";
    }
}

5.开启扫描注解

<?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
        http://www.springframework.org/schema/mvc ">
    <!--开启注解扫描-->
    <context:component-scan base-package="cn.itcast"></context:component-scan>

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

    <!--开启SpringMVC框架的支持-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

6.编写两个JSP

首页

<%--
  Created by IntelliJ IDEA.
  User: Yuan
  Date: 2019/7/21
  Time: 14:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hello">入门程序</a>
</body>
</html>

成功页面

<%--
  Created by IntelliJ IDEA.
  User: Yuan
  Date: 2019/7/21
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>
</body>
</html>

《SpringMVC笔记1》

入门案例的流程总结

1.服务器启动,加载配置

《SpringMVC笔记1》

2.DispatcherServlet对象创建

《SpringMVC笔记1》

3.springmvc.xml会开启注解扫描

4.找到HelloController,把他变成对象,加载进入IOC容器当中,

5.InternalResourceViewResolver视图解析器也会变成对象,谁调用该对象,就会帮他跳转页面《SpringMVC笔记1》

RequestMapping注解的作用:用于建立请求URL和处理请求方法之间的对应关系,注解位置用在方法上或者类上

请求参数绑定入门

1.请求地址携带参数username

<body>
    <%--请求参数绑定--%>
    <a href="param/testParam?username=hehe">请求参数绑定</a>
</body>

2.方法带有参数username

package cn.itcast.controller;

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

@Controller
@RequestMapping("/param")
public class ParamController {
    //请求参数绑定入门
    @RequestMapping("/testParam")
    public String testParam(String username){
        System.out.println("执行了....");
        System.out.println(username);
        return "success";
    }
}

3.自动给方法的参数赋值

//输出结果
//执行了....   
//hehe

配置解决中文乱码的过滤器

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

引用类型的封装

public class User implements Serializable {
    private String uname;
    private String age;
}

《SpringMVC笔记1》

集合类型封装

《SpringMVC笔记1》

编写自定义类型转换器

//两个泛型,S表示字符串,T表示想要转换的类型
public interface Converter<S, T> 
    

1.实现接口Converter

package cn.itcast.utils;

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

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//字符串转日期
public class StringToDateConverter implements Converter<String, Date> {
    @Override
    //实现接口方法
    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.配置自定义类型转换器

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

3.开启SpringMVC框架的支持

<!--开启SpringMVC框架的支持-->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

《SpringMVC笔记1》

常用注解

RequestParam注解

作用:把请求中指定名称的参数给控制器中的形参赋值

属性:

value,请求参数中的名称,

required:请求参数中是否必须提供此参数,默认值:true《SpringMVC笔记1》

RequestBody注解

作用:用于获取请求体内容,直接使用得到是key=value&key=value…结构的数据get请求不适用(get请求没有请求体,把参数都封装到地址栏上)

属性:

required:是否必须有请求体,默认值true,当取值为true时,get请求会报错,如果取值为false,get请求得到是null

PathVariable注解

作用:用于绑定url中的占位符,例如:请求url中/delete{id},这个{id}就是url占位符。url支持占位符是spring3.0之后加入的。是springmvc支持rest风格URL的一个重要标志。

属性:

value:用于指定url中占位符名称

required:是否必须提供占位符

 @RequestMapping("/testPathVariable/{sid}")
    public String testPathVariable(@PathVariable(name="sid") String id){
        System.out.println("执行了");
        System.out.println(id);
        return "success";
    }
<a href="anno/testPathVariable/10">testPathvariable</a>

相关文章