servlet拓展-统一响应json功能、全局异常处理
一、baseservlet
import com. fasterxml. jackson. databind. ObjectMapper ;
import teamwork. com. utils. ApiResult ;
import javax. servlet. ServletException ;
import javax. servlet. http. HttpServlet ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import java. io. IOException ;
import java. io. PrintWriter ;
import java. lang. reflect. Method ;
public class BaseServlet extends HttpServlet {
@Override
protected void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException {
String operation = req. getParameter ( "operation" ) ;
Method [ ] methods = this . getClass ( ) . getDeclaredMethods ( ) ;
for ( Method method : methods) {
if ( method. getName ( ) . equals ( operation) ) {
try {
method. invoke ( this , req, resp) ;
} catch ( Exception e) {
sendJsonResponse ( resp, new ApiResult ( 500 , "服务器内部错误" , e. getMessage ( ) ) ) ;
e. printStackTrace ( ) ;
}
}
}
}
protected static void sendJsonResponse ( HttpServletResponse response, Object responseObject) throws IOException {
ObjectMapper objectMapper = new ObjectMapper ( ) ;
String json = objectMapper. writeValueAsString ( responseObject) ;
response. setContentType ( "application/json" ) ;
PrintWriter out = response. getWriter ( ) ;
out. print ( json) ;
out. flush ( ) ;
}
}
二、用法
import javax. servlet. annotation. WebServlet ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import java. io. IOException ;
@WebServlet ( "/example" )
public class ExampleServlet extends BaseJsonServlet {
protected void doGet ( HttpServletRequest request, HttpServletResponse response) throws IOException {
ExampleObject exampleObject = new ExampleObject ( ) ;
exampleObject. setId ( 1 ) ;
exampleObject. setName ( "John Doe" ) ;
exampleObject. setAge ( 30 ) ;
sendJsonResponse ( response, exampleObject) ;
}
}