SpringMVC速通

本文详细介绍了SpringMVC的架构、开发流程、参数接收、跳转、传值、静态资源处理、JSON处理、异常解析、拦截器、上传下载、RESTful API、跨域问题及其解决方案,以及通过SSM实现登录的实例教程。内容涵盖从配置到实践的全过程。
摘要由CSDN通过智能技术生成

文章目录

1 SpringMVC

1.1 引言

  • java开源框架,Spring Framework的一个独立模块。
  • MVC框架,在项目中开辟MVc层次架构
  • 对控制器中的功能包装简化扩展践行工厂模式,功能架构在工厂之上

1.2 MVC架构

MVC : Model View Controller
模型 视图 控制器
模型:即业务模型,负责完成业务中的数据通信处理,对应项目中的service和dao
视图:渲染数据,生成页面。对应项目中的jsp
控制器:直接对接请求,控制MVC流程,调度模型,选择视图。对应项目中的Servlet


  • MVC是现下软件开发中的最流行的代码结构形态;
  • 人们根据负责的不同逻辑,将项目中的代码分成MVC 3个层次;层次内部职责单一,层次之间耦合度低;
  • 符合低耦合高内聚的设计理念。也实际有利于项目的长期维护。

2 开发流程

2.1 步骤

导入依赖

<!--SpringMVC核心依赖-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.14</version>
</dependency>
<!--lombok,需要在IDEA中安装插件-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
</dependency>

配置前端控制器web.xml

右键项目名–>添加框架支持–>web

  • 作为一个MVC框架,首先要解决的是:如何能够收到请求!
  • 所以MVC框架大都会设计一款前端控制器,选型在Servlet或 Filter两者之一,在框架最前沿率先工作,接收所有请求。
  • 此控制器在接收到请求后,还会负责springMVc的核心的调度管理,所以既是前端又是核心。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--mvc前端(核心)控制器
        1.前端,接收所有请求
        2.启动SpringMVC工厂 mvc.xml
        3.SpringMVC流程调度
    -->
    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!--局部参数:声明配置文件位置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>

        <!--Servlet启动时刻:可选(懒饿加载)-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置后端控制器

@Controller //声明这是一个控制器
@RequestMapping("/hello")//访问路径,等价于url-pattern
public class HelloController {
   

    @RequestMapping( "/test1")//访问路径
    public String hello1(){
   
            System.out.println( "hello world" );
            return "hello"; //跳转:/index.jsp
    }

}

配置文件

在resource目录下创建mvc.xml

默认名称:核心控制器名-servet.xml默认位置:WEB-INF随意名称: mvc.xml

随意位置:resources但需要配置在核心控制器中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--注解扫描-->
    <context:component-scan base-package="net.lj"/>

    <!--注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--视图解析器
    作用: 1.捕获后端控制器的返回值="index"
         2.解析:在返回值的前后拼接==> "/index.jsp "
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

运行Tomcat测试

http://localhost:8080/

http://localhost:8080/hello/test1

2.3 中文乱码问题

页面字符集统一

JSP   <%@ page contentType="text/html;charset=UTF-8" language="java" %>
HTML  <meta charset="UTF-8">

tomcat中字符集设置,对get请求中,中文参数乱码有效

Tomcat配置:URIEncoding=utf-8

设置此filter,对post请求中,中文参数乱码有效

<!--设置字符编码过滤器-->
<filter>
    <filter-name>Character Encoding</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>Character Encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3.请求参数接收

3.1 基本类型参数

请求参数与方法形参同名

  • springMVC默认可以识别的日期字符串格式为: YYYY/MM/dd HH:mm:ss
  • 通过@DateTimeFormat可以修改默认日志格式
// http://xxxx/test1?id=1&name=shine&gender=true&birth=2020/12/12 12:13:20
@RequestMapping("test1")
public String test1(Integer id, String name, Boolean gender, Date birth) {
   
    System.out.println("test1");
    System.out.println(id+","+name+","+gender+","+birth);
    return "hello";
}

3.2 实体类接收(推荐)

传入值与类属性同名

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
   
    private Integer id;
    private String name;
    private Boolean gender;
    private Date birth;
}
// http://xxxx/test1?id=1&name=shine&gender=true&birth=2020/12/12 12:13:20
@RequestMapping("test2")
public String test2(User user) {
   
    System.out.println("test2");
    System.out.println(user);
    return "hello";
}

