admin 管理员组文章数量: 1087678
spring 个人使用文档
前言:
本开发springmvc文档,仅供参考!!
概述
1.springMVC执行流程
2.springMVC集成流程
3.controller
- 返回值有哪些?
- 参数有哪些?怎么用
4.springmvc访问静态资源
5.springmvc文件上传
springMVC执行流程
解释:
前端控制器: org.springframework.web.servlet.DispatcherServlet
页面控制器: @Controller
模型: @RequestMapping
渲染视图: org.springframework.web.servlet.view.InternalResourceViewResolver
springMVC集成过程
pom依赖
1.spring-webmvc
2.jstl→渲染识图中的viewClass需要
1.配置org.springframework.web.servlet.DispatcherServlet
模板
<!--所有的用户请求都交给spring处理--><servlet-mapping><servlet-name>all</servlet-name><url-pattern>/</url-pattern></servlet-mapping><servlet><servlet-name>all</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--初始化前端控制器的路径--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:app.xml</param-value></init-param></servlet>
2.配置spring-beans.schema.xml
添加context的schema
xmlns:context=""
xsi:schemaLocation里面添加:
.xsd
初始化contextclass
base-package填bean和controller文件夹的根目录
<!--初始化contextClass--><context:component-scan base-package="txk.*"></context:component-scan>
渲染视图配置
prefix以…开头
suffix以…结束
<!--渲染视图--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean>
controller的方法
返回值有哪些?
1. void
业务场景:不进行跳转服务器内部跳转,直接在@RequestMapping定义的path下定义输出,就像servlet那样
例:
@RequestMapping(value = "/void.do")public void Test(Writer writer){try {writer.write("voidTest");} catch (IOException e) {e.printStackTrace();}}
2. String
说明:返回值为跳转path,如return “index”,根据我设置的渲染配置,跳转的真实路径→/index.jsp
应用场景:只需要跳转不需要携带数据(设计初心),但。。。。。
例1:最普通
@RequestMapping(value = "/index.do")public String Test(){return "";}
例2:
我就想返回值是String还传值,嘿嘿
@RequestMapping(value = "/index.do")public String Test(ModelAndView mv){mv.addObject("name","txk");return "";}
但是有bug,下文有详细说说明
3. ModelAndView
应用场景:携带数据并跳转
写法一:
@RequestMapping(value = "/index.do")public ModelAndView Test(ModelAndView mv){mv.addObject("name","txk");mv.setViewName("");//就是跳转的path,不设置报错!!return mv;}
写法二:
@RequestMapping(value = "/index.do")public ModelAndView Test(){ModelAndView mv = new ModelAndView("");//就是跳转的path,不设置报错!!mv.addObject("name","txk");return mv;}
查看ModelAndView 传一个参数调用的是ViewName,所以可以new的时候直接写
参数(常用)其他可百度嘛。。
1.@RequestMapping(value = "/index.do")
像servlet一样,这个value是请求地址,(就是真实的地址)
2.@RequestMapping(value = "/index.do",method = RequestMethod.POST)
设置请求的方式
3.
@RequestMapping(value = "/index.do",method = RequestMethod.POST)public ModelAndView Test(HttpServletRequest req, HttpServletResponse rep){return null;}
相当于servlet的request和response
4.
public ModelAndView Test(String str){return null;}
只要前端使用Parameter的形式传入的数据都可以直接使用传入参数的形式直接获取,此方法抛弃了原始的request和response的写法,更加简洁
5.假设:你的登陆login.jsp是这样的
<%--Created by IntelliJ IDEA.User: TianXinKunDate: 2021/8/31Time: 12:22To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>login</title>
</head>
<body>
<form action="login.do" method="post">name:<input name="name" type="text" required><br>密码:<input name="password" type="password" required><br>年龄:<input name="age" type="text" required><br>性别:<input name="sex" type="radio" value="nan">男<input name="sex" type="radio" value="nan">女<br><input type="submit" value="登陆">
</form>
</body>
</html>
主要注意input的name
然后,bean里面可以直接定义一个User,参数必须和input-name的一致!!!
/*** Copyright (C), 2021/9/1 1:11** @author 田信坤* Author: TianXinKun* Date: 2021/9/1 1:11*/package txk.bean;/*** @Author TianXinKun* @createTime 2021/9/1 1:11 * This program is protected by copyright laws.* @version : 1.0*/public class User {String name;String password;String age;String sex;public User(String name, String password, String age, String sex) {this.name = name;this.password = password;this.age = age;this.sex = sex;}public User() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", password='" + password + '\'' +", age='" + age + '\'' +", sex='" + sex + '\'' +'}';}@Overridepublic boolean equals(Object o) {if (this == o) {return true;}if (o == null || getClass() != o.getClass()) {return false;}User user = (User) o;if (name != null ? !name.equals(user.name) : user.name != null) {return false;}if (password != null ? !password.equals(user.password) : user.password != null) {return false;}if (age != null ? !age.equals(user.age) : user.age != null) {return false;}return sex != null ? sex.equals(user.sex) : user.sex == null;}@Overridepublic int hashCode() {int result = name != null ? name.hashCode() : 0;result = 31 * result + (password != null ? password.hashCode() : 0);result = 31 * result + (age != null ? age.hashCode() : 0);result = 31 * result + (sex != null ? sex.hashCode() : 0);return result;}
}
并且初始化contextClass的时候必须包含User的文件夹像这样
我们就可以直接传入一个User进去
@RequestMapping(value = "/login.do",method = RequestMethod.POST)public String login(User user,ModelAndView mv){mv.addObject("user",user);return "show";}
在/show.jsp接收一下
<%--Created by IntelliJ IDEA.User: TianXinKunDate: 2021/8/31Time: 12:26To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>show</title>
</head>
<body>
${user.name}
${user.password}
</body>
</html>
运行结果
6.我们平常接收path数据是?xxx:xxx&xxx:xxx
我们如何获取*/xxx/10中的10呢,
@RequestMapping(value = "/scp/{num}")public String scp(@PathVariable("num")String num,ModelAndView mv){mv.addObject("num",num);return "scp";}
没错就是这么简单!!!
7.流
上面可以看到可以直接放Writer进去,那么其他的呢
@RequestMapping(value = "/index.do",method = RequestMethod.POST)public ModelAndView Test(Reader s, Buffer b,OutputStream out){return null;}
当然可以!!
差不多常用的就这些了
Spring MVC 访问静态文件
我们的web.xml设置的地址拦截是全部,这就导致我们图片地址,css地址…都会被渲染…
在Spring3.0以后(好像是3.0)支持mvc命名空间指定静态文件,其实还有其他的方法…
要使用mvc命名空间,肯定要先导入啊…
具体的spring-beans.schema.xml是这样的
<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns=""xmlns:context=""xmlns:mvc=""xmlns:xsi=""xsi:schemaLocation="://www.springframework/schema/beans/spring-beans.xsd://www.springframework/schema/context/spring-context.xsd://www.springframework/schema/mvc/spring-mvc.xsd
"><!--初始化contextClass--><context:component-scan base-package="txk.*"></context:component-scan><!--渲染视图--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean><!--设置配置方案--><mvc:annotation-driven></mvc:annotation-driven><!--前面是请求地址,后面是文件地址,以web文件夹为起始地址,还有一种<mvc:default-servlet-handler/>也可以,方式挺多....--><mvc:resources mapping="/imags/*" location="/imags/"></mvc:resources><mvc:resources mapping="/css/*" location="/css/"></mvc:resources>
</beans>
配置了mvc命名空间就可以正常访问服务器上的静态资源了
Spirng MVC文件上传
我使用的是fileuplocd
form配置一个enctype,文件接受用file
<form method="post" action="fileuplocd.do" enctype="multipart/form-data"><input type="file" name="fileuplocd"><input type="text" name="summarize"><input type="submit" name="上传">
</form>
pom依赖添加fileuplocd
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version></dependency>
spring-beans.schema.xml 需要添加一个bean(一定要加id)(如果没有commons io依赖加上)
<!--上传文件拦截 需要添加feiluplocd、commons io两个jar包--><bean id="multipartResolver" class="org.springframework.web.multipartmons.CommonsMultipartResolver"><!--以下三个property可省--><property name="maxInMemorySize" value="10000000"></property><property name="maxUploadSize" value="10000000"></property><property name="defaultEncoding" value="UTF-8"></property></bean>
@Controller怎么写呢?
@RequestMapping(value = "/fileuplocd.do",method = RequestMethod.POST)public ModelAndView FileUplocd(@RequestParam("summarize") String summarize ,@RequestParam("fileuplocd") CommonsMultipartFile fieluplcod,ModelAndView mv){
由于CommonsMultipartFile 不是java的基本数据类型,所以加一个注解@RequestParam就指定好了
接下来就可以直接transferTo了
具体实现
@RequestMapping(value = "/fileuplocd.do",method = RequestMethod.POST)public ModelAndView FileUplocd(@RequestParam("summarize") String summarize ,@RequestParam("fileuplocd") CommonsMultipartFile fieluplcod,ModelAndView mv){String filename = fieluplcod.getOriginalFilename();File file = new File(new File("你服务器存储的地址"),filename);mv.addObject("summarize",summarize);try {fieluplcod.transferTo(file);mv.setViewName("source");} catch (IOException e) {e.printStackTrace();mv.setViewName("error");}return mv;
还可以用流的思想:(可以模拟的打印一个进度):
@RequestMapping(value = "/fileuplocd.do",method = RequestMethod.POST)public ModelAndView FileUplocd(@RequestParam("summarize") String summarize ,@RequestParam("fileuplocd") CommonsMultipartFile fieluplcod,ModelAndView mv){String filename = fieluplcod.getOriginalFilename();File file = new File(new File("你服务器存储的地址"),filename);mv.addObject("summarize",summarize);/* try {fieluplcod.transferTo(file);mv.setViewName("source");} catch (IOException e) {e.printStackTrace();mv.setViewName("error");}*/try {InputStream stream = fieluplcod.getInputStream();long alltotal = fieluplcod.getSize();OutputStream outputStream = new FileOutputStream(file);byte[] bytes = new byte[1024];double total = 0;int len = 0;while ((len=stream.read(bytes))!=-1){outputStream.write(bytes,0,len);total+=len;if ((total/alltotal*100)>10) {total-=10;System.out.print("#");}}mv.setViewName("source");} catch (IOException e) {mv.setViewName("error");e.printStackTrace();}return mv;}
搞定!!
编写于2021-9-2 9:45
本文标签: spring 个人使用文档
版权声明:本文标题:spring 个人使用文档 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1700275854a375751.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论