一文上手SpringMVC

一文上手SpringMVC

1 原生SpringMVC使用

1.1 创建JavaEE工程

1.2 引入jar包

引入Spring及SpringMVC的jar包,可以使用工具导入,也可以使用Maven依赖
例如:

commons-logging-1.1.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar

1.3 maven依赖


    
      org.springframework
      spring-webmvc
      4.3.18.RELEASE
    

    
    
      javax.servlet
      jstl
      1.2
    

    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.7.0
    
    
    
      javax.servlet
      servlet-api
      2.5
      provided
    

    
      javax.servlet
      jsp-api
      2.0
      provided
    

    
    
      commons-fileupload
      commons-fileupload
      1.3.1
    

1.4 配置web.xml文件


    
        springDispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
			 
            classpath:springmvc.xml
        
        1
    
    
        springDispatcherServlet
        /
    

1.5 创建springmvc.xml文件并配置

在src下创建Spring文件springmvc.xml
配置:


    
    
    
        
        
    

1.6 在/WEB-INF/views/目录下创建 success.jsp 文件

1.7 创建Handler类(也就是Controller类)

@org.springframework.stereotype.Controller

这个注解标明该类是一个Controller类

@org.springframework.web.bind.annotation.RequestMapping

标识请求路径

@org.springframework.web.bind.annotation.RequestMethod

标识请求的类型 GET/POST/PUT/DELETE ,可以写多个
例如:method = {RequestMethod.GET, RequestMethod.POST}

package com.hongyu.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/first")
public class SpringMVCHandler {

    // 处理请求
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String handleHello() {
        System.out.println("Hello springMVC");
        return "success";  // 根据视图解析器的配置,页面会转发到
//  /WEB-INF/views/success.jsp
    }
}

1.8 请求验证

请求的路径 http://IP:端口/工程名/RequestMapping路径
例如:
http://localhost:8585/springmvc01/first/hello

1.9 对参数和头文件的限制

@RequestMapping(value = "/params", params = {"!name", "age=33"}, headers = {"User-Agent"})
    public String handleparams() {
        return "success";
    }

例如:
参数不能有name,age必须等于33等
头文件中必须包含 User-Agent 属性

1.10 占位符写法(Rest)

@RequestMapping("/path/{name}/{id}")
    public String testPath(@PathVariable("id") String uid, @PathVariable("name") String name) {
        System.out.println("uid:" + uid + " | " + "name:" + name);
        return "success";
    }

1.11 获取请求参数

1.11.1 基本写法

@RequestMapping("/testParam")
public String testParam(@RequestParam("name") String name, 
@RequestParam("age") Integer age1) {
        System.out.println("name:" + name + "|age:" + age1);
        return "success";
    }

请求:/testParam?name=zhangsan&age=34
注意:如果参数名和形参名一致,可以省略 @RequestParam 注解

1.11.2 设置参数非必填

@RequestMapping("/testParam")
public String testParam(@RequestParam(value = "name", required = false) 
String name, @RequestParam("age") Integer age1) {
        System.out.println("name:" + name + "|age:" + age1);
        return "success";
    }

1.11.3 设置默认值

@RequestMapping("/testParam")
    public String testParam(@RequestParam(value = "name", required = false) String name,
 @RequestParam(value = "age", defaultValue = "18") int age1) {
        System.out.println("name:" + name + "|age:" + age1);
        return "success";
    }

1.11.4 获取头文件参数

@RequestMapping(value = "/params", params = {"!name", "age=33"}, headers = {"User-Agent"})
    public String handleparams(@RequestHeader("User-Agent") String userAgent) {
        System.out.println("Content-Type:" + userAgent);
        return "success";
    }

1.11.5 获取cookie的值

@RequestMapping("/testParam")
    public String testParam(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "age", defaultValue = "18") int age1,
@CookieValue(value = "JSESSIONID") String jsessionid) {
System.out.println("name:" + name + "|age:" + age1 + "|cookie:" + jsessionid);
        return "success";
    }

1.11.6 Pojo参数

请求的参数名,必须和实体类的属性名一致

1.11.6.1 前端

用户名称:
用户密码:
email:
age: 18 28
省:
市:

1.11.6.2 后端

@RequestMapping(value = "/testPojo", method = RequestMethod.POST)
    public String testPojo(User user) {
        System.out.println(user);
        return "success";
    }

1.11.6.3 实体

public class User {

    private String name;

    private String password;

    private String email;

    private Integer age;

    private Address address;

public class Address {

    private String sheng; // 省

