如何强制spring-security将未经授权的用户重定向到特定页面?

时间:2013-05-24 04:54:36

标签: javascript ajax java-ee struts2 spring-security

我的应用程序完美地向服务器提交表单并显示从服务器收到的响应消息,例如“表单已提交”或“抱歉,出错了!”

但是,我需要允许所有用户访问表单页面,但只有授权用户才能提交表单。所以我使用Spring安全性,它被配置为在用户尝试访问安全页面时将用户重定向到索引页面。

到目前为止,每件事情都运行正常,但问题是,因为我使用message.jsp页面来显示服务器返回的消息,一旦未经授权的用户尝试提交表单,索引页面将显示为正文message.jsp页面,因为message.jsp页面用于显示消息,它将在我的form.jsp页面中显示index.jsp页面。

如何解决问题?或者如何在form.jsp页面上显示服务器消息以避免此问题?

form.jsp

  function Add(value){
        if(window.XMLHttpRequest)
        {
            xmlhttp = new XMLHttpRequest();
        }
        else
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                document.getElementById("msg").innerHTML = xmlhttp.responseText;
            } 
        }
        xmlhttp.open("get","add?myvalue="+value,false);
        xmlhttp.send();
    }
    .....

     form goes here

    <label id="msg"></label>

formSubmit.java

private String ServerMessage;
  public String add(){
    ....
    if(result)
      this.ServerMessage = "form is submitted";
    else
      this.ServerMessage = "sorry, something went wrong!" 
    return "successful";   
}
....

struts.xml中

<result name="successful">message.jsp</result>

message.jsp

   required library goes here
   <s:property value="ServerMessage"/> 

1 个答案:

答案 0 :(得分:2)

添加类似:

<error-page> <error-code>403</error-code> <location>/403.jsp</location> </error-page>

web.xml。如果用户无权访问给定的URL,则会抛出Http Error 403,它将基于spring-security中定义的 user_role 。 例如。

<intercept-url pattern="" access="" />

其中pattern表示您的网址格式。和访问包含可访问模式的角色。模式可以像/index/**/index本身。看看official documentation的春季安全。

(确保在特定位置形成了正确的jsp。在我的情况下, 403.jsp 位于WebContent目录下。)