Spring mvc 中文乱码 日期

smvc

ThymeleafConfig 视图模板

package ws.wsj.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

@Configuration
public class ThymeleafConfig{
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        // 模板解析 templateResolver; 模板 template;
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("utf-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver view = new ThymeleafViewResolver();
        view.setCharacterEncoding("utf-8");
        view.setOrder(1);
        view.setTemplateEngine(templateEngine());
        return view;
    }
}

配置类

package ws.wsj.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.beans.propertyeditors.CharacterEditor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.SpringVersion;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.EnumSet;
import java.util.List;

//无xml配置文件
//编码过滤器配置post请求表单中文乱码
//消息转换器
@EnableWebMvc
@RestController
@Configuration
@ComponentScan(basePackages={"ws.wsj.controller"})
@Import(ThymeleafConfig.class)
public class Webinit implements WebApplicationInitializer, WebMvcConfigurer {
    @Override
    public void onStartup(ServletContext sctx) throws ServletException {
        var ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(this.getClass());
        ctx.setServletContext(sctx);

        //配置 DispatcherServlet
        ServletRegistration.Dynamic servlet = sctx.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        //配置Spring默认编码过滤器
        var fc = new CharacterEncodingFilter("utf-8");
        var ff = sctx.addFilter("fc",fc);
        //此处主要解决PrintWriter out 输出编码方式
        ff.setInitParameter("forceEncoding","true");
        ff.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD),true,"/*");
        //ff.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD),true,"/hello","/hello","/user.do","/abc");
    }

    //消息转换器
    public void configureMessageConverters(List<HttpMessageConverter<?>> c){
        //字符集 Charset
        Charset cs = Charset.forName("utf-8");
        //消息转换器 MessageConverter
        StringHttpMessageConverter shmc = new StringHttpMessageConverter();
        shmc.setDefaultCharset(cs);
        //List<MediaType> list = List.of(new MediaType("text", "html", cs),new MediaType("text", "json", cs));
        var list = List.of(MediaType.parseMediaType("text/html;charset=UTF-8"));
        shmc.setSupportedMediaTypes(list);
        c.add(shmc);

        //springmvc 对日期类型处理
        //如下配置需要引入jackson组件,主要解决json输出,面向接口开发用的
        var m2 = new MappingJackson2HttpMessageConverter();

        //设置日期格式
        ObjectMapper objectMapper = new ObjectMapper();

        var m = new JavaTimeModule();
        //LocalDateTime
        m.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        m.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //LocalDate
        m.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        m.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //LocalTime
        m.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        m.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(m);

        //java.util.Date 设置日期格式
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
        objectMapper.setDateFormat(smt);

        m2.setObjectMapper(objectMapper);
        //设置中文编码格式
        m2.setSupportedMediaTypes(List.of(MediaType.parseMediaType("application/json;charset=UTF-8")));
        c.add(m2);
    }
}

控制器

package ws.wsj.controller;

import org.springframework.core.SpringVersion;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ws.wsj.pojo.User;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller //控制器
public class IndexController {
    @RequestMapping(value = "/")
    public void index(HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.printf("<h2>hello world 徐凤年 SpringMVC[%s]</h2> ", SpringVersion.getVersion());
    }

    //通过消息转换解决的中文乱码
    @GetMapping("/index")
    @ResponseBody
    public String index(){
        return String.format("<h2>hello world 徐凤年 ,SpringMVC[%s]</h2>",SpringVersion.getVersion());
    }


    @GetMapping("/show")
    public void show(String name, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\">");
        out.println("<title>玉灵 QQ:7031633 Email:webrx@126.com</title>");
        out.println("<meta name=\"keywords\" content=\"关键字\">");
        out.println("<meta name=\"description\" content=\"简介\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Hello World  中文效果</h3>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }


    @PostMapping("/hello")
    @ResponseBody
    public String hello(String name,int id){
        System.out.println(name);
        System.out.println(id);
        return name+id;
    }


    @RequestMapping("/abc")
    public void abc(PrintWriter out){
        out.print("徐凤年");
    }

    //日期
    @GetMapping("/uus")
    @ResponseBody //响应体
    /*public User uu(){
        User user = new User(100,"徐凤年");
        return user;
    }*/
    public List<User> uus (){
        List<User> list = new ArrayList<>();
        var u = new User();
        u.setId(1);
        u.setName("徐凤年");
        u.setRegtime(new Date());
        u.setBirth(LocalDate.of(2001,06,23));
        u.setCtime(LocalDateTime.now());
        list.add(u);
        return list;
    }

    @GetMapping("/uu")
    @ResponseBody
    public User uu(){
        var u = new User();
        u.setId(2);
        u.setName("徐渭熊");
        u.setRegtime(new Date());
        u.setBirth(LocalDate.of(2002,06,23));
        u.setCtime(LocalDateTime.now());
        return u;
    }

    @GetMapping("/uud")
    @ResponseBody
    public List<LocalDate> uud(){
        List<LocalDate> list = new ArrayList<>();
        list.add(LocalDate.now());
        list.add(LocalDate.of(2001,06,23));
        return list;
    }

    @GetMapping("/uudd")
    @ResponseBody
    public LocalDateTime uudd(){
        return LocalDateTime.now();
    }

    @GetMapping("/uuda")
    @ResponseBody
    public Date uuda(){
        return new Date();
    }

    @GetMapping("/myuser")
    public String user(Model m){
        m.addAttribute("name","徐龙象");
        return "user";
    }
}

控制器

package ws.wsj.controller;

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

import java.io.PrintWriter;

import static java.lang.System.out;

//@Controller // 控制器
@RestController //加上这个一律不用视图,直接输出
@RequestMapping("/user") // 请求映射
public class HomeController {

    @GetMapping("/show")
    //@ResponseBody //响应体
    public String show(){
        return "hello";
    }

    @GetMapping("/aa")
    public void aa(PrintWriter out){
        out.print("hello world 徐凤年 printWriter");
    }

    //  /user的首页 ; @RequestMapping 啥mapping都支持
    @RequestMapping({"/","/index.html"})
    public String index(String name){
        return "user 徐凤年"+name;
    }

    @RequestMapping(value="/abc/{nn}",method=RequestMethod.GET)
    public String abc(@PathVariable("nn") String name){
        return "user 姓名:"+name;
    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>徐凤年</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>徐凤年</h3>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值