spring 访问html页面乱码,SpringMVC:解决乱码和静态资源访问

本文介绍了如何在SpringMVC中处理GET和POST提交时的中文乱码问题,以及解决静态资源如图片无法正常显示的策略。通过在web.xml中配置CharacterEncodingFilter解决乱码,通过在spring-mvc.xml中添加配置允许静态资源访问。同时,文章还提到了不加配置时静态资源和Controller请求的权衡。
摘要由CSDN通过智能技术生成

一.  数据准备

test.jsp

html>

Title

Controller

package io.zhangjia.springmvc.controller;

import org.springframework.stereotype.Controller;

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

@Controller

public class Test {

@RequestMapping("/test")

public String test(String name)  {

System.out.println("name = " + name);

return "test";

}

}

二.  解决乱码

在《CSS表单》一文中我们讲过,form表单提交的默认方式是get,如果想修改其提交方式,则需要添加method属性,但是如果提交方式为post,传输中文便可能发生乱码,SpringMVC也为其提供了相关的解决方案,只需要在web.xml文件中添加以下内容即可:

characterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

utf-8

characterEncodingFilter

/*

三.  静态资源访问

我们在jsp文件中,加入本地的一张图片:

html>

但是此时打开text.jsp,会发现图片无法正常显示,单独打开图片地址,会显示404,这是因为SpringMVC默认把图片的路径也当成了一个页面去处理,解决方法如下:

方法一,在spring-mvc.xml的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 http://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">

方法二:

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 http://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">

如果不添加,那么静态资源可以访问,但是Controller的请求无法访问

四.  总结

1.  解决乱码

在web.xml中添加filter、filter-mapping标签,并进行相关配置

2.  访问静态资源

方法一:在spring-mvc.xml中添加

方法二:在spring-mvc.xml中添加

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值