4.0.0
net.hw.spring
SpringMVCDemo
1.0-SNAPSHOT
org.springframework
spring-core
4.3.6.RELEASE
org.springframework
spring-beans
4.3.6.RELEASE
org.springframework
spring-context
4.3.6.RELEASE
org.springframework
spring-web
4.3.6.RELEASE
org.springframework
spring-webmvc
4.3.6.RELEASE
junit
junit
4.12
log4j
log4j
1.2.17
javax.servlet
jstl
1.2
/WEB-INF/views/login.jsp
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:spring-config.xml
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc-config.xml
1
DispatcherServlet
/
Character Encoding
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
Character Encoding
/*
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
用户登录
用户登录
package net.hw.spring.webmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
/**
* Created by howard on 2017/3/3.
*/
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session) {
session.setAttribute("username", username);
if (username.equals("admin") && password.equals("12345")) {
return "success"; // 逻辑视图名
} else {
return "failure"; // 逻辑视图名
}
}
}
package net.hw.spring.bean;
import java.util.Date;
/**
* Created by howard on 2017/3/8.
*/
public class User {
private int id;
private String username;
private String password;
private String telephone;
private Date registerTime;
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
package net.hw.spring.webmvc;
import net.hw.spring.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by howard on 2017/3/8.
*/
@Controller
public class GetJsonController {
@RequestMapping(value = "/getJson", produces = "application/json; charset=utf-8")
public @ResponseBody
User getJson() {
User user = new User();
user.setId(1);
user.setUsername("萌萌哒");
user.setPassword("12345");
user.setTelephone("15889895678");
user.setRegisterTime(new Date());
user.setPopedom(1);
return user;
}
@RequestMapping(value = "/getJsonArray", produces = "application/json; charset=utf-8")
public @ResponseBody
List getJsonArray() {
List users = new ArrayList();
User user = new User();
user.setId(1);
user.setUsername("萌萌哒");
user.setPassword("12345");
user.setTelephone("15889895678");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
user = new User();
user.setId(2);
user.setUsername("李文霞");
user.setPassword("45678");
user.setTelephone("13978783456");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
user = new User();
user.setId(3);
user.setUsername("郑智化");
user.setPassword("88888");
user.setTelephone("15890903456");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
return users;
}
}
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.5.3
package net.hw.spring.webmvc;
import net.hw.spring.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by howard on 2017/3/8.
*/
@Controller
public class GetXmlController {
@RequestMapping(value = "/getXml", produces = "application/xml; charset=utf-8")
public @ResponseBody
List getXml() {
List users = new ArrayList();
User user = new User();
user.setId(1);
user.setUsername("萌萌哒");
user.setPassword("12345");
user.setTelephone("15889895678");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
user = new User();
user.setId(2);
user.setUsername("李文霞");
user.setPassword("45678");
user.setTelephone("13978783456");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
user = new User();
user.setId(3);
user.setUsername("郑智化");
user.setPassword("88888");
user.setTelephone("15890903456");
user.setRegisterTime(new Date());
user.setPopedom(1);
users.add(user);
return users;
}
}
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc-config.xml
1
DispatcherServlet
/
2、在pom.xml文件里添加依赖
4.0.0
net.hw.spring
SpringMVC4Demo
1.0-SNAPSHOT
javax
javaee-web-api
7.0
provided
javax.servlet
jstl
1.2
javax.servlet
javax.servlet-api
3.1.0
javax.servlet.jsp
jsp-api
2.2.1-b03
org.springframework
spring-webmvc
4.3.6.RELEASE
org.springframework
spring-tx
4.3.6.RELEASE
org.slf4j
slf4j-api
1.7.5
org.slf4j
jcl-over-slf4j
1.7.5
log4j
log4j
1.2.17
ch.qos.logback
logback-classic
1.0.13
ch.qos.logback
logback-core
1.0.13
ch.qos.logback
logback-access
1.0.13
junit
junit
4.12
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.5.3
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.2
true
logback: %d{HH:mm:ss.SSS} %logger{36} - %msg%n
package net.hw.springmvc4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by howard on 2017/2/25.
*/
@Configuration
@EnableWebMvc
@ComponentScan("net.hw.springmvc4")
public class MyMVCConfig {
@Bean
public InternalResourceViewResolver viewResolver () {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}
package net.hw.springmvc4;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
/**
* Created by howard on 2017/2/25.
* WebApplicaitonInitializer是Spring用来配置Servlet3.0+配置的接口,
* 从而实现了替代web.xml配置文件的作用。实现此接口将会自动被
* SpringServletContainerInitializer(用来启动Servlet3.0容器)获取到。
*/
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 创建Web应用容器
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
// 注册配置类(配置类对应以前的spring-mvc-config.xml文件)
context.register(MyMVCConfig.class);
// 与当前ServletContext关联
context.setServletContext(servletContext);
// 注册Spring MVC的前端控制器(DispatcherServlet)
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
// 过滤一切资源请求
servlet.addMapping("/");
// 设置启动加载顺序
servlet.setLoadOnStartup(1);
}
}
package net.hw.springmvc4.domain;
/**
* Created by howard on 2017/2/25.
*/
public class Person {
private Long id;
private String name;
public Person() {
}
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package net.hw.springmvc4.webmvc;
import net.hw.springmvc4.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* Created by howard on 2017/2/25.
*/
@Controller
@RequestMapping("/anno")
public class DemoAnnoController {
@RequestMapping(produces = "text/plain;charset=utf-8")
public @ResponseBody
String index(HttpServletRequest request) {
return "网址[" + request.getRequestURL() + "]可访问";
}
@RequestMapping(value = "/pathvar/{str}", produces = "text/plain;charset=utf-8")
public @ResponseBody
String demoPathVar(@PathVariable String str, HttpServletRequest request) {
return "网址[" + request.getRequestURL() + "]可访问,路径参数:" + str;
}
@RequestMapping(value = "/requestParam", produces = "text/plain;charset=utf-8")
public @ResponseBody
String passRequestParam(Long id, HttpServletRequest request) {
return "网址[" + request.getRequestURL() + "]可访问,id: " + id;
}
@RequestMapping(value = "/person", produces = "application/json;charset=utf-8")
public @ResponseBody
String passPerson(Person person, HttpServletRequest request) {
return "网址[" + request.getRequestURL() + "]可访问, person对象的id: " + person.getId()
+ ", person对象的name: " + person.getName();
}
@RequestMapping(value = {"/luzhou", "/nanjing"}, produces = "text/plain;charset=utf-8")
public @ResponseBody
String remove(HttpServletRequest request) {
return "网址[" + request.getRequestURL() + "]可访问,不同路径映射到同一个方法";
}
}
package net.hw.springmvc4.webmvc;
import net.hw.springmvc4.domain.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by howard on 2017/2/25.
*/
@RestController // 返回数据时不需要@ResponseBody
@RequestMapping("/rest")
public class DemoRestController {
@RequestMapping(value = "/getjson", produces = "application/json;charset=utf-8")
public Person getjson(Person person) {
return new Person(person.getId() + 1, person.getName() + "先生");
}
@RequestMapping(value = "/getxml", produces = "application/xml;charset=utf-8")
public Person getxml(Person person) {
return new Person(person.getId() + 1, person.getName() + "女士");
}
}
package net.hw.springmvc4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by howard on 2017/2/25.
*/
@Configuration
@EnableWebMvc
@ComponentScan("net.hw.springmvc4")
public class MyMVCConfig extends WebMvcConfigurerAdapter {
/**
* 声明视图解析器Bean,用来映射路径和实际页面的位置
*/
@Bean
public InternalResourceViewResolver viewResolver () {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
/**
* 功能:静态资源映射
* addResourceLocations指的是文件放置的目录
* addResourceHandler指的是对外暴露的访问路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").
addResourceLocations("classpath:/static/");
}
}
package net.hw.springmvc4.interceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by howard on 2017/2/25.
* 或者实现HandlerInterceptor接口
*/
public class DemoInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long startTime = (Long) request.getAttribute("startTime");
request.removeAttribute("startTime");
long endTime = System.currentTimeMillis();
System.out.println("本次请求处理时间:" + (endTime - startTime) + "ms");
request.setAttribute("handlingTime", endTime - startTime);
}
}
package net.hw.springmvc4;
import net.hw.springmvc4.interceptor.DemoInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Created by howard on 2017/2/25.
*/
@Configuration
@EnableWebMvc
@ComponentScan("net.hw.springmvc4")
public class MyMVCConfig extends WebMvcConfigurerAdapter {
/**
* 配置拦截器Bean
*/
@Bean
public DemoInterceptor demoInterceptor() {
return new DemoInterceptor();
}
/**
* 注册拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(demoInterceptor());
}
/**
* 声明视图解析器Bean,用来映射路径和实际页面的位置
*/
@Bean
public InternalResourceViewResolver viewResolver () {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
/**
* 功能:静态资源映射
* addResourceLocations指的是文件放置的目录
* addResourceHandler指的是对外暴露的访问路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").
addResourceLocations("classpath:/static/");
}
}
package net.hw.springmvc4.advice;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by howard on 2017/2/25.
*/
@ControllerAdvice // 声明控制器通知
public class ExceptionHandlerAdvice {
@ExceptionHandler (value = Exception.class)
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMessage", exception.getMessage());
return modelAndView;
}
@ModelAttribute // 所有注解了@RequestMapping的方法可获得此键值对
public void addAttribute(Model model) {
model.addAttribute("msg", "请求参数id被忽略~");
}
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
// 忽略request参数的id
webDataBinder.setDisallowedFields("id");
// 注册自定义日期编辑器
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
package net.hw.springmvc4.webmvc;
import net.hw.springmvc4.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by howard on 2017/2/25.
*/
@Controller
public class AdviceController {
@RequestMapping("/advice")
public String getSomething(@ModelAttribute("msg") String msg, Person person) {
throw new IllegalArgumentException("非常抱歉,参数有误!" + "
来自@ModelAttribute的msg: " + msg
+ "
request参数person的信息:" + person.getId() + ", " + person.getName());
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Welcome
${errorMessage}
@Controller
public class HelloController {
@RequestMapping("/")
public String hello() {
return "index";
}
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 不会忽略路径参数中“.”之后的值
configurer.setUseSuffixPatternMatch(false);
}
package org.springframework.web.servlet.config.annotation;
import java.util.List;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
public WebMvcConfigurerAdapter() {
}
public void configurePathMatch(PathMatchConfigurer configurer) {
}
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
public void addFormatters(FormatterRegistry registry) {
}
public void addInterceptors(InterceptorRegistry registry) {
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
public void addCorsMappings(CorsRegistry registry) {
}
public void addViewControllers(ViewControllerRegistry registry) {
}
public void configureViewResolvers(ViewResolverRegistry registry) {
}
public void addArgumentResolvers(List argumentResolvers) {
}
public void addReturnValueHandlers(List returnValueHandlers) {
}
public void configureMessageConverters(List> converters) {
}
public void extendMessageConverters(List> converters) {
}
public void configureHandlerExceptionResolvers(List exceptionResolvers) {
}
public void extendHandlerExceptionResolvers(List exceptionResolvers) {
}
public Validator getValidator() {
return null;
}
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
package org.springframework.web.servlet.config.annotation;
import java.util.List;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
public interface WebMvcConfigurer {
void configurePathMatch(PathMatchConfigurer var1);
void configureContentNegotiation(ContentNegotiationConfigurer var1);
void configureAsyncSupport(AsyncSupportConfigurer var1);
void configureDefaultServletHandling(DefaultServletHandlerConfigurer var1);
void addFormatters(FormatterRegistry var1);
void addInterceptors(InterceptorRegistry var1);
void addResourceHandlers(ResourceHandlerRegistry var1);
void addCorsMappings(CorsRegistry var1);
void addViewControllers(ViewControllerRegistry var1);
void configureViewResolvers(ViewResolverRegistry var1);
void addArgumentResolvers(List var1);
void addReturnValueHandlers(List var1);
void configureMessageConverters(List> var1);
void extendMessageConverters(List> var1);
void configureHandlerExceptionResolvers(List var1);
void extendHandlerExceptionResolvers(List var1);
Validator getValidator();
MessageCodesResolver getMessageCodesResolver();
}
commons-fileupload
commons-fileupload
1.3.1
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
上传文件
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
registry.addViewController("/toUpload").setViewName("upload");
}
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
// 避免中文文件名出现乱码
multipartResolver.setDefaultEncoding("utf-8");
return multipartResolver;
}
package net.hw.springmvc4.webmvc;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* Created by howard on 2017/2/25.
*/
@Controller
public class UploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
public
@ResponseBody
String upload(MultipartFile file) {
try {
File uploadFile = new File("c:/upload/" + file.getOriginalFilename());
FileUtils.writeByteArrayToFile(uploadFile, file.getBytes());
return "文件上传成功!位置:" + uploadFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败!";
}
}
}
package net.hw.springmvc4.converter;
import net.hw.springmvc4.domain.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Created by howard on 2017/2/25.
*/
public class MyMessageConverter extends AbstractHttpMessageConverter {
public MyMessageConverter() {
// 新建自定义媒体类型application/x-hw
super(new MediaType("application", "x-hw", Charset.forName("utf-8")));
}
@Override
protected boolean supports(Class clazz) {
// 表明本HttpMessageConverter只处理Person这个类
return Person.class.isAssignableFrom(clazz);
}
@Override
protected Person readInternal(Class clazz, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("utf-8"));
String[] tempArr = temp.split("-");
return new Person(new Long(tempArr[0]), tempArr[1]);
}
@Override
protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
String out = "Hello, " + person.getId() + "-" + person.getName();
httpOutputMessage.getBody().write(out.getBytes());
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
HttpMessageConverter
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
registry.addViewController("/toUpload").setViewName("upload");
registry.addViewController("/converter").setViewName("converter");
}
@Bean
public HttpMessageConverter converter() {
return new MyMessageConverter();
}
@Override
public void extendMessageConverters(List> converters) {
converters.add(converter());
}
package net.hw.springmvc4.webmvc;
import net.hw.springmvc4.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by howard on 2017/2/25.
*/
@Controller
public class ConverterController {
@RequestMapping(value = "/convert", produces = "application/x-hw")
public @ResponseBody
Person convert(@RequestBody Person person) {
return person;
}
}
请求类型如下图所示:
package net.hw.springmvc4.webmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Random;
/**
* Created by howard on 2017/2/26.
*/
@Controller
public class SseController {
@RequestMapping(value = "/push", produces = "text/event-stream")
public @ResponseBody String push() {
Random r = new Random();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "data: Testing 1, 2, 3 " + r.nextInt() + "\n\n";
}
}
<%@ page contentType="text/html;charset=utf-8" language="java" %>
SSE Demo
演示SSE技术
package net.hw.springmvc4.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;
import java.text.SimpleDateFormat;
/**
* Created by howard on 2017/2/26.
*/
@Service
public class PushService {
/**
* 声明延迟结果
*/
private DeferredResult deferredResult;
/**
* 获取异步更新
*/
public DeferredResult getAysncUpdate() {
deferredResult = new DeferredResult();
return deferredResult;
}
@Scheduled(fixedDelay = 1000)
public void refresh() {
if (deferredResult != null) {
deferredResult.setResult(new SimpleDateFormat("hh:mm:ss").format(System.currentTimeMillis()));
}
}
}
package net.hw.springmvc4.webmvc;
import net.hw.springmvc4.service.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
/**
* Created by howard on 2017/2/26.
*/
@Controller
public class AsyncController {
@Autowired
private PushService pushService;
@RequestMapping("/defer")
public @ResponseBody DeferredResult deferredCall() {
return pushService.getAysncUpdate();
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Servlet Async Support
演示Servlet3.0+异步处理方法