这里记录一下学习MVC的过程
首先springMVC是可以对基本类型的格式进行转换,就例如我们传数据到前端的String 类型可以转换为Integer,Float等基本类型,但是当我们想要将该String类型转换成我们自己需要的对象时,就不能够了,需要做一些处理
做自定义的类型转换器
public class ClassesM implements Converter<String, classes> {
@Override
public classes convert(String source) {
classes classes=new classes();
classes.setNumber(1);
classes.setStudentNum(52);
classes.setClassMessage("学风良好......");
return classes;
}
}
pojo
@Data
public class classes {
private int number;
private int studentNum;
private String classMessage;
}
.jsp
Controller
注册一下转换器
其中需要在容器中包含一个converters属性
<bean id="conver" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<bean class="com.example.Common.ClassesM"></bean>
</property>
</bean>
<mvc:annotation-driven conversion-service="conver"/>
bean
<?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
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">
<!-- 配置自动扫包 -->
<context:component-scan base-package="com.example.Controller"></context:component-scan>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--给逻辑视图加上前缀和后缀 -->
<!--前缀-->
<property name="prefix" value="/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="conver" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!--将我们自己自定义的转换器注册进来-->
<property name="converters">
<bean class="com.example.Common.ClassesM"></bean>
</property>
</bean>
<mvc:annotation-driven conversion-service="conver">
<!--消息转换器 -->
<mvc:message-converters>
<!-- 解决中文乱码问题 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
</bean>
<!--fastjson -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
想在浏览器显示的是JSON格式,中文乱码需要在业务方法中通过设置response的编码方式来解决,bean的设置并不起作用;
如果不需要把数据转换成json格式,bean的设置可以起到中文乱码的作用
这样就可以将后端的含有中文的数据传至 前端展示