    private String shi; // 市

1.11.7 使用Request对象、Response对象、Session对象

直接在参数中写上Request和Response就可以

@RequestMapping(value = "/testPojo", method = RequestMethod.POST)
public void testPojo(User user, HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException {
        System.out.println(user);
        System.out.println(request);
        System.out.println(response);
        HttpSession session = request.getSession();
        System.out.println(session);
        request.getRequestDispatcher("/WEB-INF/views/success.jsp").forward(request, response);

}

1.12 处理模型数据

1.12.1 ModelAndView方式

@RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {

        ModelAndView mav = new ModelAndView();
        mav.addObject("userName", "zhangsan");  // 放入Model数据
        mav.setViewName("success");  // 设置View
        return mav;
    }

可以在view中使用EL表达式得到Model数据

userName:${requestScope.userName}

1.12.2 Map方式(推荐)

@RequestMapping("/testMap")
    public String testMap(Map map) { // map直接写在这里就可以
        map.put("userName", "lisi");
        map.put("age", 11);
        return "success";
}



userName:${requestScope.userName}

age: ${requestScope.age}

放在map中的数据,也可以使用EL表达式得到

1.12.3 Model方式

@RequestMapping("/testModel")
    public String testModel(Model model) {
        model.addAttribute("userName", "wangwu");
        model.addAttribute("age", 25);
        return "success";
}

放在model中的数据,也可以使用EL表达式得到

userName:${requestScope.userName}

age: ${requestScope.age}

1.13 省略java方法,直接通过配置重定向

在springmvc.xml中配置

	
    
    

Path就是请求路径,default是要跳转到的jsp页面

1.14 重定向

@RequestMapping("/testRedirect")
    public String testRedirect() {
        return "redirect:/ok.jsp";   // 此处会重定向到工程下的ok.jsp页面
    }

1.15 返回Json格式

@ResponseBody   // 加上这个注解就可以返回Json
    @RequestMapping("/testJson")
    public User testJson() {
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setEmail("[email protected]");
        Address address = new Address();
        address.setSheng("guangdong");
        user.setAddress(address);
        return user;
    }

1.16 实现下载

1.16.1 前台

点我下载

1.16.2 后台

@RequestMapping("/download")
public ResponseEntity testDownload(HttpSession session) 
throws IOException {

        byte[] file = null;
        ServletContext sc = session.getServletContext();
        InputStream in 
= sc.getResourceAsStream("download/tepiqingjiadan.docx");
        file = new byte[in.available()]; // in.available() 流中能读取的字节数大小
        in.read(file);  // 将流读到byte[]
        // 将响应数据和响应头都放在 ResponseEntity 中
        /**
         * 参数1:发送给浏览器端的数据
         * 参数2:设置响应头
         * 参数3:设置响应码
         */
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" +
  new String("特批请假单".getBytes("UTF-8"),"ISO-8859-1") + ".docx");

        ResponseEntity re = new ResponseEntity(file, headers, HttpStatus.OK);

        return re;
    }

1.16.3 解决文件名中文乱码问题

方式一将中文文件名用ISO-8859-1进行重新编码如headers.add(“Content-disposition”,“attachment;filename=”+new String(“中国”.getBytes(“UTF-8”),“ISO-8859-1”)+".txt");
方式二可以对中文文件名使用url编码如headers.add(“Content-disposition”,“attachment;filename=”+URLEncoder.encode(“中国”,“UTF-8”)+".txt");

1.17 实现文件上传

1.17.1 springmvc.xml 增加配置



        
        
        
        

注意:bean的id必须叫作 multipartResolver,否则会报错!

1.17.2 为什么上传bean一到要配置成multipartResolver

找到 org.springframework.web.servlet.DispatcherServlet的initStrategies方法,里面的 initMultipartResolver(context);中使用
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);得到对象。
代码中定义:
public static final String MULTIPART_RESOLVER_BEAN_NAME = “multipartResolver”;
因此,想让框架得到对象,必须将id命名为multipartResolver

1.17.3 前台

上传文件:
文件描述:

1.17.4 后台

@RequestMapping("/upload")
    public String testUploadFile(@RequestParam("desc") String desc,
@RequestParam("uploadFile") MultipartFile uploadFile,
HttpSession session) throws Exception {

        System.out.println("desc:" + desc );

        // 获取上传文件的名字
        String uploadFileName = uploadFile.getOriginalFilename();
        System.out.println("OriginalFilename: " + uploadFileName);
        // 获取输入流
        InputStream in = uploadFile.getInputStream();

        // 获取服务器upload文件夹的真是路径
        ServletContext sc = session.getServletContext();
        String realPath = sc.getRealPath("upload");
        System.out.println("realPath:" + realPath);

        File targetFile = new File(realPath + "/" + uploadFileName);

        FileOutputStream os = new FileOutputStream(targetFile);

        // 写文件
        int i;
        while ((i=in.read()) != -1) {
            os.write(i);
        }

        in.close();
        os.close();

        return "success";
}

1.17.5 后台(简洁版)

@RequestMapping("/uploadNew")
    public String testUploadFileNew(@RequestParam("desc") String desc,
@RequestParam("uploadFile") MultipartFile uploadFile,
HttpSession session) throws Exception {
        System.out.println("desc:" + desc );
        // 获取上传文件的名字
        String uploadFileName = uploadFile.getOriginalFilename();
        System.out.println("OriginalFilename: " + uploadFileName);
        // 获取服务器upload文件夹的真是路径
        ServletContext sc = session.getServletContext();
        String realPath = sc.getRealPath("upload");
        System.out.println("realPath:" + realPath);

        File targetFile = new File(realPath + "/" + uploadFileName);
        uploadFile.transferTo(targetFile);

        return "success";
    }

只需要得到文件的绝对路径,然后调用API uploadFile.transferTo(targetFile);,搞定

1.17.6 解决IDEA下Maven工程上传文件始终报错问题

错误:Current request is not a multipart request
在maven工程下使用tomcat7插件启动,上传文件始终报上面这个错
分析:
将工程打包,放到Apache官网下载的Tomcat中,没有任何问题,可以正常上传文件,因此代码和jar包的依赖应该没有问题,怀疑是Tomcat插件的问题。
解决:
不使用插件启动,直接把工程部署到IDEA中嵌入的Tomcat中,问题解决

1.18 拦截器

1.18.1 后台

实现 org.springframework.web.servlet.HandlerInterceptor 接口
或者
继承 org.springframework.web.servlet.handler.HandlerInterceptorAdapter 抽象类

package com.hongyu.springmvc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
//@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 请求处理方法之前执行
        System.out.println("MyInterceptor preHandle...");
        return true; // true会继续执行,false不会继续执行
    }
    @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	// 请求处理方法之后,视图处理之前执行

        System.out.println("MyInterceptor postHandle...");
    }
    @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	// 视图处理之后执行(转发/重定向后执行)
	// 当某个拦截器的preHandle返回false,也会执行当前拦截器之前拦截器的afterCompletion方法
