上节代码中没有配置视图服务器
在配置Controller
类的RequestMapping
后,需要注意会偷偷在前面再添加该RequestMapping
的路由
package com.CakeCN.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.xml.ws.RequestWrapper;
@Controller
public class UserController {
@RequestMapping(value="/save2",method = {RequestMethod.GET, RequestMethod.POST}, params = {"username"})
public ModelAndView save2(){
/*
Model 模型,封装数据
View 视图,展示数据
*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("success.jsp");
return modelAndView;
}
@RequestMapping("/save")
public String save(){
System.out.println("Controller save running...");
return "success.jsp";
}
}
modelAndView.addObject("username","CakeCN");
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Success!!title>
head>
<body>
<h1>HelloWorld ${username}h1>
body>
html>
model用于设定数据
@RequestMapping("/save3")
public String save3(Model model){
model.addAttribute("username","CakeCN");
return "success.jsp";
}
@RequestMapping("/save3")
public String save3(Model model, HttpServletRequest req, HttpServletResponse resp){
model.addAttribute("username","CakeCN");
return "success.jsp";
}
@RequestMapping("/save3")
@ResponseBody
public String save3(){
return "Hello World";
}
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.0version>
dependency>
class tempStruct{
public String username;
public int age;
public void setAge(int age) {
this.age = age;
}
public void setUsername(String username) {
this.username = username;
}
}
@RequestMapping("/save4")
@ResponseBody
public String save4() throws Exception {
tempStruct tmp = new tempStruct();
tmp.setAge(18);
tmp.setUsername("CakeCN");
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(tmp);
}
Spring-mvc.xml
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
list>
property>
bean>
此时直接返回对象,就能帮忙转化为json格式
@RequestMapping("/save5")
@ResponseBody
public tempStruct save5(){
tempStruct tmp = new tempStruct();
tmp.setAge(18);
tmp.setUsername("CakeCN");
return tmp;
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.CakeCN.controller"/>
<mvc:annotation-driven/>
beans>
@RequestMapping("/save5")
@ResponseBody
public tempStruct save5(String username, int age){
tempStruct tmp = new tempStruct();
tmp.setAge(age);
tmp.setUsername(username);
return tmp;
}
@RequestMapping("/save5")
@ResponseBody
public tempStruct save5(tempStruct tmp){
return tmp;
}
对于自定义格式的字符串,可以通过自定义数据转换器转换为相应的对象
定义转化器实体类,实现转换器Converter
接口,并声明出转换器数据前后的类型
package com.CakeCN.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
public Date convert(String s) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
} catch (Exception e){
e.printStackTrace();
}
return date;
}
}
Spring-mvc.xml中配置转换器服务工厂并在注解驱动中引用
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.CakeCN.converter.DateConverter"/>
list>
property>
bean>
<mvc:annotation-driven conversion-service="conversionService"/>
pom.xml导包
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
Spring-mvc.xml配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"/>
<property name="maxUploadSizePerFile" value="5242800"/>
<property name="defaultEncoding" value="UTF-8"/>
bean>
文件接收控制器,注意其中MultipartFile
的参数名字要与前端页面表单中的文件名字一致
@RequestMapping("/save6")
@ResponseBody
public void save6(String name, MultipartFile uploadFile) throws Exception{
String filename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("H:\\test\\"+filename));
}
前端页面表单如此:
<body>
<form action="${pageContext.request.contextPath}/save6" method="post" enctype="multipart/form-data">
<label>名称:<input type="text" name="username"/>label>
<label>文件:<input type="file" name="uploadFile"/>label>
<label><input type="submit" value="提交"/>label>
form>
body>
之后可以在对应文件夹下找到文件
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/img/**" location="/img"/>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>