spring mvc简单使用
阅读原文时间:2023年07月08日阅读:3

spring mvc

导入servlet、springmvc、Jackson的依赖,编译插件、tomcat

<?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>org.example</groupId>
  <artifactId>springmvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>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.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
    <!--必要的servlet依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!--springmvc的核心依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <!--jackson依赖,用来方便数据转java格式 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.5</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>springmvc</finalName>
    <pluginManagement>
      <plugins>
          <!--jdk的编译插件,用1.8的版本 -->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
          <!--tomcat插件 -->
        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>2.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

先在web.xml上注册中央调度器,这是最关键的

<!--配置DispqtcherServlet -->
<servlet>
    <!--自定义名称,就当个id吧, -->
    <servlet-name>springmvc</servlet-name>
    <!--全限定类名,固定 -->
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <!--大于零代表启动时创建servlet-->
    <load-on-startup>1</load-on-startup>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!--springmvc配置文件的路径 -->
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
</servlet>
<!--配置地址映射,将请求映射到对应的Servlet -->
<servlet-mapping>
    <servlet-name>springmvc</servlet-name><!--上面的中央调度器的名称 -->
    <url-pattern>*.do</url-pattern>
    <!--一般情况不要写/*,这样的话,所有的请求将全部由Spring的DispatcherServlet来处理,显然是不合适的,jsp文件还是应该由Tomcat配置的JSP Servlet来处理 -->
    <!--大概感觉有点像过滤器的作用,代表这个形式的访问地址才经过中央调度器 -->
</servlet-mapping>

接下来就在resources目录里写springmvc的配置文件

当然这里的配置文件的路径就是你在web.xml里指定的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 声明组件扫描器 -->
    <context:component-scan base-package="top.changtong1819.controller"/>
    <!--mvc的注解驱动 -->
    <mvc:annotation-driven/>

    <!--注册视图解析器,用来帮我们自动在文件路径上添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

那么组件扫描器的作用是什么呢

组件扫描(component scanning):

Spring能够从指定的classpath下自动扫描,侦测和实例化具有特定注解的bean。

Spring提供了一下几个注解来标注需要被扫描到的bean:

@Component:标注一个普通的Spring Bean类

@Controller:标注一个控制器组件类

@Service:标注一个业务逻辑组件类

@Repository:标注一个Dao组件类

有了组件扫描器之后,相当于不需要再写bean标签去实例化某个类了,扫描到注解会自动实例化

@Controller//表示当前类是处理类
public class MyController {
    @RequestMapping(value = "/some.do")//表示当前方法为处理器方法,value属性指定URl地址
    public ModelAndView doSome(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("name","changtong");
        mv.addObject("age","21");
        mv.setViewName("show");
        return mv;
    }
}

要返回自定义对象,需要在方法上使用@ResponseBody注解,这里要在springmvc的配置文件上先注册注解驱动,前面已经注册了

@Controller//表示当前类是处理类
public class MyController {
@RequestMapping(value = "/ajax.do")
    @ResponseBody
    public Student doAjax(HttpServletRequest req, HttpServletResponse resp,int age,String name) throws IOException {
        Student stu = new Student();
        stu.setAge(age);
        stu.setName(name);
/*        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(stu);
        resp.getWriter().write(json);*/  //不需要再写这些了
        return stu;//直接返回对象就是json格式
    }
}

使用过滤器,在web.xml里注册

<!--注册过滤器,解决请求乱码的问题 -->
    <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>
        <!-- 强制request请求使用encoding格式-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- 强制response请求使用encoding格式-->
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <!--过滤器所过滤的地址 -->
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>