初识Spring MVC

初识Spring MVC

                                        ——Javee

老规矩,新建一个maven项目,引用Spring mvc框架之后,先输出一个Hello world看看<手动滑稽脸>

新建好项目,修改pom.xml文件如下:

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.5.RELEASE</version>
</dependency>

添加web.xml文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <display-name>Archetype Created Web Application</display-name>
  <!--设置编码-->
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>mymvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!-- 设置要加载的核心xml -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mymvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
   <!--设置错误页面-->
  <error-page>
    <error-code>404</error-code>
    <location>/error.html</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/error.html</location>
  </error-page>
</web-app>

在main文件夹下添加java和resource文件夹,和之前一样分别设置为根

新建java->com->seecen->mvc->controller->HelloController.java

package com.seecen.mvc.controller;

import com.seecen.mvc.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
* @Author Javee
* @Date 2019/9/23 9:48
* @Description
*/
@Controller
@RequestMapping("/")
public class HelloController {
    @RequestMapping("index")
    public String helloMethod(){
        System.out.println("进入后台控制层!");
        return "/index.jsp";
    }
}

新建resource->spring-mvc.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="com.seecen.mvc.controller"/>
    <!-- 开启扫面(包含其他) -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

新建或修改webapp->index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h1>hello world</h1>
</body>
</html>

新建webapp->error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>错误</title>
</head>
<body>
    <h1>报错啦!!!</h1>
</body>
</html>

好,接下来添加tomcat,然后运行,就可以看到helloworld啦~~~

接下来我们看看spring mvc如何传值,我们修改webapp->index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/index.action" method="post">
        消息:<input type="text" name="message">
        用户名:<input type="text" name="userName">
        <input type="submit">
    </form>
</body>
</html>

修改java->com->seecen->mvc->controller->HelloController.java

package com.seecen.mvc.controller;

import com.seecen.mvc.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
* @Author Javee
* @Date 2019/9/23 9:48
* @Description
*/
@Controller
@RequestMapping("/")
public class HelloController {
    @RequestMapping("index")
    public String helloMethod(String message, User user, HttpSession session){
        System.out.println(session);
        System.out.println("进入后台控制层!接收到message数据:" + message);
        System.out.println("进入后台控制层!接收到user数据:" + user.getUserName());
        return "hello";
        //return "redirect:/page/hello.jsp";    //重定向
    }

    @RequestMapping("method2")
    public ModelAndView method2(@RequestParam("message") String aa, @RequestParam("number") int bb){
        //注意,上面参数中,如果变量名和传入的变量名不一样的话,就要加上映射,如果一样,就不用加
        System.out.println(aa);
        System.out.println(bb);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello");
        mv.addObject("message", aa);
        mv.addObject("number", bb);
        return mv;
    }

    @RequestMapping("method3/{message}/{number}")
    public ModelAndView method3(@PathVariable("message") String aa, @PathVariable("number") int bb){
        System.out.println(aa);
        System.out.println(bb);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello");
        mv.addObject("message", aa);
        mv.addObject("number", bb);
        return mv;
    }

    @GetMapping("method4")
    @ResponseBody   //将返回的对象转为Json
    public User method4(){
        User user = new User();
        user.setUserName("Javee");
        user.setAge(18);
        return user;
    }
}

修改resource->spring-mvc.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="com.seecen.mvc.controller"/>
    <!-- 开启扫面(包含其他) -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 转发视图页面添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- action中return的页面的前缀 -->
        <property name="prefix" value="/page/" />
        <!-- action中return的页面的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

新建java->com->seecen->mvc->pojo->User.java

package com.seecen.mvc.pojo;

/**
* @Author Javee
* @Date 2019/9/23 10:54
* @Description
*/
public class User {
    private String userName;
    private Integer age;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

修改pom.xml

<?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>com.seecen</groupId>
  <artifactId>mymvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>mymvc 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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.8</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.8</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>

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

  <build>
    <finalName>mymvc</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>

运行即可,可以通过页面传参或者URL传参都可以看见效果~

接下来看看上传文件吧~

新建java->com->seecen->mvc->controller->FileController.java

package com.seecen.mvc.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
* @Author Javee
* @Date 2019/9/23 17:08
* @Description
*/
@RestController
public class FileController {
    @PostMapping("/upload")
    public String doUpload(MultipartFile myfile) throws IOException {
        File file = new File("D:" + File.separator + myfile.getOriginalFilename());
        System.out.println("myfile:" + myfile);
        System.out.println("file:" + file);

        if(!file.exists()) file.createNewFile();
        myfile.transferTo(file);
        return "success";
    }
}

pom.xml中添加

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

修改resource->spring-mvc.xml

<!-- 上传文件解释器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置默认编码 -->
    <property name="defaultEncoding" value="utf-8"></property>
    <!-- 上传文件最大大小5M-->
    <property name="maxUploadSize" value="5242440"></property>
</bean>

新建webapp->upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload.action"
          enctype="multipart/form-data" method="post">
        <input type="file" name="myfile">
        <input type="submit">
    </form>
</body>
</html>

然后运行项目,访问localhost:8080/upload.jsp就可以啦~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值