SpringMVC的学习

SpringMVC

1、初识SpringMVC

SpringMVC是一个基于Java实现MVC模式的一种轻量级架构。

1.1 主要特点

  • 轻量级,高效
  • 依靠请求响应
  • 与Spring兼容性好
  • 实现功能强大,可以整合其他风格设计(Restful)

1.2 基本原理

在这里插入图片描述

DispatcherServlet :前置控制器,在整个SpringMVC中,作为中央控制角色。

HandlerMapping:处理器映射,根据传递过来的请求(url)映射相应handler。

HandLerExecution:具体的handler,根据映射关系,查找具体的handler。

HandlerAdapter:处理器适配器,根据规则执行handler。

ViewResolver:视图解析器,用来解析相应的视图。

执行流程:

  1. 当用户发起请求时,会传递一个请求(URL)到DispatcherServlet进行解析请求
  2. DispatcherServlet携带所请求的控制器名称(/hello)到HandlerMapping,HandlerMapping根据名称去找到相对应的处理器
  3. HandlerExecution去接收查找到的handler,
  4. 并且将所接收到的hello请求名称传递给DispatcherServlet
  5. HandlerAdapter表示处理器适配器,就是指根据handler的请求,去适配相应的handler执行
  6. handler使得对应的Controller执行
  7. Controller将执行得到的信息返回给HandlerAdapter,也就是ModelAndView(模型和视图)
  8. HandlerAdapter将得到信息传递给DispatcherServlet
  9. DispatcherServlet 调用ViewResolver(视图解析器)来解析传递过来的视图名
  10. ViewResolver将结果传递给DispatcherServlet
  11. DispatcherServlet 根据传递过来的信息,调用具体的视图
  12. 显示到界面

1.3 一个简单的demo

在这里插入图片描述

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

    <!--配置DispatcherServlet  -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--绑定Spring的核心配置文件-->
        <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>


    <!--
            /   指匹配所有的请求
           /*   匹配所有请求,包括jsp页面   会造成  index.jsp.jsp~~~~~  -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

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

    <!--处理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    <!--处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>


    <bean id="/test" class="com.myl.TestController"></bean>


</beans>

test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/27
  Time: 15:18
  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>

TestController.java

package com.myl;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import sun.awt.ModalityEvent;
import sun.security.provider.MD2;

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

/**
 * @ClassName: TestController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  15:31
 */
public class TestController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        ModelAndView mv = new ModelAndView();

        //编写业务代码,逻辑处理
        String result = "Hello SpringMvc";
        mv.addObject("msg", result);

        // 视图跳转
        mv.setViewName("test");


        return mv;
    }
}

pom.xml

<?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.myl</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>SpringMVC-HelloWorld</module>
    </modules>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
        </dependency>


        <!--        添加Servlet依赖包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>



</project>

1.4 使用注解开发

在这里插入图片描述

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


    <!--    配置DispatcherServlet :注册Servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <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>

    <!--表示所有请求都会被拦截-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</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: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/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.myl.controller"/>
    <!--使MVC 不去处理静态资源(例如CSS、js)-->
    <mvc:default-servlet-handler/>
    <!--支持MVC注解驱动,使得handler和adapter完成配置-->
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀  后缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>

    </bean>


</beans>

TestController.java

package com.myl.controller;

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


/**
 * @ClassName: TestController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  16:25
 */
@Controller
// @RequestMapping("/HelloController")   表示  localhost:8080/ /HelloController/test
public class TestController {


    //设置请求的servlet
    @RequestMapping("/test")
    public String hello(Model model){

        //模型中添加数据,发给视图
        model.addAttribute("msg","Hello mvc");

        //设置想要访问的视图   WEB-INF/jsp/test.jsp
        return "test";
    }
}

2、Restful风格

package com.myl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @ClassName: Restful
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  20:16
 */

@Controller
public class RestfulController {


    //之前使用  localhost:8080/add/a=?&b=?
    //现在      localhost:8080/add/1/2
    //常用注解   @RequestMapping @GetMapping  @PostMapping

    
    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int result = a+b;
        model.addAttribute("msg",result);

        return "test";
    }
}

3、重定向和请求转发

3.1 没有视图解析器情况下Servlet

package com.myl.controller;

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

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

