安装项目管理工具maven
安装tomcat
这个自行解决即可
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jn7M3CDE-1599060329602)(https://i.loli.net/2020/08/26/m6xIgDZ8AnYbrMv.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UlC0SiCr-1599060329605)(https://i.loli.net/2020/08/26/3tKaAV7o2zRDjZX.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tj3AJHAb-1599060329608)(https://i.loli.net/2020/08/26/3tKaAV7o2zRDjZX.png)]
注意事项
1.maven工程打包方式为war包
2.要使用eclipse自带的工具帮我们生成web.xml
在webapp下写一个index.jsp
内容如下:
<%@ page pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> hello world </h1> </body> </html>启动项目
访问:localhost:8080/springmvc-cli
页面出现
helloworld
证明springmvc-cli脚手架配置成功实体类
package com.shaoming.model; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; public class User { private Integer id; private String name; private Integer age; private String sex; @JsonFormat(pattern = "yyyy/MM/dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date birthday; public User(Integer id, String name, Integer age, String sex, Date birthday) { super(); this.id = id; this.name = name; this.age = age; this.sex = sex; this.birthday = birthday; } public User() { super(); } 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 Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + "]"; } }返回数据的vo(为了测试用的)
package com.shaoming.model; import java.util.HashMap; import java.util.Map; public class Msg { //状态码 100 成功 200 失败 private int code; //提示信息 private String msg; //用户要返回给客户端的数据 private Map<String,Object> data = new HashMap<String, Object> (); //当前对象添加用户要返回给客户端的数据 public Msg add(String key,Object value){ this.getData ().put (key,value); return this; } //执行成功 public static Msg success(){ Msg result = new Msg (); result.setCode (100); result.setMsg ("执行成功!"); return result; } //执行失败 public static Msg fail(){ Msg result = new Msg (); result.setCode (200); result.setMsg ("执行失败!"); return result; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } } 测试controller package com.shaoming.controller; import java.util.Date; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.shaoming.model.Msg; import com.shaoming.model.User; @Controller @RequestMapping("/mvc") public class HelloController { /** * 1.返回jsp页面 * * @return */ @RequestMapping("/tojsp") public String toJspPage() { return "hello"; } /** * 2.返回字符窜,看是否有中文乱码 produces="text/html;charset=UTF-8;"这段配置解决返回字符串中文乱码的问题 */ @RequestMapping(value = "/tostring", produces = "text/html;charset=UTF-8;") @ResponseBody public String toString() { return "返回string字符窜,看是否有中文乱码"; } /** * 3.返回json格式的字符窜 * * @ReponseBody这个注解的使用 */ @RequestMapping("/tojson") @ResponseBody public Msg tojson() { return Msg.success().add("返回内容为", new User(1, "user的name", 18, "男", new Date())); } /** * 4.传递json数据 * * @RequestBody这个注解的使用 传递json成功,返回到成功页面 请求的测试数据 * {"id":1,"name":"user的name","age":19,"birthday":"2020/08/26 00:08:57","sex":"男"} */ @RequestMapping(value = "/injson", method = RequestMethod.POST) public String injson(@RequestBody User user) { System.out.println(user); return "success"; }引入相关的依赖
<!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency>springmvc配置文件springmvc-config.xml配置文件上传的相关的参数
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> <!-- 启用是为了推迟文件解析,以便捕获文件大小异常 --> <property name="resolveLazily" value="true" /> <property name="uploadTempDir" value="fileUpload/temp" /> </bean>在src/main/webapp下建一个文件夹测试文件上传
我这里定义的是upresource
准备三个文件,一个压缩包,一个图片,一个.md文档oracle.md
commons-beanutils-1.9.3-bin.zip
Koala.jpg
写controller方法,进行文件上传 /** * 文件上传 * * @param myfiles * @param request * @return * @throws IOException */ @RequestMapping(value="/upload",produces = "text/html;charset=UTF-8;",method=RequestMethod.POST) @ResponseBody public String upload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException { for (MultipartFile file : myfiles) { // 此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了 if (file.isEmpty()) { System.out.println("文件未上传!"); } else { // 得到上传的文件名 String fileName = file.getOriginalFilename(); // 得到服务器项目发布运行所在地址 String path1 = request.getSession().getServletContext().getRealPath("upresource") + File.separator; // 此处未使用UUID来生成唯一标识,用日期做为标识 //String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName; // 查看文件上传路径,方便查找 String path = path1 + "/" + fileName; System.out.println(path); // 把文件上传至path的路径 File localFile = new File(path); file.transferTo(localFile); } } return "文件上传成功"; }说明:
String path1 = request.getSession().getServletContext().getRealPath(“upresource”) + File.separator;
path1就是项目文件上传路径
String path = path1 + “/” + fileName;
path1是需要上传后文件的路径
文件下载的jsp页面
up.jsp
<%@ page pageEncoding="utf-8"%> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form action="http://localhost:8080/springmvc-cli/mvc/upload" method="post" enctype="multipart/form-data"> 文件1: <input type="file" name="myfiles" /><br /> 文件2: <input type="file" name="myfiles" /><br /> 文件3: <input type="file" name="myfiles" /><br /> <input type="submit" value="上传"> </form> </body> </html>说明:
form表单重要的配置
method=“post” enctype=“multipart/form-data”
(1)post表示文件上传是一个post请求
(2)enctype表示这是文件上传
说明:
为了测试,使用超链接的方式下载上传目录下已有的文件
下载的jsp页面
down.jsp
<%@ page pageEncoding="utf-8"%> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>下载页面</title> <!--引入jQuery--> <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <body> <a href="http://localhost:8080/springmvc-cli/mvc/download?fileName=oracle.md">下载oracle.md文档</a> <hr> <a href="http://localhost:8080/springmvc-cli/mvc/download?fileName=commons-beanutils-1.9.3-bin.zip"> 下载commons-beanutils-1.9.3-bin.zip压缩文件</a> <hr> <a href="http://localhost:8080/springmvc-cli/mvc/download?fileName=Koala.jpg">下载Koala.jpg图片</a> <hr> </body> </html> 下载文件的controller方法 /** * 文件下载 * * @param fileName * @param request * @param response * @return */ @RequestMapping("/download") public String download(String fileName, HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); try { //new String(fileName.getBytes(), "iso-8859-1")是为了防止文件出现中文乱码 response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(), "iso-8859-1")); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { String path = request.getSession().getServletContext().getRealPath("image") + File.separator; InputStream inputStream = new FileInputStream(new File(path + fileName)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 这里主要关闭。 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 返回值要注意,要不然就出现下面这句错误! // java+getOutputStream() has already been called for this response return null; }tStackTrace(); } try { String path = request.getSession().getServletContext().getRealPath(“image”) + File.separator; InputStream inputStream = new FileInputStream(new File(path + fileName));
OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 这里主要关闭。 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 返回值要注意,要不然就出现下面这句错误! // java+getOutputStream() has already been called for this response return null; }