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

SpringMVC笔记1

程序员文章站 2022-06-05 20:23:39
SpringMVC是一个一种基于Java的实现MVC设计模型的请求驱动类型的轻量级web框架 SpringMVC的入门案例 1. 2.导入相关jar包 3,在web.xml中配置前端控制器 4.编写控制器类 5.开启扫描注解 6.编写两个JSP 首页 成功页面 入门案例的流程总结 1.服务器启动,加 ......

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:请求参数中是否必须提供此参数,默认值:trueSpringMVC笔记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>