/**
 * @ClassName: ServletController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/29  20:45
 */
@Controller
public class ServletController {

    @RequestMapping("/test/t1")
    public String test1(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());

       // return "test";
        return "/index.jsp";

    }


    //是在没有视图解析器情况下测试

    @RequestMapping("/test/t2")
    public String test2(Model model){
        model.addAttribute("msg","aa");

        //默认的是  请求转发
//        return "/index.jsp";
        //重定向  :地址栏会显示参数  , 不能访问WEB-INF下的东西。
        //       return "redirect:/index.jsp";
        return "redirect:/test/t1";

    }
}

4、前端传递参数

package com.myl.controller;

import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * @ClassName: UserController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/29  21:30
 */

@Controller
@RequestMapping("/user")
public class UserController {


    //路径:localhost:8080/user/t1?name=myl
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //从前端接收到的参数
        System.out.println("前端接收到的参数:"+name);
        //返回结果传递给前端
        model.addAttribute("msg",name);
        //跳转视图
        return "test";
    }


    /*
        接收到的是一个对象,参数直接使用对象即可(对象有get和set方法和构造方法)
        User的属性和参数名需要一致,否则是null
     */

    @GetMapping("/t2")
    public String test2(User user){
        System.out.println("前端接收一个对象:"+user);

        return "test";
    }
}

5、乱码问题处理

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/30
  Time: 10:41
  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="/encoding/t3">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

web.xml

 <!--配置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>

test.java

@Controller
@RequestMapping("/encoding")
public class EncodingController {
    @RequestMapping("/t3")
    public String test3(String name, Model model){
        model.addAttribute("msg",name);

        return "test";
    }
}

解决失败:自定义过滤器,进行配置。

package com.kuang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {

   @Override
   public void destroy() {
  }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //处理response的字符编码
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");

       // 转型为与协议相关对象
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // 对request包装增强
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
  }

}

