搭建springmvc脚手架

tech2022-08-25  130

搭建springmvc脚手架

1.准备工作

安装项目管理工具maven

安装tomcat

这个自行解决即可

2.创建一个简单的maven的web工程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(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

3.引入依赖

pom.xml

<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.shaoming</groupId> <artifactId>springmvc-cli</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!-- 集中定义依赖版本号 --> <properties> <junit.version>4.10</junit.version> <spring.version>4.1.3.RELEASE</spring.version> </properties> <dependencies> <!-- 文件上传 --> <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> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Servlet支持Request和Response --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <!-- java对象转换json的工具类 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> </project>

3.springmvc的配置文件

springmvc-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 1.配置前端控制器放行静态资源(html/css/js等,否则静态资源将无法访问) --> <mvc:default-servlet-handler /> <!-- 2.配置注解驱动,用于识别注解(比如@Controller) --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 3.配置需要扫描的包:spring自动去扫描 base-package 下的类, 如果扫描到的类上有 @Controller、@Service、@Component等注解, 将会自动将类注册为bean @Controller public class HelloController{} --> <context:component-scan base-package="com.shaoming.controller"> </context:component-scan> <!-- 4.配置内部资源视图解析器 prefix:配置路径前缀 suffix:配置文件后缀 /WEB-INF/pages/home.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <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> </beans>

4.web.xml配置

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>springmvc-cli</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 配置springmvc的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springmvc核心配置文件的位置 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> </servlet> <!-- 表示匹配除了JSP以外的所有资源,即当浏览器访问服务器时 除了访问JSP,访问其他的资源都会被前端控制器所拦截。 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 处理POST提交的中文参数乱码问题 对GET提交不起作用!! --> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

5.测试项目启动是否成功

在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脚手架配置成功

6.测试springmvc相关基础的功能

准备工作

实体类

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"; }

7.springmvc的文件上传功能

准备工作

引入相关的依赖

<!-- 文件上传 --> <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表示这是文件上传

8.springmvc的文件下载功能

说明:

为了测试,使用超链接的方式下载上传目录下已有的文件

下载的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; }
最新回复(0)