SpringMVC--redirect, filter static files, Chinese garbled processing, Ajax returns json

Filter static resource files

When we add some static resources to the jsp page, an error will occur and an exception will appear in the console.

org.springframework.web.servlet.DispatcherServlet.noHandlerFound No mapping for GET /ssm/static/img/1.png

The following is displayed in the browser:
Insert image description here

Root cause : The request configured in web.xml is mapped to all files, as shown in the figure below:
Insert image description here
The running result after the modification is completed:

Insert image description here

Solution : Make the following configuration in springMVC and use it to intercept and detect .jpg, .css, .js and other suffix files to prevent them from entering the DispatcherServlet.

<mvc:default-servlet-handler/>

Solve the problem of Chinese garbled characters

We found that when submitting a request, if the input is Chinese, the processor method will get garbled characters.
Solution: Just add a filter and set the encoding set for the request object. Just configure it in web.xml.

  <!--解决中文乱码-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Redirect

Case

NewController

package com.ff.ssm.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@org.springframework.stereotype.Controller
@RequestMapping(path = "/login")
public class Controller {
    
    
    @RequestMapping(path = "/toLogin")
    public ModelAndView toLogin() {
    
    
        //viewname为视图名,通过视图解析器查找jsp
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    //ModelAndView默认为请求转发
    @PostMapping(path = "login")
    public ModelAndView login() {
    
    
        ModelAndView mv = new ModelAndView("redirect:/login/tosuccess");
        return mv;
    }
    //跳转页面简写方式,只返回视图名称,默认是请求转发
/*
    public String login() {
        return "redirect:/login/tosuccess";
    }
*/

    @GetMapping(path = "tosuccess")
    public String tosuccess() {
    
    
        return "success";
    }

}

Create a new login page

<%--
  Created by IntelliJ IDEA.
  User: 云
  Date: 2021/5/20
  Time: 20: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>
<img src="${path}/static/img/1.png">
<form method="post" action="/ssm/login/login">
    <input type="hidden" name="mark" value="save">

    账号:<input type="text" name="account">
    <br>
    密码:<input type="password" name="pwd">
    <br>
    年龄:<input name="text" name="age">
    <br>
    出生日期:<input name="text" name="birthday">
    <br>
    <input type="submit" value="登录">
</form>
</body>
</html>

Create a new login success page

<%--
  Created by IntelliJ IDEA.
  User: 云
  Date: 2021/5/20
  Time: 21: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>
<h3>欢迎您登录成功!!!</h3>
</body>
</html>

Running results:
Note that the address visited when you first entered is different from the address where the page jumps after clicking login.
Screenshot of the first visit:
Insert image description here
Screenshot after successful login:
Insert image description here

Ajax returns json

Case:

New User

package com.ff.ssm.bean;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class User {
    
    
    private  Integer id;
    private String name;
    private  Integer age;
    //日期型的不能自动转化为String需要加 @DateTimeFormat转换
    @DateTimeFormat
    private Date birthday;

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    public Date getBirthday() {
    
    
        return birthday;
    }

    public void setBirthday(Date birthday) {
    
    
        this.birthday = birthday;
    }

    public User(Integer id, String name, Integer age, Date birthday) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}

Create new ajaxDemo.jsp

<%--
  Created by IntelliJ IDEA.
  User: 云
  Date: 2021/5/22
  Time: 17:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="${path}/static/js/jquery.1.8.3.min.js"></script>
    <script type="text/javascript">
        function save(){
    
    
         $.post("${path}/login/save",$("#formID").serialize(),function(res){
    
    
         if(res.code==200){
    
    
             alert(res.msg)
          }else{
    
    
             alert(res.msg)
             }
             });
    }

    </script>
</head>
<body>
<form id="formID">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="button" value="提交" onclick="save()">
</form>
</body>
</html>

NewController

package com.ff.ssm.controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

@org.springframework.stereotype.Controller
@RequestMapping(path = "/login")
public class Controller {
    
    
    @GetMapping(path = "toAjaxDemo")
    public String toAjaxDemo() {
    
    
        return "ajaxDemo";
    }

    @PostMapping(path = "/save")
    @ResponseBody
    public Map save(String name, String age) {
    
    
        Map map = new HashMap();
       try{
    
    
           //System.out.println(10/0);
           map.put("code", 200);
           map.put("msg", "操作成功");
           map.put("data", new LinkedList<>().add("a"));
       }catch (Exception e){
    
    
           map.put("code", 500);
           map.put("msg", "操作失败");
       }
        return map;
    }

}

Running results:
When there are no exceptions in the program, the running results
Insert image description here
When there are exceptions in the program, the running results
Insert image description here

Guess you like

Origin blog.csdn.net/crraxx/article/details/117168884