相关疑难解决方法(0)

Spring Boot - 如何在一个地方记录所有具有异常的请求和响应?

我正在用弹簧靴做休息api.我需要使用输入参数(使用方法,例如GET,POST等),请求路径,查询字符串,此请求的相应类方法,以及此操作的响应,成功和错误来记录所有请求.

举个例子:

成功要求:

http://example.com/api/users/1
Run Code Online (Sandbox Code Playgroud)

日志应该看起来像这样:

{
   HttpStatus: 200,
   path: "api/users/1",
   method: "GET",
   clientIp: "0.0.0.0",
   accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
   method: "UsersController.getUser",
   arguments: {
     id: 1 
   },
   response: {
      user: {
        id: 1,
        username: "user123",
        email: "user123@example.com"   
      }
   },
   exceptions: []       
}
Run Code Online (Sandbox Code Playgroud)

或者请求错误:

http://example.com/api/users/9999
Run Code Online (Sandbox Code Playgroud)

日志应该是这样的:

    {
       HttpStatus: 404,
       errorCode: 101,                 
       path: "api/users/9999",
       method: "GET",
       clientIp: "0.0.0.0",
       accessToken: "XHGu6as5dajshdgau6i6asdjhgjhg",
       method: "UsersController.getUser",
       arguments: {
         id: 9999 
       },
       returns: {            
       },
       exceptions: [
         {
           exception: "UserNotFoundException",
           message: "User with id 9999 not found",
           exceptionId: "adhaskldjaso98d7324kjh989",
           stacktrace: ................... …
Run Code Online (Sandbox Code Playgroud)

java logging spring spring-rest

165
推荐指数
16
解决办法
22万
查看次数

Spring MVC - 为什么不能一起使用@RequestBody和@RequestParam

使用带有Post请求的HTTP dev客户端和Content-Type application/x-www-form-urlencoded

1)只有@RequestBody

请求 - localhost:8080/SpringMVC/welcome In Body - name = abc

码-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, Model model) {
    model.addAttribute("message", body);
    return "hello";
}
Run Code Online (Sandbox Code Playgroud)

//按预期将body标记为"name = abc"

2)只有@RequestParam

请求 - localhost:8080/SpringMVC/welcome In Body - name = abc

码-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, Model model) {
    model.addAttribute("name", name);
    return "hello";
}
Run Code Online (Sandbox Code Playgroud)

//按预期将名称命名为"abc"

3)两者在一起

请求 - localhost:8080/SpringMVC/welcome In Body - name = abc

码-

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, …
Run Code Online (Sandbox Code Playgroud)

post spring spring-mvc http-post http-request-parameters

56
推荐指数
2
解决办法
10万
查看次数

我应该如何在RESTful JAX-RS Web服务中记录未捕获的异常?

我使用Jersey和Jackson在Glassfish 3.1.2下运行RESTful Web服务:

@Stateless
@LocalBean
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("users")
public class UserRestService {
    private static final Logger log = ...;

    @GET
    @Path("{userId:[0-9]+}")
    public User getUser(@PathParam("userId") Long userId) {
        User user;

        user = loadUserByIdAndThrowApplicableWebApplicationExceptionIfNotFound(userId);

        return user;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于预期的异常,我抛出适当的WebApplicationException,我对发生意外异常时返回的HTTP 500状态感到满意.

我现在想为这些意外的异常添加日志记录,但是尽管搜索,但是无法找到我应该如何处理这个问题.

没有结果的尝试

我已经尝试使用a Thread.UncaughtExceptionHandler并且可以确认它是在方法体内应用的,但是它的uncaughtException方法永远不会被调用,因为其他东西在它们到达我的处理程序之前处理未捕获的异常.

其他想法:#1

我见过一些人使用的另一个选项是ExceptionMapper,它捕获所有异常,然后过滤掉WebApplicationExceptions:

@Provider
public class ExampleExceptionMapper implements ExceptionMapper<Throwable> {
    private static final Logger log = ...;

    public Response toResponse(Throwable t) {
        if (t instanceof WebApplicationException) {
            return ((WebApplicationException)t).getResponse();
        } …
Run Code Online (Sandbox Code Playgroud)

java rest jersey jackson glassfish-3

39
推荐指数
4
解决办法
2万
查看次数

HttpServletRequestWrapper,setReadListener/isFinished/isReady的示例实现?

我正在尝试调整HttpServletRequestWrapper(请参阅如何多次读取InputStream)以便能够在过滤器中使用后读取HTTP Post主体.现在我遇到了如何实现ServletInputStream的挑战.从规范3.1开始,必须实施新的方法.

  • isFinished
  • 准备好了
  • setReadListener

我正在寻找关于如何实现这些方法的示例或一些代码.任何提示?

java spring servlets

25
推荐指数
2
解决办法
2万
查看次数

为什么HttpServletRequest输入流为空?

我有这个代码,我从请求输入流中读取输入并使用JacksonMapper转换为POJO.它在带有guice支撑的码头7容器中运行.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {
        RequestType requestType = mapper.readValue(req.getInputStream(), RequestType.class);
    } Catch(Exception ex) {
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,有时在加载时会抛出以下异常.我检查了我的客户端,我确信它发送了一个有效的json字符串.出了什么问题?Jetty 7在负载下的预期行为是什么?

java.io.EOFException: No content to map to Object due to end of input
    at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2433)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2385)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1637)
    at com.ea.wsop.user.LoginServlet.processRequest(LoginServlet.java:69)
    at com.ea.wsop.user.LoginServlet.doPost(LoginServlet.java:63)
    at com.ea.wsop.user.LoginServlet$$EnhancerByGuice$$a91c2ebd.CGLIB$doPost$0(<generated>)
    at com.ea.wsop.user.LoginServlet$$EnhancerByGuice$$a91c2ebd$$FastClassByGuice$$c6f479ee.invoke(<generated>)
    at com.google.inject.internal.cglib.proxy.$MethodProxy.invokeSuper(MethodProxy.java:228)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:72)
    at com.ea.monitor.MethodExecutionTimer.invoke(MethodExecutionTimer.java:130)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:72)
    at com.google.inject.internal.InterceptorStackCallback.intercept(InterceptorStackCallback.java:52)
    at com.ea.wsop.user.LoginServlet$$EnhancerByGuice$$a91c2ebd.doPost(<generated>)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at com.ea.wsop.user.LoginServlet$$EnhancerByGuice$$a91c2ebd.CGLIB$service$8(<generated>)
    at com.ea.wsop.user.LoginServlet$$EnhancerByGuice$$a91c2ebd$$FastClassByGuice$$c6f479ee.invoke(<generated>)
    at com.google.inject.internal.cglib.proxy.$MethodProxy.invokeSuper(MethodProxy.java:228)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:72)
    at com.ea.monitor.MethodExecutionTimer.invoke(MethodExecutionTimer.java:130)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:72) …
