SpringMVC-课程项目案例

需求

  • 添加课程,成功则返回全部课程信息。
  • 查询课程,通过 id 查询对应的课程信息。
  • 修改课程,成功则返回修改之后的全部课程信息。
  • 删除课程,成功则返回删除之后的全部课程信息。

1、创建实体类

package com.southwind.entity;

public class Course {
    private Integer id;
    private String name;
    private Double price;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Course(Integer id, String name, Double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}

2、CourseRepository

package com.southwind.repository;

import com.southwind.entity.Course;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class CourseRepository {
    private static Map<Integer, Course> map;

    static {
        map = new HashMap();
        map.put(1,new Course(1,"Java",6000d));
        map.put(2,new Course(2,"C++",6000d));
        map.put(3,new Course(3,"Python",6000d));
    }

    public void saveOrUpdate(Course course){
        map.put(course.getId(),course);
    }

    public Collection<Course> findAll(){
        return map.values();
    }

    public Course findById(Integer id){
        return map.get(id);
    }

    public void deleteById(Integer id){
        map.remove(id);
    }
}

3、CourseHandler

package com.southwind.controller;

import com.southwind.entity.Course;
import com.southwind.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/course")
public class CourseHandler {
    @Autowired
    private CourseRepository courseRepository;

//    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    @GetMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView("course");
        modelAndView.addObject("list",courseRepository.findAll());
        return modelAndView;
    }

    @DeleteMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id") Integer id){
        courseRepository.deleteById(id);
        return "redirect:/course/findAll";
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") Integer id){
        ModelAndView modelAndView = new ModelAndView("update");
        modelAndView.addObject("course",courseRepository.findById(id));
        return modelAndView;
    }

    @PutMapping("/update")
    public String update(Course course){
        courseRepository.saveOrUpdate(course);
        return "redirect:/course/findAll";
    }

    @PostMapping("/add")
    public String add(Course course){
        courseRepository.saveOrUpdate(course);
        return "redirect:/course/findAll";
    }
}

Spring MVC 文件上传下载

  • 单文件上传

1、pom.xml

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

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

2、JSP

  • input 的 type 设置为 file
  • form 表单的 method 设置为 post
  • form 表单的 enctype 设置为 multipart/form-data
<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-08-22
  Time: 21:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="img"/>
        <input type="submit" value="上传"/>
    </form><br/>
    <c:if test="${filePath!=null}">
        <h1>上传的图片</h1>
        <img width="300px" src="${filePath}">
    </c:if>
</body>
</html>

3、UploadHandler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UploadHandler {

    @RequestMapping("/upload")
    public String upload(@RequestParam("img") MultipartFile img, HttpServletRequest request){
        if(img.getSize()>0){
            String path = request.getSession().getServletContext().getRealPath("file");
            String fileName = img.getOriginalFilename();
            File file = new File(path,fileName);
            try {
                img.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            request.setAttribute("filePath","/file/"+fileName);
        }
        return "upload";
    }
}

4、springmvc.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

5、web.xml

<servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
  • 多文件上传

1、JSP

<%--
  Created by IntelliJ IDEA.
  User: southwind
  Date: 2019-08-22
  Time: 21:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/uploads" method="post" enctype="multipart/form-data">
        file1:<input type="file" name="imgs"/><br/>
        file2:<input type="file" name="imgs"/><br/>
        file3:<input type="file" name="imgs"/><br/>
        <input type="submit" value="上传"/>
    </form>
    <c:if test="${filePath!=null}">
        <h1>上传的图片</h1>
        <c:forEach items="${filePath}" var="img">
            <img width="300px" src="${img}"/>
        </c:forEach>
    </c:if>
</body>
</html>

2、Handler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UploadsHandler {

    @RequestMapping("/uploads")
    public String uploads(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request){
        List<String> filePath = new ArrayList<>();
        for(MultipartFile img:imgs){
            if(img.getSize()>0){
                String path = request.getSession().getServletContext().getRealPath("file");
                String fileName = img.getOriginalFilename();
                File file = new File(path,fileName);
                try {
                    img.transferTo(file);
                    filePath.add("/file/"+fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        request.setAttribute("filePath",filePath);
        return "uploads";
    }
}

设置文件上传的大小

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 处理文件名中文乱码 -->
  <property name="defaultEncoding" value="utf-8"></property>
  <!-- 多文件上传总大小的上限 -->
  <property name="maxUploadSize" value="10485760"></property>
  <!-- 单文件大小的上限 -->
  <property name="maxUploadSizePerFile" value="1048576"></property>
</bean>






备注:最近来手感,写了个类似Tomcat服务

github地址:https://github.com/cnamep001/my_tomcat.git






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值