我正在开发Java Servlet。我正在使用glassfish服务器4。
最终用户通过URL参数向我发送信息,如下所示:
http://myIP:8080/TestProject/TestServlet?param1=test1¶m2=test2¶m3=test3
我从param1,param2和param3获取值,我想将它们写入数据库中。如果在数据库中写入信息时遇到SQL异常,我想抛出“ 500 Internal Server Error”,让他们知道我遇到一些技术问题并重新发送他们的请求。我想知道是否有执行此操作的默认方法,设置一些状态,显示文本...?
这是代码:
@WebServlet(urlPatterns = {"/TestServlet"}, initParams = {
@WebInitParam(name = "param1", value = ""),
@WebInitParam(name = "param2", value = ""),
@WebInitParam(name = "param3", value = "")})
public class TestServlet extends HttpServlet {
String param1;
String param2;
String param3;
boolean dbOK;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get parametars from the request
param1 = request.getParameter("param1");
param2 = request.getParameter("param2");
param3 = request.getParameter("param3");
//Input in db
dbOK = Database.saveParams(param1,param2,param3);
//Print response
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>T-Mobile Interface</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> dbOK=" + dbOK + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
您应该能够做到这一点 response.sendError(int)
编辑:是说该参数是您要发送的错误代码,因此在您的情况下为500。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句