SpringBoot 创建SpringMVC项目 liuxm

1.pom文件

<?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.example</groupId>
  <artifactId>myweb</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>myweb Maven Webapp</name>
  <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>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath />
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--需要引入 jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>
    <!--需要引入 tomcat-embed-jasper-->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

2.application.properties文件

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

3.创建jsp页面

在文件夹 src/main/webapp/WEB-INF/jsp/下创建index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    hello jsp
    <p>${userInfo.name}</p>
</body>
</html>

常用标签库

<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

4.创建controller

import com.example.myweb.domain.UserInfo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 返回ModelAndView ,视图为modelAndView实例中的view值
     *
     * @return
     */
    @RequestMapping(value = "/mav", method = RequestMethod.GET)
    public ModelAndView getModelAndView() {

        ModelAndView mav = new ModelAndView("modelandview_demo");
        //mav.setViewName("admin"); //初始化时使用无参构造函数时,可使用此方法设置视图

        mav.addObject("data", new UserInfo());
        mav.addObject("time", new Date());

        return mav;
    }

    /**
     * 返回string,视图为返回值
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/model", method = RequestMethod.GET)
    public String getModel(Model model) {
        //方法中的Model是接口,也可换成 ModelMap

        model.addAttribute("data", new UserInfo());
        model.addAttribute("time", new Date());

        return "model_demo";
    }

    /**
     * 返回void时,视图为请求名
     *
     * @param model
     */
    @RequestMapping("/void_demo")
    public void getWelcome(Model model) {

        model.addAttribute("time", new Date());
    }

    /**
     * 返回map ,视图为请求名
     *
     * @return
     */
    @RequestMapping("/map_demo")
    public Map<String, Object> getMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("key1", "value-1");
        map.put("key2", "value-2");
        map.put("time", new Date());
        return map;
    }

    /**
     * 返回对像 ,视图为请求名
     * jsp访问数据是userInfo
     * 等价于 model.addAttribute("userInfo", 返回值);
     *
     * @return
     */
    //@ModelAttribute("data")
    @RequestMapping("/obj_demo")
    public UserInfo getObj() {
        return new UserInfo(1, "demo", new Date());
    }

    /**
     * 返回json
     *
     * @return
     */
    @RequestMapping("/json_demo")
    @ResponseBody
    public UserInfo getJson() {
        return new UserInfo(1, "demo", new Date());
    }

    /**
     * 返回json
     *
     * @return
     */
    @RequestMapping("/mydemo")
    public ResponseEntity<Map<String, Object>> responseEntity() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("message", "Hello Wrold");
        return new ResponseEntity(map, HttpStatus.OK);
    }

    /**
     * post json
     *
     * @param user
     * @return
     */
    @PostMapping("/useradd")
    public String postJson(@RequestBody UserInfo user) {
        return "newuser";
    }


    /**
     * post form
     *
     * @param name
     * @param date
     * @return
     */
    @RequestMapping(value = "/user/save", method = RequestMethod.POST)
    private String doSave(@RequestParam("name") String name, @RequestParam("date") Date date) {
        return "success";
    }

    /**
     * post form
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/save", method = RequestMethod.POST)
    private String doSave(@ModelAttribute UserInfo user) {
        //可以不添加@ModelAttribute注解
        return "success";
    }

    /**
     * 上传文件
     *
     * @param file
     * @param req
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {
        //也可以把MultipartFile 定义为一个对像的属性进行获取
        //file.transferTo(new File("save.data"));

        // 判断文件是否为空,空则返回失败页面
        if (file.isEmpty()) {
            return "failed";
        }
        // 获取文件存储路径(绝对路径)
        String path = req.getServletContext().getRealPath("/upload");
        // 获取原文件名
        String fileName = file.getOriginalFilename();
        // 创建文件实例
        File filePath = new File(path, fileName);
        // 如果文件目录不存在,创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件
        file.transferTo(filePath);
        return "success";
    }

    /**
     * 下载文件
     *
     * @param request
     * @param filename
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET) //匹配的是href中的download请求
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,
                                           Model model) throws IOException {

        String downloadFilePath = "D:\\userUploadFile\\Files";//从我们的上传文件夹中去取

        File file = new File(downloadFilePath + File.separator + filename);//新建一个文件

        HttpHeaders headers = new HttpHeaders();//http头信息

        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");//设置编码

        headers.setContentDispositionFormData("attachment", downloadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息

        return new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.CREATED);

    }


    /**
     * 页面调转
     * @return
     */
    @RequestMapping("/jump")
    public String jump1(){

        //转发方式1
        return "index";

        //转发方式2
        return "forward:index";

        //重定向方式  hello指的是requsrmapping
        return "redirect:index";

    }

    /**
     * 页面跳转2
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/resp")
    public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //转发方式1
        req.getRequestDispatcher("index.jsp").forward(req,resp);

        //转发方式2
        resp.sendRedirect("index.jsp");
    }


}

5.启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
    

6.生成war包发布到容器中

6.1修改pom 打包成war,并修改引用

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <!-- 排除内置容器,排除内置容器导出成 war 包可以让外部容器运行spring-boot项目 -->
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>

6.2 在启动类同级目录创建文件ServletInitializer.java

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}
原文地址:https://www.cnblogs.com/liuxm2017/p/15746899.html