//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {

   private HttpServletRequest request;
   //是否编码的标记
   private boolean hasEncode;
   //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
   public MyRequest(HttpServletRequest request) {
       super(request);// super必须写
       this.request = request;
  }

   // 对需要增强方法 进行覆盖
   @Override
   public Map getParameterMap() {
       // 先获得请求方式
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
           // post请求
           try {
               // 处理post乱码
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
           // get请求
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) { // 确保get手动编码逻辑只运行一次
               for (String parameterName : parameterMap.keySet()) {
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
                       for (int i = 0; i < values.length; i++) {
                           try {
                               // 处理get乱码
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }

   //取一个值
   @Override
   public String getParameter(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // 取回参数的第一个值
  }

   //取所有值
   @Override
   public String[] getParameterValues(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

6、JSON

6.1 使用第三方工具 Jackson

pom.xml

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

springmvc-servlet.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>

UserController.java

package com.myl.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName: UserController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/30  11:18
 */
//@RestController   类中所有的方法都将返回字符串,不走视图解析器
@Controller
public class UserController {

    @RequestMapping("/j1")
    //ResponseBody 不走视图解析器,直接返回一个字符串,配合@Controller使用
    @ResponseBody
    public String json1() throws JsonProcessingException {
        //jackson的对象
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(1,"孟哈哈",18);
        //调用方法将value转化为String
        String users = mapper.writeValueAsString(user);

        return users;
    }
}


    @RequestMapping("/j2")
    @ResponseBody
    public String test1() throws JsonProcessingException {

        Date date = new Date();
        return JSONutils.getJson(date,"yyy-MM-dd HH:mm:ss");
    }

工具类:

package com.myl.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

/**
 * @ClassName: JSONutils
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/30  16:47
 */
public class JSONutils {

    public static String getJSON(Object o ) throws JsonProcessingException {
        return getJson(o,"yyy-MM-dd HH:mm:ss");
    }



    public static String getJson(Object o,String dataFormat) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //关闭默认时间戳显示方式,从1970年到现在所经历的毫秒数
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dataFormat);
        //将自定义日期格式set进去
        mapper.setDateFormat(simpleDateFormat);

        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

6.2 使用第三方工具FastJson

   <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

 @RequestMapping("/j3")
    @ResponseBody
    public String test2() throws JsonProcessingException {


        //
        List<User> userList = new ArrayList<>();

        User user1 = new User(1,"lala",3);
        User user2 = new User(2,"lala",4);
        User user3 = new User(3,"lala",5);
        User user4 = new User(4,"lala",6);

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        //使用alibaba的FastJson包
        return JSON.toJSONString(userList);
    }

7、Ajax简单使用

7.1、使用jquery的Ajax

jQuery Ajax本质就是 XMLHttpRequest,进行了封装,方便调用!

jQuery.ajax(...)
     部分参数:
           url:请求地址
           type:请求方式,GET、POST(1.9.0之后用method)
       headers:请求头
           data:要发送的数据
   contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
         async:是否异步
       timeout:设置请求超时时间(毫秒)
     beforeSend:发送请求前执行的函数(全局)
       complete:完成之后执行的回调函数(全局)
       success:成功之后执行的回调函数(全局)
         error:失败之后执行的回调函数(全局)
       accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
       dataType:将服务器端返回的数据转换成指定类型
         "xml": 将服务器端返回的内容转换成xml格式
         "text": 将服务器端返回的内容转换成普通文本格式
         "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
       "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
         "json": 将服务器端返回的内容转换成相应的JavaScript对象
       "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

简单小demo:测试失去焦点发起请求

jquery.ajax

jquery-3.6.0.js
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/31
  Time: 19:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>
      function a() {
          $.post({
            url:"${pageContext.request.contextPath}/a1",
            data:{"name":$("#username").val()},
            success:function (data,status) {
                console.log("data"+data);
                console.log("status"+status);
            },
            error:function (data) {
              console.log("data"+data);
              console.log("status"+status);
            }
          })
      }
    </script>
  </head>
  <body>


  用户名<input type="text" id="username" οnblur="a()">

  </body>
</html>

package com.myl.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: AjaxController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/31  20:00
 */
@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test(){

        return "hello";
    }

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        //从前端接收data中 name属性的值
        System.out.println("name"+name);
        
        //向前端发送响应消息
        if("meyolo".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }
}

7.2、Ajax异步加载数据

package com.myl.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @ClassName: User
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  15:32
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

 @RequestMapping("/a2")
    public List<User> a2(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("孟哈哈",18,"男"));
        userList.add(new User("孟小二",19,"男"));
        userList.add(new User("孟十一",20,"男"));

        return userList;
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>信息</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>

       $(function () {
           /*添加点击事件*/
           $("#btn").click(function () {
               /*使用Ajax获取数据
               * $>post(url  param[可以省略]  success)
               * */
              $.post("${pageContext.request.contextPath}/a2",function (data) {
                    console.log(data);
                    //进行html节点拼接
                    var html = "";
                    for (let i=0;i<data.length;i++){
                        html +="<tr>" +
                                "<td>"+data[i].name+"</td>" +
                                "<td>"+data[i].age+"</td>" +
                                "<td>"+data[i].sex+"</td>" +
                                "</tr>"
                    }
                    /*嵌入到html中*/
                    $("#content").html(html);
              })
           })
       })

    </script>
</head>
<body>


<input type="button" value="加载数据" id="btn">
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <tbody id="content">

    </tbody>
</table>
</body>
</html>

7.3、Ajax实现异步登录

package com.myl.controller;

import com.myl.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: AjaxController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/31  20:00
 */
@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test(){

        return "hello";
    }

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        //从前端接收data中 name属性的值
        System.out.println("name"+name);

        //向前端发送响应消息
        if("meyolo".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }

    @RequestMapping("/a2")
    public List<User> a2(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("孟哈哈",18,"男"));
        userList.add(new User("孟小二",19,"男"));
        userList.add(new User("孟十一",20,"男"));

        return userList;

    }

    @RequestMapping("/a3")
    public String a3(String username,String pwd){
        String msg ="";
        if(username!=null){
            if("meyolo".equals(username)){
                msg="用户名正确";
            }else{
                msg="用户名错误";
            }
        }
        if(pwd!=null){
            if("12345".equals(pwd)){
                msg="密码正确";
            }else{
                msg="密码错误";
            }
        }
        return msg;

    }
}

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 16:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

    <script>
        function a1() {
            //使用Ajax异步提交数据
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"username": $("#username").val()},    //向后端传递data中username的值
                success: function (data) {        //从后端接收data
                    if (data.toString() === "用户名正确") {
                        $("#sp").css("color","green");
                    }else{
                        $("#sp").css("color","red");
                    }
                    //嵌入到span中
                    $("#sp").html(data);
                }
            })
        }

        function a2() {
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"pwd": $("#pwd").val()},
                success: function (data) {
                    if (data.toString() === "密码正确") {
                        $("#spw").css("color","green");
                    }else{
                        $("#spw").css("color","red");
                    }
                    $("#spw").html(data);
                }
            })
        }
    </script>
