飞道的博客

JavaEE学习日志(九十三): SpringMVC入门

397人阅读  评论(0)

JavaEE学习日志持续更新----> 必看!JavaEE学习路线(文章总汇)

SpringMVC

传统servlet

实现打印当前时间

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //将当前时间显示给用户
        Date date = new Date();
        //resp.getWriter().print(date.toLocaleString());
        String content = "当前时间"+date.toLocaleString();
        req.setAttribute("content",content);
        req.getRequestDispatcher("/WEB-INF/pages/hello/list.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div style="text-align: center; color: red; margin: 200px auto;">
        ${content}
    </div>
</body>
</html>

springmvc入门案例(映射路径)

实现打印当前时间

一、引入依赖

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

二、UserController

@RequestMapping("/test01.do") 映射路径

package com.itheima.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/test01.do")
    public ModelAndView test1(ModelAndView modelAndView){
        //将当前时间显示给用户
        Date date = new Date();
        //resp.getWriter().print(date.toLocaleString());
        String content = "当前时间"+date.toLocaleString();
        //类似于写的req.setAttribute("content",content);
        modelAndView.addObject("content",content);
        //等同于req.getRequestDispatcher("/WEB-INF/pages/hello/list.jsp").forward(req,resp);
        modelAndView.setViewName("/WEB-INF/pages/user/list.jsp");
        return modelAndView;
    }
}

三、web.xml配置文件:DispatcherServlet任何请求都由他接收

  • 初始化创建spring容器
<init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
  • 项目一启动就创建容器,不配置的话就是第一次请求才去创建容器
<load-on-startup>1</load-on-startup>
<?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_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc</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>springmvc</servlet-name>
        <!--<url-pattern>*.do</url-pattern>-->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

四、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 http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.itheima.web"></context:component-scan>

</beans>

五、jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div style="text-align: center; color: red; margin: 200px auto;">
        ${content}
    </div>
</body>
</html>

springmvc的参数绑定

springmvc的参数绑定
一、直接在参数列表中增加int id,无需手动接收,会自动获取

@RequestMapping("/test02")
    public ModelAndView test2(ModelAndView modelAndView, int id){
        System.out.println(id);
        //将当前时间显示给用户
        Date date = new Date();
        //resp.getWriter().print(date.toLocaleString());
        String content = "当前时间"+date.toLocaleString();
        //类似于写的req.setAttribute("content",content);
        modelAndView.addObject("content",content);
        //等同于req.getRequestDispatcher("/WEB-INF/pages/hello/list.jsp").forward(req,resp);
        modelAndView.setViewName("/WEB-INF/pages/user/list.jsp");
        return modelAndView;
    }

访问地址

http://localhost/user/test02?id=123

控制台中打印出了123

二、直接在参数列表中添加User user,会自动封装pojo对象

访问地址:需要什么写什么,会自动封装

http://localhost/user/test02?id=123&username=xiaoming&desc=haha

Controller

@RequestMapping("/test02")
    public ModelAndView test2(ModelAndView modelAndView, User user){
        System.out.println(user);
        //将当前时间显示给用户
        Date date = new Date();
        //resp.getWriter().print(date.toLocaleString());
        String content = "当前时间"+date.toLocaleString();
        //类似于写的req.setAttribute("content",content);
        modelAndView.addObject("content",content);
        //等同于req.getRequestDispatcher("/WEB-INF/pages/hello/list.jsp").forward(req,resp);
        modelAndView.setViewName("/WEB-INF/pages/user/list.jsp");
        return modelAndView;
    }


控制台打印

springmvc的三大组件


DispatcherServlet:负责接收请求
HandlerMapping:负责寻找方法
HandlerAdapter:负责处理方法的参数
ViewResolver:负责渲染页面

定制化三大组件

一、定制视图解析器

内部视图解析器配置:

  • prefix:前缀
  • suffix:后缀
<?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 http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.itheima.web"></context:component-scan>
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

这样一来,这句话就可以改写成

modelAndView.setViewName("user/list");

减少了代码量

二、定制处理器映射器
指明:就是要使用requestMapping handler映射处理器,在spring5以后就默认,但还是需要添加配置文件

<mvc:annotation-driven></mvc:annotation-driven>

两个原因:

  • 版本原因:RequestMappingHandlerMapping在以前版本中已经有这个类,但是5.0以前版本默认不是这个
  • 需要添加其他功能:其他的转换、json转换、自定义格式转换都需要用到他

转载:https://blog.csdn.net/Sakuraaaaaaa/article/details/105948071
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场