3.3 数组接收

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/test3">
            <input type="checkbox" name="hobby" value="football">足球
            <input type="checkbox" name="hobby" value="basketball">篮球
            <input type="checkbox" name="hobby" value="volleyball">排球<br/>
            <input type="submit" value="提交">
        </form>
    </body>
</html>
// http://xxxx/param/test3?hobby=football&hobby=basketball&hobby=volleyball
@RequestMapping("test3")
public String test3(String[] hobby) {
   
    System.out.println("test3");
    for (String s : hobby) {
   
        System.out.println(s);
    }
    return "hello";
}

3.4 集合接收

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/test4">
            id:<input type="text" name="user[0].id"><br>
            name:<input type="text" name="user[0].name"><br>
            gender:<input type="text" name="user[0].gender"><br>
            <hr>
            id:<input type="text" name="user[1].id"><br>
            name:<input type="text" name="user[1].name"><br>
            gender:<input type="text" name="user[1].gender"><br>
            <input type="submit" value="提交">
        </form>
    </body>
</html>
//http://x/test4?users[0].id=1&users[0].name=shine&users[0].gender=true&users[1].id=2.users[1].name=zhangsan
@RequestMapping("test4")
public String test4(UserList userList) {
   
    for (User user : userList.getUsers()) {
   
        System.out.println(user);
    }
    return "hello";
}

3.5 路径接收

// {id}等价于*  test5/1  test5/2  test5/XXXX
@RequestMapping("test5/{id}")
public String test5(@PathVariable("id") Integer id) {
   
    System.out.println(id);
    return "hello";
}

//  test5/1/2  test5/2/3  test5/XXXX/xxx
@RequestMapping("test6/{id}/{name}")
public String test6(@PathVariable("id") Integer id,@PathVariable("name") String name2) {
   
    System.out.println(id);
    System.out.println(name2);
    return "hello";
}

4 跳转

4.1 转发

@RequestMapping("test1")
public String test1(){
   
    System.out.println("test1");
    //return "hello"; //转发
    return "forward:/hello"; //转发
}

@RequestMapping("test2")
public String test2(){
   
    System.out.println("test2");
    //return "forward:/test1"; //转发到test1
    return "forward:test1"; //相对路径
}

4.2 重定向

@RequestMapping("test3")
public String test3(){
   
    System.out.println("test3");
    return "redirect:/hello";
}

@RequestMapping("test4")
public String test4(){
   
    System.out.println("test4");
    //return "redirect:test3";//相对路径
    return "redirect:/test3";//绝对路径
}

4.3 细节

  • 在增删改之后,为了防止请求重复提交,重定向跳转
  • 在查询之后,可以做转发跳转

5 传值

C得到数据后,跳转到v,并向传递数据。进而V中可以渲染数据,让用户看到含有数据的页面

  • 转发跳转:Request作用域
  • 重定向跳转:Session作用域

导入依赖

<!--Servlet -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<!--JSP标准标签库-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<!--JSP编译环境-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>

5.1 request和session

@RequestMapping("test1")
public String test1(HttpServletRequest request, HttpSession session) {
   
    System.out.println("test1");
    request.setAttribute("name", "张三");
    session.setAttribute("age", "18");
    return "data";
}
name:${requestScope.name}<br>
age:${sessionScope.age}

5.2 model

@RequestMapping("test2")
public String test2(Model model) {
   
    System.out.println("test2");
    model.addAttribute("gender", true);
    return "data2";
}
gender:${requestScope.gender}

5.3 @SessionAttributes

@Controller
@SessionAttributes(names = {
   "city","street"})
public class DataController {
   

    @RequestMapping("test2")
    public String test2(Model model) {
   
        System.out.println("test2");
        model.addAttribute("city", "北京");
        model.addAttribute("street", "长安街");
        return "data2";
    }
    
    @RequestMapping("test3")
    public String test3(SessionStatus status) {
   
        //清空所有通过model存入的session
        status.setComplete();
        return "data2";
    }
}
city:${
   sessionScope.city}
street:${
   sessionScope.street}

5.4 ModelAndView

//ModelAndView跳转并传递数据
@RequestMapping("test4")
public ModelAndView test4() {
   
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("forward:/hello.jsp");
    modelAndView.addObject("clz", "001");
    return modelAndView;
}
clz:${requestScope.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值