Day21-springMVC

SpringMVC

回顾Servlet

环境搭建

  1. 导包

    • junit

    • spring-webmvc

    • servlet-api

    • jsp-api

    • jstl

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lsq</groupId>
    <artifactId>SpringMVC-study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
    <module>springmvc-01</module>
    </modules>

    <properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.15.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2.1-b03</version>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
    </dependencies>

    </project>
  2. 编写一个servlet类

    "add".equals(method)  //写成method.equals("add")可能会出现空指针的情况
    package com.lsq.servlet;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

    public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1.获取前端参数
    String method = req.getParameter("method");
    if (method.equals("add")) {
    req.getSession().setAttribute("msg", "执行了add方法");
    }
    if (method.equals("delete")) {
    req.getSession().setAttribute("msg", "执行了delete方法");
    }
    //2.调用业务层
    //3.视图转发或者重定向
    req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
    }
    }
  3. 编写xml文件

    <?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">
    <!--注册servlet-->
    <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.lsq.servlet.HelloServlet</servlet-class>
    </servlet>
    <!--servlet的请求路径-->
    <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>15</session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
  4. jsp

    <%--
    Created by IntelliJ IDEA.
    User: liushaoqin
    Date: 2023/8/1
    Time: 00:54
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    <form action="/hello" method="post">
    <input type="text" name="method">
    <input type="submit">
    </form>
    </body>
    </html>
    <%--
    Created by IntelliJ IDEA.
    User: liushaoqin
    Date: 2023/8/1
    Time: 00:43
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>

SpringMVC执行原理

