spring MVC 续
@RequsetMapping
@RequestMapping注解用于映射url到控制器类
package top.wmgx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
//@RequestMapping("/a")
public class Hello {
//访问地址为(http://localhost:8081/a1)
//若类前面有@RequestMapping("/a")访问地址为(http://localhost:8081/a/a1)
@RequestMapping("/a1")
public String test(Model model){
model.addAttribute("msg","ok");
return "test";
}
}
参数接收
1. 普通参数
http://localhost:8081/a1?username=admin&pwd=123456
@Controller
public class Hello {
//名称一致的可以直接写
//名称不一致的加@RequestParam("pwd") 注解
//建议一致或者不一致都写@RequestParam()
@RequestMapping("/a1")
public String test(String name, @RequestParam("pwd") String password){
System.out.println(name+"\n"+password);
return "test";
}
}
2. 接受方也可以是对象
前提,对象的属性和前端必须保持一致提供set方法
package top.wmgx.Model;
public class User {
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
@Controller
public class Hello {
//可以直接写User user 对应属性会被设置进去,没有的会为null
@RequestMapping("/a1")
public String test(User user){
System.out.println(user);
return "test";
}
}
3. HttpServletRequest
@Controller
public class Hello {
//可以直接写User user 对应属性会被设置进去,没有的会为null
@RequestMapping("/a1")
public String test(HttpServletRequest request){
String name = request.getParameter("name"); String pwd = request.getParameter("pwd");
System.out.println(name+"\n"+password);
return "test";
}
}
4. RestFul
参数在路径中,上方的链接变成了
http://localhost:8081/a1/admin/123456
url含有中文名称时,因为编码问题,无法进行映射,需要修改tomcat下的conf文件夹下的server.xml中的URIEncoding=”UTF-8”
@Controller
public class Hello {
// 限制get请求并设置返回编码为utf-8
@RequestMapping(value = "/a1/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String test(@PathVariable String name, @PathVariable String pwd){
System.out.println(name+"\n"+pwd);
return "test";
}
}
5. JSON方式
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.2</version>
</dependency>
需要导入jackson的支持,会被自动装配的配置项 <mvc:annotation-driven /> 装配
前端提示:HTTP Status 415 – 不支持的媒体类型
后端提示:Content type 'application/json' not supported]
前端发送的Header前面需要加上Content-Type:”application/json”
前端提示:HTTP Status 415 – 不支持的媒体类型
描述源服务器拒绝服务请求,因为有效负载的格式在目标资源上此方法不支持。
@RequestMapping(value = "/a", method = {RequestMethod.POST}, consumes = {"application/json"})
@ResponseBody
public String test(@RequestBody User user){
return user.toString();
}
**consumes设置后,只处理Content-Type:“application/json”**的数据
组合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping 等同于 @RequestMapping(method =RequestMethod.GET)
转发与重定向
- 在视图解析器中,默认就是转发
- 重定向的话 return "redirect:index.jsp"或者return "redirect:test1"另一个RequestMapping
拦截器
public class MyInterceptor implements HandlerInterceptor {
//在请求处理的方法之前执行
//如果返回true执行下一个拦截器
//如果返回false就不执行下一个拦截器
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("------------处理前------------");
return true;//true继续向下走
}
//在请求处理方法执行之后执行
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("------------处理后------------");
}
//在dispatcherServlet处理后执行,做清理工作.
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("------------清理------------");
}
}
配置文件
<!--关于拦截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--/** 包括路径及其子路径-->
<!--/* 拦截的是/一级的-->
<mvc:mapping path="/**"/>
<!--bean配置的就是拦截器-->
<bean class="top.wmgx.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
文件上传
前端设置
enctype="multipart/form-data"
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit">
</form>
导入jar包
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
配置sping配置文件
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
multipartResolver 命名一定是这个
代码
- String getOriginalFilename():获取上传文件的原名
- InputStream getInputStream():获取文件流
- void transferTo(File dest):将上传文件保存到一个目录文件中
//@RequestParam("file") 将得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String Upload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
利用file。Transto
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
下载
@RequestMapping(value="/download")
public String downloads(@RequestParam("file") String fileName,HttpServletResponse response , HttpServletRequest request) throws Exception{
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员小航
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果