0

I'm using Java RESTful web service (Jersey) to do a web form submission. The user submits a web form and the information is stored in MySQL database after submission. I'm using Spring JDBC for DB operations. The web form has three fields: id, name, and DOB. The id must be unique in the DB. So if the user submits a duplicate existing id field, the form should stay and alert: "ID must be unique". However, I don't know how to pass the DB unique constraint exception to the view layer in my code. My code looks like the following:

public class CustomerJDBCTemplate implements CustomerDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;


    public void create(int id, String name, Date dob) {
        String sqlStmt = "INSERT INTO Person (id, name, dob) VALUES (?, ?, ?)";

        jdbcTemplateObject.update(sqlStmt, new Integer(id), name, dob);
        System.out.println("Created Record Name = " + name);
    }

        // ......
}

The controller class in my presentation layer is:

@Path("/customer")
public class CustomerService {

    @Context UriInfo uriInfo;
    @Context HttpServletRequest request;
    @Context HttpServletResponse response;

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    CustomerJDBCTemplate dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");


    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Path("created")
    public Response createCustomer(@FormParam("id") int id,
            @FormParam("name") String name, @FormParam("dob") Date dob)
            throws ServletException, IOException {
        URI uri = URI.create(uriInfo.getPath());
        Response r;


        try {
            dbController.create(id, name, dob); //This may throw exception.

                    request.setAttribute("name", name);
            request.setAttribute("dob", dob);
            request.setAttribute("id", Integer.valueOf(id));
            RequestDispatcher dispatcher = request.getRequestDispatcher("/confirm.jsp");
            dispatcher.forward(request, response);
        } catch (DataAccessException ex) {
            String errMsg = ex.getMessage();
            System.out.println(errMsg);
        //To do: what should I put here to pass the "id already exists" information to the users?
        }

        r = Response.created(uri).build();
        return r;
    }

    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable displayForm() {
        return new Viewable("/form.html");
    }
}

In the above code, the following line may throw an exception if the enter ID already exists in the DB:

dbController.create(id, name, dob); //This may throw exception. 

So how do I catch the DB UNIQUE constraint exception and present this error information to the web form? My web form is form.html which will go to confirm.jsp if submitted info is correct. But if the entered id is existing, I want the web form to stay at the current page and prompt user the error info. So what should I write to propagate the DB error to the view layer?

Update

I've added the following line to catch the exception due to DB error:

} catch (DataIntegrityViolationException ex) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }

But this will only direct to an Internal Server Error page after the user clicks "Submit" button. So how can I make the web form stay there and prompt user "ID already exists" message when the user enters an existing ID?

4

3 回答 3

0

为什么不像使用name,dob和一样添加另一个参数id。像这样的东西:

public Response createCustomer(@FormParam("id") int id,
        @FormParam("name") String name, @FormParam("dob") Date dob)
        throws ServletException, IOException {
    URI uri = URI.create(uriInfo.getPath());
    Response r;

    String error = null;
    try {
        dbController.create(id, name, dob); //This may throw exception.

    } catch (DataAccessException ex) {
        String errMsg = ex.getMessage();
        System.out.println(errMsg);
        error = "ID already exists";
    }

    request.setAttribute("name", name);
    request.setAttribute("dob", dob);
    request.setAttribute("id", Integer.valueOf(id));
    request.setAttribute("error", error);//indicates IF there was an error or not
    RequestDispatcher dispatcher = request.getRequestDispatcher("/confirm.jsp");
    dispatcher.forward(request, response);

    r = Response.created(uri).build();
    return r;
}
于 2013-06-12T07:43:16.477 回答
0

我通常看到这样做的方式是为 id 使用一AUTO_INCREMENT ,这样数据库就可以保证您拥有唯一的 id。换句话说,你不允许用户输入 id,你在幕后为用户管理 id。

于 2013-06-11T15:46:52.280 回答
0

异常org.springframework.dao.DataIntegrityViolationExceptionDataAccessException. 这将在主键唯一违规的情况下被抛出。

您可以选择在控制器中捕获此异常,然后执行适当的操作。

try {
    dbController.create(id, name, dob); //This may throw exception.
}
catch(DataIntegrityViolationException e)
{
    // your logic for showing error message
}
catch(DataAccessException e)
{
    // general logic to handle exception
}
于 2013-06-11T15:49:38.940 回答