如何在泽西中实现servlet response.redirect?

时间:2015-11-20 07:44:38

标签: java ajax jersey-2.0

虽然我尝试使用Response.temporaryRedirect(location)和Response.seeOther(location)在jersey中实现response.redirect,但两者都不像Servlet response.sendRedirect那样工作。

我试过,

Java脚本: -

function loginFunction(){
        var password=$("#password").val();
        var username=$("#emailId").val();
        function make_base_auth(user, password) {
              var tok = user + ':' + password;
              var hash = btoa(tok);
              return "Basic " + hash;
            }
        $.ajax({
            url:'/test/login/filter',
            type:'GET',
            crossDomain: true,
            beforeSend : function(req) {
                req.setRequestHeader('Authorization', make_base_auth(username, password));
            },
            success:function(res,status,xhr){
                userToken=xhr.getResponseHeader("Authorization");
                localStorage.setItem("userToken", userToken);
                if(userToken != undefined || userToken != null){
                    window.location.href = "./index.html";
                }else{
                    $('.errmsg').html('please provide a valid credentials.')
                    $(this).load();
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                console.log("textStatus is:"+textStatus);
                }
        });
    }

泽西岛代码: -

@Path("/login")
public class UserLogin {

    private static Map<String ,Token> tokTable=new HashMap<String ,Token>();

    @GET
    @Path("/filter")
    public void filter(@Context ContainerRequestContext context){
        String authentication = filterContext.getHeaderString(HttpHeaders.AUTHORIZATION);
            if (authentication == null) {
                throw new AuthenticationException("Authentication credentials are required");
            }
            if (!authentication.startsWith("Basic ")) {
                return null;
            }
            authentication = authentication.substring("Basic ".length());
            String[] values = new String(DatatypeConverter.parseBase64Binary(authentication), Charset.forName("ASCII")).split(":");
            String username=null,givenPass=null;
            try{
                username = values[0];
                givenPass=org.glassfish.jersey.internal.util.Base64.encodeAsString( values[1]);
            }catch(Exception e){
                throw new AuthenticationException("User name and password can't be empty\r\n");
            }
        }
        User user = AuthLookUpTables.userTable.get(username);
            // Validate the extracted credentials
            if ( user == null ) {
                logger.info("USER NOT AUTHENTICATED");
                throw new AuthenticationException("Invalid username");
             }
            String password=org.glassfish.jersey.internal.util.Base64.encodeAsString(givenPass.concat(user.getSalt()));
            if ((username == null) || (password == null)) {
                throw new WebApplicationException(400);
            }
            String dbPass=org.glassfish.jersey.internal.util.Base64.encodeAsString(user.getHashedPassword().concat(user.getSalt()));
            if ( dbPass.equals(password) ) {
                logger.info("USER AUTHENTICATED");
            //SOme code using for main sever.
            } else {
                logger.info("USER NOT AUTHENTICATED");
                throw new AuthenticationException("Invalid username or password\r\n");
            }
            return user;
    }

POJO(用户): -

public class User {
        public String username;
        public String roles;
        public String salt;
        public String hashedPassword;
    //and below getter and setter methods
    }

自定义例外: -

public class AuthenticationException extends RuntimeException {

        public AuthenticationException() {
            super();
        }
        public AuthenticationException(String message) {
        super(message);

        }
    }

异常映射器: -

@Provider
    public class AuthenticationExceptionMapper implements ExceptionMapper<AuthenticationException> {
    private Logger logger=Logger.getLogger(AuthenticationExceptionMapper.class);
         @Context
         UriInfo uriInfo;
        public Response toResponse(AuthenticationException e) {
            UriBuilder builder=null;
        if (e.getMessage() != null) {
           builder=UriBuilder.fromPath(uriInfo.getBaseUriBuilder().toString()).path("..");
           return Response.temporaryRedirect(builder.build()).build();
        } else {
            return Response
                    .status(Status.UNAUTHORIZED)
                    .type("text/plain")
                    .entity(e.getMessage())
                    .build();
        }
        }

    }

这是我在开发人员工具中获得的,

enter image description here

但是,我期待服务器重定向到登录页面,我该怎么做,同样的人帮助我做到这一点。 谢谢

0 个答案:

没有答案