// 当Controller方法抛出异常,也会执行afterCompletion方法
        System.out.println("MyInterceptor afterCompletion...");
    }
}

1.18.2 springmvc.xml配置


    
        
        
        

        
        

            
            
            
        

    

1.18.3 多个拦截器的执行顺序

preHandle按配置的正序执行,postHandle、afterCompletion按配置的倒叙执行
例子:
按顺序配置了3个拦截器,执行效果如下
MyInterceptor preHandle…
MyInterceptor2 preHandle…
MyInterceptor3 preHandle…
MyInterceptor3 postHandle…
MyInterceptor2 postHandle…
MyInterceptor postHandle…
MyInterceptor3 afterCompletion…
MyInterceptor2 afterCompletion…
MyInterceptor afterCompletion…

2 各种请求的实现

2.1 GET请求

hello SpringMVC 

2.2 POST请求

  

2.3 PUT 和 DELETE请求

2.3.1 配置HiddenHttpMethodFilter过滤器


    
        HiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
        HiddenHttpMethodFilter
        /*
    

2.3.2 PUT请求

2.3.3 DELETE请求

3 View的使用

3.1 JSTL标签

3.1.1 引入jar包

jstl.jar
standard.jar

3.1.2 在jsp页面声明标签

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

3.1.3 使用标签


        
${name}

3.2 SpringMVC表单标签

3.2.1 理论

1) 通过 SpringMVC 的表单标签可以实现将模型数据中的属性和 HTML 表单元素相绑定,以实现表单数据更便捷编辑和表单值的回显
2) form 标签
 一般情况下,通过 GET 请求获取表单页面,而通过 POST 请求提交表单页面,因此获取表单页面和提交表单页面的 URL 是相同的。
 只要满足该最佳条件的契约,form:form 标签就无需通过 action 属性指定表单提交的 URL
 可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean,如果该属性值也不存在,则会发生错误。
3) SpringMVC 提供了多个表单组件标签,如 form:input/、form:select/ 等,用以绑定表单字段的属性值,它们的共有属性如下:
 path:表单字段,对应 html 元素的 name 属性,支持级联属性
 htmlEscape:是否对表单值的 HTML 特殊字符进行转换,默认值为 true
 cssClass:表单组件对应的 CSS 样式类名
 cssErrorClass:表单组件的数据存在错误时,采取的 CSS 样式
4) form:input、form:password、form:hidden、form:textarea:对应 HTML 表单的 text、password、hidden、textarea 标签
5) form:radiobutton:单选框组件标签,当表单 bean 对应的属性值和 value 值相等时,单选框被选中
6) form:radiobuttons:单选框组标签,用于构造多个单选框
 items:可以是一个 List、String[] 或 Map
 itemValue:指定 radio 的 value 值。可以是集合中 bean 的一个属性值
 itemLabel:指定 radio 的 label 值
 delimiter:多个单选框可以通过 delimiter 指定分隔符
7) form:checkbox:复选框组件。用于构造单个复选框
8) form:checkboxs:用于构造多个复选框。使用方式同 form:radiobuttons 标签
9) form:select:用于构造下拉框组件。使用方式同 form:radiobuttons 标签
10) form:option:下拉框选项组件标签。使用方式同 form:radiobuttons 标签
11) form:errors:显示表单组件或数据校验所对应的错误
” /> :显示表单所有的错误
” /> :显示所有以 user 为前缀的属性对应的错误
:显示特定表单对象属性的错误

3.2.2 例子

3.2.2.1 声明标签

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

3.2.2.2 后台代码

@RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(User user) {
        System.out.println("user:" + user);
        return "redirect:/ok.jsp";
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String findOneUser(Map map, @PathVariable("id") String id) {
        System.out.println("id:" + id);

        Map ageItem = new HashMap<>();
        ageItem.put("10", "10岁");
        ageItem.put("20", "20岁");
        ageItem.put("30", "30岁");
        map.put("ageItem", ageItem); // 前台的标签可以直接用

        List
shengItem = new ArrayList<>(); shengItem.add(new Address("beijing", "北京")); shengItem.add(new Address("shanghai", "上海")); shengItem.add(new Address("guangdong", "广东")); map.put("shengItem", shengItem); // 前台的标签可以直接用 User user = new User(); user.setAge(20); map.put("user", user); return "add"; }

3.2.2.3 前台代码


        
        名字: 
Email:
年龄选择:
地址选择:

注意:
select 和 radio ,传入的items是List时,需要指定itemValue(key)和itemLabel(显示值)
form:form 的 modelAttribute属性极其重要,这个属性指明Model的key,Model可以用于回写表单的数据,如果不指定则默认为command,后台也要传相应的对象,否则会报错。

3.3 DELETE请求的实现

项目中通常是用 a 标签实现删除,不使用form,那如何添加hidden,指定是DELETE请求呢?
解决方案:
写一个只有hidden input的form,在里面写上 _method 的input,然后利用js提交请求。
HTML部分:

delUser

JavaScript部分:

$(function(){
          $(".del").click(function () {
              var href = this.href;
              $("#deleteForm").attr("action", href).submit();
              return false;
          });

3.4 PUT请求的实现

原理与DELETE类似,需要先打开详细页面回显数据,可以跟新增页面整合,然后做一个对id的判断,如果有id属性,则增加在form中增加 标签。

3.5 得到当前工程路径

${pageContext.request.contextPath}

3.6 解决JavaScript文件不能被加载问题

在springmvc.xml中增加配置

3.7 解决字符集问题

web.xml中增加字符编码过滤器


    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

4 Rest风格

User为例

4.1 列表

请求资源路径: /users
请求类型: GET

4.2 跳转到新增

请求资源路径: /user
请求类型: GET

4.3 执行新增

请求资源路径: /user
请求类型: POST

4.4 跳转到更新

请求资源路径: /user/{id}
请求类型: GET

4.5 更新

请求资源路径: /user/{id}
请求类型: PUT

4.6 删除

请求资源路径: /user/{id}
请求类型: DELETE

5 解决EL表达式无法解析问题

检查web.xml文件的文件头,确保是以下的写法



6 SpringMVC 与 Spring整合

6.1 配置监听器启动Spring容器

web.xml中配置


    contextConfigLocation
    classpath:applicationContext.xml
  
  


org.springframework.web.context.ContextLoaderListener

  

6.2 解决Bean对象被重复扫描问题

在Spring中配置了扫描后,Spring和SpringMVC都会去扫描注解注册的组件
可以通过配置排除解决该问题

6.2.1 修改springmvc.xml





6.2.2 修改spring配置文件


        

6.3 spring与springMVC的关系

springmvc是spring的子容器
springmvc可以访问spring的内容,spring不能访问springmvc

7 利用Session对象得到ApplicationContext对象

@RequestMapping("/findContext")
    public String findContext(HttpSession session) {

        ServletContext servletContext = session.getServletContext();
        ApplicationContext applicationContext
=  WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserDao userDao2 = applicationContext.getBean(UserDao.class);
        userDao2.userList();
        return "success";
    }

你可能感兴趣的:(Java,spring,springmvc,java)