</head>
<body>


用户名<input type="text" id="username" οnblur="a1()">
<span id="sp"></span>
密码<input type="text" id="pwd" οnblur="a2()">
<span id="spw"></span>
</body>
</html>

注意处理乱码问题

    <!--    解决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>

8、拦截器

拦截器是基于AOP思想的具体实现

自定义拦截器

applicationContext.xml

 <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--表示拦截user下的所有请求-->
            <mvc:mapping path="/user/**"/>
            <bean class="com.myl.InterCeptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

拦截器实现类

package com.myl.InterCeptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @ClassName: LoginInterceptor
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  17:44
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        //   判断是否包含goLogin  请求
        if(request.getRequestURI().contains("goLogin")){
            return true;
        }

        //  判断是否包含 login 请求,第一次登录
        if(request.getRequestURI().contains("login")){
            return true;
        }

        //如果session不为空,直接跳转
        if(session.getAttribute("user")!=null){
            return true;
        }
        //否则去登录
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }
}

Controller类

package com.myl.controller;

import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: LoginController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  17:40
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    //WEB-INF下的页面是不能直接访问的,只能通过Controller或者Servlet访问
    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    //去登录页面
    @RequestMapping("/goLogin")
    public String goLogin() {
        return "login";
    }


    //登录
    @RequestMapping("/login")
    public String login(HttpServletRequest request, User user, Model model) {
        System.out.println("接收到的参数"+user);
        request.getSession().setAttribute("user", user);
        model.addAttribute("msg", user.getUsername());
        return "main";
    }

    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "main";
    }


}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  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>
  <a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a>
  <a href="${pageContext.request.contextPath}/user/main">首页</a>
  </body>
</html>

main.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>

<h1>首页</h1>
    ${msg} <a href="/user/logout">注销</a>

</body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
    用户名<input type="text" name="username">
    密码<input type="text" name="password">
    <input type="submit" value="提交">
</form>

</body>
</html>

A.
User: 10254
Date: 2021/4/2
Time: 17:35
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

$Title$ 登录页面 首页

main.jsp

```jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>

<h1>首页</h1>
    ${msg} <a href="/user/logout">注销</a>

</body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
    用户名<input type="text" name="username">
    密码<input type="text" name="password">
    <input type="submit" value="提交">
</form>

</body>
</html>

原文地址:https://blog.csdn.net/Meyolo_/article/details/115455419

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


开发过程中是不可避免地会出现各种异常情况的,例如网络连接异常、数据格式异常、空指针异常等等。异常的出现可能导致程序的运行出现问题,甚至直接导致程序崩溃。因此,在开发过程中,合理处理异常、避免异常产生、以及对异常进行有效的调试是非常重要的。 对于异常的处理,一般分为两种方式: 编程式异常处理:是指在代
说明:使用注解方式实现AOP切面。 什么是AOP? 面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能。 AOP底层使用动态代理。 AOP术语 连接点
Spring MVC中的拦截器是一种可以在请求处理过程中对请求进行拦截和处理的机制。 拦截器可以用于执行一些公共的操作,例如日志记录、权限验证、数据转换等。在Spring MVC中,可以通过实现HandlerInterceptor接口来创建自定义的拦截器,并通过配置来指定拦截器的应用范围和顺序。 S
在 JavaWeb 中,共享域指的是在 Servlet 中存储数据,以便在同一 Web 应用程序的多个组件中进行共享和访问。常见的共享域有四种:ServletContext、HttpSession、HttpServletRequest、PageContext。 ServletContext 共享域:
文件上传 说明: 使用maven构建web工程。 使用Thymeleaf技术进行服务器页面渲染。 使用ResponseEntity实现下载文件的功能。 @Controller public class FileDownloadAndUpload { @GetMapping(&quot;/file/d
创建初始化类,替换web.xml 在Servlet3.0环境中,Web容器(Tomcat)会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringS
在 Web 应用的三层架构中,确保在表述层(Presentation Layer)对数据进行检查和校验是非常重要的。正确的数据校验可以确保业务逻辑层(Business Logic Layer)基于有效和合法的数据进行处理,同时将错误的数据隔离在业务逻辑层之外。这有助于提高系统的健壮性、安全性和可维护
什么是事务? 事务(Transaction)是数据库操作最基本单元,逻辑上一组操作,要么都成功,要么都失败,如果操作之间有一个失败所有操作都失败 。 事务四个特性(ACID) 原子性 一组操作要么都成功,要么都失败。 一致性 一组数据从事务1合法状态转为事务2的另一种合法状态,就是一致。 隔离性 事
什么是JdbcTemplate? Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作。 准备工作 引入jdbcTemplate的相关依赖: 案例实操 创建jdbc.properties文件,配置数据库信息 jdbc.driver=com.mysql.cj.
SpringMVC1.MVC架构MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范是将业务逻辑、数据、显示分离的方法来写代码MVC主要作用是:降低了视图和业务逻辑之间的双向耦合MVC是一个架构模型,不是一种设计模式。1.model(模型)数据模型,提供要展示的数据,因此包
SpringMVC学习笔记1.SpringMVC应用1.1SpringMVC简介​SpringMVC全名叫SpringWebMVC,是⼀种基于Java的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于SpringFrameWork的后续产品。​MVC全名是ModelViewController,是模型(model)-视图(view)-控制器(co
11.1数据回显基本用法数据回显就是当用户数据提交失败时,自动填充好已经输入的数据。一般来说,如果使用Ajax来做数据提交,基本上是没有数据回显这个需求的,但是如果是通过表单做数据提交,那么数据回显就非常有必要了。11.1.1简单数据类型简单数据类型,实际上框架在这里没有
一、SpringMVC简介1、SpringMVC中重要组件DispatcherServlet:前端控制器,接收所有请求(如果配置/不包含jsp)HandlerMapping:解析请求格式的.判断希望要执行哪个具体的方法.HandlerAdapter:负责调用具体的方法.ViewResovler:视图解析器.解析结果,准备跳转到具体的物
1.它们主要负责的模块Spring主要应用于业务逻辑层。SpringMVC主要应用于表现层。MyBatis主要应用于持久层。2.它们的核心Spring有三大核心,分别是IOC(控制反转),DI(依赖注入)和AOP(面向切面编程)。SpringMVC的核心是DispatcherServlet(前端控制器)。MyBatis的核心是ORM(对
3.注解开发Springmvc1.使用注解开发要注意开启注解支持,2.注解简化了,处理映射器和处理适配器,只用去管视图解析器即可案例代码:1.web.xml,基本不变可以直接拿去用<!--调用DispatcherServlet--><servlet><servlet-name>springmvc</servlet-name>
拦截器概述SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。**过滤器与拦截器的区别:**拦截器是AOP思想的具体应用。过滤器servlet规范中的一部分,任何javaweb工程都可以使用
<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="
学习内容:1、SSH&SSM2、Spring3、Struts2&SpringMVC4、Hibernate&MyBatis学习产出:1.SSH和SSM都是有Spring框架的,他们两个差不多。2.Spring分为四个模块,持久层,表示层,检测层,还有核心层,核心层分为2个关键核心功能。分别为,控制反转(IOC),依赖注入(DI),和面向切面编程
一、SpringMVC项目无法引入js,css的问题具体原因是css和js等被SpringMVC拦截了:解决方案:在spring-mvc.xml中配置<mvc:default-servlet-handler/><?xmlversion="1.0"encoding="UTF-8"?><beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
开发环境:Eclipse/MyEclipse、Tomcat8、Jdk1.8数据库:MySQL前端:JavaScript、jQuery、bootstrap4、particles.js后端:maven、SpringMVC、MyBatis、ajax、mysql读写分离、mybatis分页适用于:课程设计,毕业设计,学习等等系统介绍