Run Code Online (Sandbox Code Playgroud)

java servlets jetty guice

16
推荐指数
3
解决办法
2万
查看次数

如何在Spring'HandlerMethodArgumentResolver'中多次读取请求体?

我正在尝试解决某些RequestMapping方法的某些参数,从请求体中提取值并验证它们并将它们注入到某些带注释的参数中.

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                              NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    // 1, get corresponding input parameter from NativeWebRequest
    // 2, validate
    // 3, type convertion and assemble value to return
    return null;
}
Run Code Online (Sandbox Code Playgroud)

最大的问题是我发现HttpServletRequest(get from NativeWebRequest)无法读取输入流(某些参数在请求体中)不止一次.那么我怎样才能多次检索Inputstream/ Reader或请求体?

java spring spring-mvc

16
推荐指数
1
解决办法
3万
查看次数

基于spring的组动态POJO验证

考虑以下pojo以供参考:

public class User{

    private  String username;
    private String firstName;
    private String middleName;
    private String lastName;
    private String phone;

    //getters and setters

}
Run Code Online (Sandbox Code Playgroud)

我的应用程序基本上是基于spring-boot的REST API,它公开了两个端点,一个用于创建用户,另一个用于检索用户.

"用户"属于某些类别,group-a,group-b等,我从post请求的标题中获取.

我需要在运行时验证用户数据,验证可能会因用户组而有所不同.

例如,属于组-a的用户可能将电话号码作为可选字段,而对于某些其他组,它可能是必填字段.

正则表达式也可能因其组而异.

我需要能够配置spring,以某种方式动态验证我的pojo一旦创建它们各自的验证集就会根据它们的组触发.

也许我可以创建一个yml/xml配置,允许我启用它?

我宁愿不标注我private String phone@NotNull@Pattern.

我的配置如下:

public class NotNullValidator implements Validator {
    private String group;
    private Object target;

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public Object getTarget() {
        return target;
    } …
Run Code Online (Sandbox Code Playgroud)

java validation spring jackson spring-boot

12
推荐指数
2
解决办法
2662
查看次数

H2 控制台错误:找不到适合 08001/0 的驱动程序

您好,我在 H2 控制台数据库中查看我的架构时遇到问题:

我使用弹簧靴:

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MV_STORE=FALSE;MVCC=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
Run Code Online (Sandbox Code Playgroud)

这是我的登录页面:

在此处输入图片说明

所以我在里面看到的是标准的控制台视图,没有我的表,但我的应用程序运行良好。

java spring h2 spring-boot

8
推荐指数
2
解决办法
6885
查看次数

我们为什么要包装HttpServletRequest?api提供了一个HttpServletRequestWrapper,但我们从包装请求中获得了什么?

使用HttpServletRequestWrapper包装HttpServletRequest的目的是什么?这样做我们可以获得什么好处?

java java-ee

6
推荐指数
1
解决办法
6096
查看次数

httpservlet参数为null

我有一个带有表单的jsp页面.提交后,它正在调用httpservlet类.但是所有getParamter()操作都返回null.我究竟做错了什么?

JSP

<form action="GatherController" method="post">
    <input type='text' name="a"/>
    <input type='date' name="b" />
    ...
    <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

Servlet的

@WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {

    ...

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {


        String a = request.getParameter("a");
        System.out.println(a);  

        ... 

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

- 我正在使用Tomcat v8.0

执行-doPost(...)方法,我得到的输出,System.out.println(a);这是null

java jsp tomcat servlets

5
推荐指数
1
解决办法
1061
查看次数

如何调试通过线路的所有内容(http)

我正在尝试在Glassfish 4中调试一些Rest服务,我想确切地看到通过线路发送的内容(HTTP连接).有没有办法让Glassfish打印出来?

我的项目使用Apache HTTP Client,我知道可以在那里配置它,但我无法使用我们的日志框架(java.util.logging).

编辑:或者有没有办法调试泽西岛,将打印出这个信息?

java debugging glassfish glassfish-4

2
推荐指数
1
解决办法
5278
查看次数