【SpringMVC】SpringMVC入门

一、入门案例

1、web.xml配置

将org.springframework.web.servlet.DispatcherServlet配置成servlet标签,并且利用init-param属性,引入spring的配置(因为spring需要管理这些bean和视图)

<?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">
    <!--配置Spring的编码过滤器, 一定配置在其他配置之前-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

load-on-startup 参数将severlet初始化时间提前到服务启动,默认是第一次启动。

2、spring配置文件

  配置扫描组件
  配置视图解析器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描包,这样spring才能认识配置的东西-->
    <context:component-scan base-package="com.lucky"></context:component-scan>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

二、RequestMapping注解

@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。

1、标注位置

可以标注在类上,也可以标注在方法上,如果标注在类上,路径就是类上路径加上方法上路径。

2、value属性

@RequestMapping注解的value属性通过请求的请求地址匹配请求映射。
@RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求
@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射。

3、method属性

@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配,多种请求方式的请求若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错
405:Request method ‘POST’ not supported

 <a th:href="@{/testRequestMapping}">测试@RequestMapping的method属性-->/test</a><br>
 <form th:action="@{/testRequestMapping}" method="post">
     <input type="submit">
 </form>
  @RequestMapping(
            value = {"/testRequestMapping", "/test"},
            method = {RequestMethod.GET, RequestMethod.POST}
    )
    public String testRequestMapping(){
        return "success";
    }

4、占位符

<a th:href="@{/testRest/1/admin}">测试路径中的占位符-->/testRest</a><br>
 @RequestMapping("/testRest/{id}/{username}")
    public String testRest(@PathVariable("id") String id, @PathVariable("username")
            String username){
        System.out.println("id:"+id+",username:"+username);
        return "success";
    }

输出:
在这里插入图片描述

三、SpringMVC获取请求参数

1、severlet原生API

request.getParameter

2、通过控制器方法的形参获取请求参数

在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在DispatcherServlet中就会将请求参数赋值给相应的形参。

<a th:href="@{/testParam(username='admin',password=123456)}">测试获取请求参数--
>/testParam</a><br>
@RequestMapping("/testParam")
public String testParam(String username, String password){
System.out.println("username:"+username+",password:"+password);
return "success";
}

3、@RequestParam

@RequestParam是将请求参数和控制器方法的形参创建映射关系
@RequestParam注解一共有三个属性:
**value:**指定为形参赋值的请求参数的参数名
**required:**设置是否必须传输此请求参数,默认值为true
若设置为true时,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置defaultValue属性,则页面报错400:Required String parameter ‘xxx’ is not present;若设置为false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为null。
defaultValue:不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值

4、通过POJO获取请求参数

可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值。

 <form th:action="@{/testpojo}" method="post">
     用户名:<input type="text" name="username"><br>
     密码:<input type="password" name="password"><br>
     性别:<input type="radio" name="sex" value=""><input type="radio"
                                                         name="sex" value=""><br>
     年龄:<input type="text" name="age"><br>
     邮箱:<input type="text" name="email"><br>
     <input type="submit">
 </form>
 @RequestMapping("/testpojo")
    public String testPOJO(User user){
        System.out.println(user);
        return "success";
    }

四、域对象数据共享

域对象 context session request

处理请求过程: 获取请求参数,调用service实现业务逻辑,然后往域对象共享数据,实现页面渲染,实现页面跳转。

1、Request域共享数据

方法一: Servlet API 向request域发送数据
使用原生request.setAttribute共享数据。
方法二:ModelAndView向Request域共享数据
在Spring MVC的DispatchServlet中,都是往ModelAndView中写数据,因此推荐这个做法。
a、Request域共享数据并且设置视图为success

@RequestMapping("/mvtest")
    public ModelAndView test03() {
        ModelAndView modelAndView = new ModelAndView();
        // 请求域共享数据(model)
        modelAndView.addObject("testRequestScope", "hello, Model and view");
        // 设置逻辑视图(view)
        modelAndView.setViewName("success");
        // 一定要以ModelAndView作为返回值
        return modelAndView;
    }

b、视图中通过th接收数据, testRequestScope设置的共享数据名称

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>success</h1>
<p th:text="${testRequestScope}"></p>
</body>
</html>

方法三:使用Model
视图中渲染方法一样

@RequestMapping("/mtest")
    public String test04(Model model) {
        // 请求域共享数据(model)
        model.addAttribute("testRequestScope", "hello, model");
        return "success";
    }

方法四:使用ModelMap

 @RequestMapping("/mmtest")
    public String test05(ModelMap model) {
        // 请求域共享数据(model)
        model.addAttribute("testRequestScope", "hello, model map.");
        return "success";
    }

方法五:使用Map

  @RequestMapping("/maptest")
    public String testMap(Map<String, Object> map){
        map.put("testRequestScope", "hello,Map");
        return "success";
    }

实际这几种方法,最终参数实例化都用的是BindingAwareModelMap类型。

2、context和session域共享数据

建议使用severlet中的API,

@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplicationScope", "hello,application");
return "success";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值