Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

java - How to "throw" JSF2 404 error?

Let's say that I have an application which manages users. You can add new user, delete them, edit detail etc. Each user has na ID and has detail page on URL like this:

..../user/detail.jsf?id=123

Now, what should happen if user with ID 123 does not exists? I think that natural reaction would be 404 standard error. Exactly the same as is outputed when you make some typo in URL (like /user/dtail.jsf). So the question is: is there such method?

Or maybe is this reaction (404) appropriate?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just attach a validator to the id view parameter and if validation fails, set error code 404 on the response.

e.g.

Consider this simple Facelet:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

    <f:metadata>
        <f:viewParam id="id" name="id" value="#{myBean.id}" validator="#{myBean.validate}"/>
    </f:metadata>

    <h:body>

        <h:outputText value="#{myBean.id}"/>

    </h:body>

</html>

And the following backing bean:

@ManagedBean
@ViewScoped
public class MyBean {

    private Long id;

    public void validate(FacesContext context, UIComponent component, Object object) {
        // Do some validation
        // And if failed:
        context.getExternalContext().setResponseStatus(404);
        context.responseComplete();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...