栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springmvc简单使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springmvc简单使用

1.什么是mvc


2.什么是SpringMVC框架

springMVC它是spring框架的一个分支,该springMVC框架主要完成的功能是:接收浏览器的请求响应,对数据进行处理,然后返回页面进行显示 可以把它理解为和Servlet干的工作是一样的。

3.为什么要使用SpringMVC框架。

4. 如何使用springmvc

1.创建一个maven-web工程
注:需要将原来的web.xml文件替换现在的web.xml资源

	
	
	

2.引入springmvc的依赖

 
    
      org.springframework
      spring-webmvc
      5.2.15.RELEASE
    
  

3.注册DispatcherServlet到web.xml文件上



  
    DispatctherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation

      classpath:springmvc.xml
    
  
  
    DispatctherServlet
    /
  

4.创建我们的springmvc配置文件



    
    
    
    
    
    


5.创建一个controller类,

package com.lzl.controller;

import com.lzl.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


//
@Controller //这个注解标记该类为处理层--类似@webServlet
public class HelloController {
    //把请求路径映射到该方法上
    @RequestMapping("/hello")
    public String hello01(){
        System.out.println(1);
        //响应一个页面
        return "login.jsp";
    }
}
5.springmvc的运行流程
  • 1. 客户端发生请求http://localhost:8080/qy151_springmvc01/abc
    
  • 2. 来到tomcat服务器。
    
  • 3. springmvc的前端控制器DipatcherServlet接受所有的请求。
    
  • 4. 查看你的请求地址和哪个@RequestMaping匹配。
    
  • 5. 执行对应的方法。方法会返回一个字符串。springmvc把该字符串解析为要转发的网页。
    
  • 6. 把该字符串经过视图解析器拼接。
    
  • 7. 拿到拼接的地址,找到对应的网页。
    
  • 8. 渲染该网页给客户
    
6. controller接受请求参数 6.1接受少量参数

只需要给定方法的参数,参数必须要求和请求的参数名称一致。
pringmvc会自动绑定参数

常见错误:

参数的类型或者名称有错

6.2接受大量的参数

封装一个实体类来接受这些参数:
注:name的名称一定要和你创建的实体类的属性名称一样

6.3 如果发现接受的参数值乱码:—只能添加过滤器

(1)自己创建编码过滤器. jdk1.8一定要重写init和destory方法 1.9以后可以不写

public class MyEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
    public void destroy() {

    }
}

(2)使用springmvc提供的编码过滤器

  
    encodingfilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
     
      utf-8
    
  
  
    encodingfilter
    
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private int id;
    private String name;
    private int age;
    private String address;
    // yyyy 年 MM月 dd日 HH小时 mm 分 ss 秒 H:mm:ss
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date shengri;
}

在springmvc配置文件上开启注解驱动



    
    
    
    
    
    


7.处理静态资源

无法加载j静态资源的原因:springmvc的前端控制器DispatcherSerlvet也把静态资源拦截器。放行静态资源就可以解决了
放行静态资源:哪些资源为静态资源。css img js html…



    
    
    
    
    
    


注意: 释放静态资源 和 开启注解驱动 需要一起使用 单独释放静态资源会报错 404 找不到资源 8.如何把controller数据返回到网页并回显。

回顾: 之前我们讲解servlet时,如何把数据保存并可以在网页上获取该数据。

request: 作用范围: 同一个请求内有效。setAttribute(key,value)

session:作用范围: 同一个会话有效,只要会话不关闭会一直有效。setAttribute(key,value)

网页如何获取保存的数据呢:可以使用EL表达式。${scope.key}

package com.lzl.controller;

import com.lzl.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;


@Controller
//设置那些model的key在session范围
@SessionAttributes(value = "user")
public class HelloController {
    @RequestMapping("hello")
    public String hello(){
        System.out.println(1);
        return "login.jsp";
    }
    @RequestMapping("hello01")
    public String hello01(HttpServletRequest request){
        Student student = new Student("张三",new Date(),"郑州");
        //将信息保存到 reqmuest中同一个请求可以访问
        request.setAttribute("s",student);
        return "login.jsp";
    }
    @RequestMapping("hello02")
    public String hello02(Model model){
        Student student = new Student("张三",new Date(),"郑州");
        //将消息保存到 model中 同一个对话中有用
        model.addAttribute("s",student);
        return "login.jsp";
    }
    @RequestMapping("hello03")
    public String hello03(HttpSession session){
        Student student = new Student("张三",new Date(),"郑州");
        // 将信息保存到 session中同一个会话中 有效
        session.setAttribute("s",student);
        return "redirect:login.jsp";
    }
    @RequestMapping("hello04")
    public String hello04(Model model){
        Student student = new Student("张三",new Date(),"郑州");
        //默认在request范围
        model.addAttribute("user",student);
        return "redirect:login.jsp";
    }
}
9.如何使用重定向跳转

在方法的返回字符串的内容时加上redirect:

 @RequestMapping("hello04")
    public String hello04(Model model){
        Student student = new Student("张三",new Date(),"郑州");
        //默认在request范围
        model.addAttribute("user",student);
        //当springmvc 看到你返回的字符串中含有redirect: 时就会知道要进行重定向跳转
        return "redirect:login.jsp";
    }
10. springmvc返回json数据

(1)内置了一个jar. jackson的jar包


    
      com.fasterxml.jackson.core
      jackson-databind
      2.13.2.2
    

(2) 在controller返回的数据类型变成javabean对象。

	@RequestMapping("hello05")
    @ResponseBody //表示将返回值转换为json数据
    public List hello05(){
        List list = new ArrayList();
        list.add(new Student("张三",new Date(),"郑州"));
        list.add(new Student("李四",new Date(),"郑州"));
        list.add(new Student("王五",new Date(),"郑州"));
        return list;
    }

(3) 访问该路径

发现: 上面返回的时间类型的json数据显示的为毫秒,正常情况应该显示时间格式

11. springmvc的全局异常处理类

全局异常处理类的作用: 当controller发生异常,则有全局异常类来处理并执行相应的处理方法。

(1)如何使用全局异常处理类
[1] 创建一个异常类: @ControllerAdvice注解

		@ControllerAdvice //表示该类为controller的异常处理类
		public class MyExceptinHandle {
		    @ExceptionHandler(value = RuntimeException.class)
		    //当发生RuntimeException 就会触发该方法
		    public String error(){
		        return "error.jsp";
		    }
		    @ExceptionHandler(value = Exception.class)
		    //当发生Exception就会触发该方法
		    public String error2(){
		        return "error2.jsp";
    }
}

[2] 保证springmvc能够扫描到该类。

12.springmvc拦截器

过滤器: 过滤掉某些资源,

拦截器只会拦截controller层的资源路径。

1)创建一个类,并实现HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {
    //拦截器的处理方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了过滤器");
        // true 表示放行 false 不放行
        return true;
    }
}

(2) 把该类注册到springmvc配置文件上。

    
        
            
            
            
            
            
            
        
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/964540.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号