欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot java对象以json返回,自定义拦截器,配置文件

程序员文章站 2022-03-02 18:15:19
...

spring boot java对象以json格式返回
类上加@RestController注解
方法上加@RequestMapping注解
如:

@RestController
public class HelloWorldController {
    
	@RequestMapping("/getUser")
    public User getUser() {
    	User user=new User();
    	user.setUserName("黄渤");
    	user.setAge("1234");
        return user;
    }
 }

如果不需要json格式的返回,直接用@Controller就可以

自定义拦截器
1.实现 Filter 接口,实现 Filter 方法
2.添加@Configuration 注解,将自定义Filter加入过滤链

package com.example.demo;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    
    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }
    
    public class MyFilter implements Filter {
		@Override
		public void destroy() {
			// TODO Auto-generated method stub
		}

		@Override
		public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
				throws IOException, ServletException {
			System.out.println("进入拦截器");
			// TODO Auto-generated method stub
			HttpServletRequest request = (HttpServletRequest) srequest;
			System.out.println("this is MyFilter,url :"+request.getRequestURI());
			filterChain.doFilter(srequest, sresponse);
		}

		@Override
		public void init(FilterConfig arg0) throws ServletException {
			// TODO Auto-generated method stub
		}
    }
}

配置文件:src/main/resources/application.properties

com.neo.title=happy new year
com.neo.description=good boy

--日志文件
logging.file=log.log

以@Controller或@RestController注解的类中添加

@Value("${com.neo.title}")
	private String title;
	@Value("${com.neo.description}")
	private String description;
	
	@RequestMapping("/config")
	public String getMessage() {
		return "title = "+title+"  description = "+description;
	}