第一个Spring+SpringMVC项目

  1. 新建一个module,添加web的支持

  2. 确定导入了SpringMVC的依赖

  3. 配置web.xml,注册DispatchServlet

    <?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">
    <!--配置DispatchServlet:SpringMVC的核心,请求分发器,前端控制器-->
    <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-servlet.xml</param-value>
    </init-param>
    </servlet>

    <!--
    在SpringMVC中 / /*
    /:只匹配所有请求,不会匹配jsp页面
    /*:匹配所有的请求,包括jsp页面
    -->
    <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>

    </web-app>
  4. 配置springmvc-servlet.xml,注册适配器和映射器

    <?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--处理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <!--处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--视图解析器:模版引擎 Thymeleaf Freemarker-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--前缀-->
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <!--后缀-->
    <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="/hello" class="com.lsq.controller.HelloController"/>
    </beans>
  5. HelloCotroller.java

    package com.lsq.controller;

    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;

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

    public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("msg","helloSpringMVC");
    //视图跳转
    modelAndView.setViewName("test");
    return modelAndView;
    }
    }
  6. test.jsp

    <%--
    Created by IntelliJ IDEA.
    User: liushaoqin
    Date: 2023/8/1
    Time: 17:42
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>
  7. 启动tomcat提示404

    • 解决方案1:

    1. 打开项目结构

    2. 选择工件

    3. 找到当前模块选中,查看WEB-INF下是否有lib目录,若没有则新建

    4. 选择lib新建库文件,把包全选导入

    • 解决方案2:

      • 在web.xml文件中设置默认启动的jsp,在配置文件中加上下面的代码

        <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
         

SpringMVC项目配置(不用之前的Servlet)

web.xml

<?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">

<!--配置DispatchServlet:SpringMVC的核心,请求分发器,前端控制器-->
<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-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<!--
在SpringMVC中 / /*
/:只匹配所有请求,不会匹配jsp页面
/*:匹配所有的请求,包括jsp页面
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

配置springmvc-servlet.xml,不再需要注册适配器和映射器

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:component-scan base-package="com.lsq.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>

<!--视图解析器:模版引擎 Thymeleaf Freemarker-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>


</beans>

controller

package com.lsq.controller;

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

@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","springmvcAnnotation");
return "hello";
}
}

启动页面jsp

<%--
Created by IntelliJ IDEA.
User: liushaoqin
Date: 2023/8/2
Time: 04:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>

Restful风格

  1. SpringMVC可以使用@PathVariable注解,让方法的值对应绑定一个URL模版变量上

  2. 使用restful操作资源:可以通过不同的请求方式来实现不同的效果

  3. 使用方式(默认使用get方式)

    • @Controller
      public class HelloController{

      @RequestMapping("/hello/{a}{b}")
      public String test(@PathVariable int a,@PathVariable int b, Model model){
      int result=a+b;
      model.addAttribute("msg","结果为"+result);
      return "hello";
      }
      }
    • @Controller
      public class HelloController{

      @RequestMapping(value = "/hello/{a}{b}",method = POST)
      public String test(@PathVariable int a,@PathVariable int b, Model model){
      int result=a+b;
      model.addAttribute("msg","结果为"+result);
      return "hello";
      }
      }
    • @Controller
      public class HelloController{

      @GetMapping("/hello/{a}{b}")
      public String test(@PathVariable int a,@PathVariable int b, Model model){
      int result=a+b;
      model.addAttribute("msg","结果为"+result);
      return "hello";
      }
      }

    SpringMVC:结果跳转方式

    扩展:转发和重定向

     转发相当于,张三向你借钱,但是你兜里没钱,所以你去找李四借到钱之后借给张三。对于张三而言并不知道你的钱是和李四借的。

     重定向相当于,张三向你借钱,你兜里没钱,你告诉他李四有钱,所以张三再次去找李四借钱。

    1. 重定向访问服务器两次,转发只访问服务器一次。

    2. 转发页面的URL不会改变,而重定向地址会改变

    3. 转发只能转发到自己的web应用内,重定向可以重定义到任意资源路径

    4. 转发相当于服务器跳转,相当于方法调用,在执行当前文件的过程中转向执行目标文件,两个文件(当前文件和目标文件)属于同一次请求,前后页 共用一个request,可以通过此来传递一些数据或者session信息,request.setAttribute()和 request.getAttribute()。而重定向会产生一个新的request,不能共享request域信息与请求参数

    5. 由于转发相当于服务器内部方法调用,所以转发后面的代码仍然会执行(转发之后记得return);重定向代码执行之后是方法执行完成之后进行重定向操作,也就是访问第二个请求,如果是方法的最后一行进行重定向那就会马上进行重定向(重定向也需要return)。

    6. 无论是RequestDispatcher.forward方法,还是HttpServletResponse.sendRedirect方法,在调用它们之前,都不能有内容已经被实际输出到了客户端。如果缓冲区中已经有了一些内容,这些内容将被从缓冲区中移除。

    通过SpringMVC来实现转发和重定向-有视图解析器,默认进行转发

    重定向,不需要视图解析器

    @Controller
    public class HelloController{

    @RequestMapping("/hello")
    public String test(){
    return "redirect:/hello.jsp";
    }
    }

    解决SprinMVC乱码问题

    <!--配置springMVC的乱码过滤-->
    <filter>
    <filter-name>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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    json解析工具(jackson)

    导入jar包

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
    </dependency>

    解决json乱码问题

    <!--JSON乱码问题配置-->
    <mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
    <constructor-arg value="UTF-8"/>
    </bean>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="objectMapper">
    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <property name="failOnEmptyBeans" value="false"/>
    </bean>
    </property>
    </bean>
    </mvc:message-converters>
    </mvc:annotation-driven>

    json对于日期不使用时间戳显示

    纯java方式对于日期不使用时间戳显示

Json交互处理

导入依赖

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>

解决json乱码问题,配置spring-mvc.xml

<!--JSON乱码问题配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

FastJson

可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换

导入依赖

 <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.32</version>
</dependency>

fastjson 三个主要的类:

  • JSONObject 代表 json 对象

  • JSONArray 代表 json 对象数组

  • JSON代表 JSONObject和JSONArray的转化

工具类

package com.kuang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class FastJsonDemo {
public static void main(String[] args) {
//创建一个对象
User user1 = new User("秦疆1号", 3, "男");
User user2 = new User("秦疆2号", 3, "男");
User user3 = new User("秦疆3号", 3, "男");
User user4 = new User("秦疆4号", 3, "男");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);

System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);

System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
}
}
posted @ 2023-08-07 01:31  仓鼠的气垫床  阅读(38)  评论(0编辑  收藏  举报