Spring MVC webapp在打开新的浏览器会话时重建两个视图

时间:2015-05-20 21:24:58

标签: java spring-mvc

我有一个java spring mvc webapp,它构建一个状态表,使ajax调用每3秒更新一次ping状态,每5分钟更新一次性能/健康状态。它工作正常,但唯一的事情是我添加了spring安全性,每当第二个用户从另一个页面登录时,它会重置两个视图而不是仅构建新视图。如何使其成为每个新用户会话都有自己的更新视图而不影响其他打开的浏览器会话?

这是我的jsp页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true" %>
<html>
<head>
<title>Site Connector</title>
<link rel="stylesheet" type="text/css" href="pages/styles/main.css">
<link rel="colorSchemeMapping" href="pages/styles/colorschememapping.xml">
<script type="text/javascript" src="pages/scripts/jquery-1.11.2.min.js"></script>

<script type="text/javascript">

function updateReachability() {
    $.ajax({
        url: 'updatePing',
        type: 'GET',
        success: function(data) {
            $('#site').html(data);
        }
    });
}

function updateStatus() {
    $.ajax({
        url: 'updateStatus',
        type: 'GET',
        success: function(data) {
            $('#site').html(data);
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    updateStatus();
    setInterval(updateStatus, 300000);
    setInterval(updateReachability, 3000);
    }, false);

</script>

</head>

<body lang=EN-US link=blue vlink=purple style='tab-interval:.5in'>

<div id="site">
<div id="upper_left">          
                <img src="pages/sickLogo.gif" alt="SICK Inc. logo"/>
                <br />
                <br />
                <br />
</div>
<div id="upper_right">
    <c:if test="${pageContext.request.userPrincipal.name != null}">
        <c:url var="logoutUrl" value="/logout"/>
        <form action="${logoutUrl}" method="post" id="logoutForm">
            Logged in as: ${pageContext.request.userPrincipal.name} <input type="submit" value="logout" />
            <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
        </form>
    </c:if>
</div>

<h1>Site Connector</h1>

<table>
    <tr>
        <th>IP Address</th>
        <th>Facility Name</th>
        <th>URL</th>
        <th>Health Status</th>
        <th>Performance Status</th>
    </tr>

    <c:forEach items="${site.hubs}" var="hub">
    <tr>
        <td bgcolor="${hub.pingStatus}">${hub.ipAddress}</td>
        <td>${hub.siteName}</td>
        <td><a href="${hub.url}" target="_blank">${hub.url}</a></td>
        <td bgcolor="${hub.healthStatus}"></td>
        <td bgcolor="${hub.performanceStatus}"></td>
    </tr>
    </c:forEach>
</table>
</div>

</body>
</html>

这是我的控制器类:

@Controller
public class SiteController {

private static final Logger logger =     Logger.getLogger(SiteController.class.getName());

private static String osName = System.getProperty("os.name");

private SiteManager manager = new SiteManager();

private SiteStatus site = new SiteStatus();

private ModelAndView model = new ModelAndView("SiteConnectorPage");

private boolean checkPing = true;

//method to run on initialization to build site list table from file
@RequestMapping("/connector")
public ModelAndView init() {

    System.out.println("Connector method called");

    //call method to create the list of error codes to search for
    try
    {
        if(osName.matches("^.*Windows.*$"))
        {
            //change file location to C:/SVP/hub-connector/site-list/SiteList.csv
            site = manager.buildSiteStatus("C:/p4_dominer/SiteConnector/SiteList.csv", site);
            //set the ping status and URL's for each hub
            if(!site.getHubs().isEmpty())
            {
                //set URL's for each hub and determines their reachability status
                manager.buildURL(site.getHubs(), true);
            }
            else
            {
                logger.error("Site List is empty, please check contents of input file");//throw empty list exception
            }
        }
        else //path to Linux location
        {
            site = manager.buildSiteStatus("/home/engineering/SVP/site-connector/site-list/SiteList.csv", site);

            if(!site.getHubs().isEmpty())
            {
            //set URL's for each hub and determines their reachability status
            manager.buildURL(site.getHubs(), false);
            }
            else
            {
                logger.error("Site List is empty, please check contents of input file");//throw empty list exception
            }
        }

    }
    catch (IOException e)
    {
        logger.error(e.getMessage());
    }
    model.addObject("site", site);
    return model;
}


//method to update ping status
@RequestMapping(value = "/updatePing", method = RequestMethod.GET)
public ModelAndView updatePingStatus()
{
    if(checkPing) {
        try
        {
            if(osName.matches("^.*Windows.*$"))
            {
                System.out.println("updatePing method called");
                //set URL's for each hub and determines their reachability status
                manager.buildURL(site.getHubs(), true);
            }
            else
            {
                //set URL's for each hub and determines their reachability status
                manager.buildURL(site.getHubs(), false);
            }
        }
        catch (IOException e)
        {
            logger.error(e.getMessage());
        }
    }

    return model;

}

@RequestMapping(value="/customLogin", method = RequestMethod.GET)
public ModelAndView loginPage(@RequestParam(value="error", required=false) String error,
                              @RequestParam(value="logout", required=false) String logout)
{
    ModelAndView loginModel = new ModelAndView("customLogin");

    if(error != null) {
        loginModel.addObject("error", "Login was unsuccessful, Please Try Again.");
    }
    if(logout != null) {
        loginModel.addObject("msg", "You've been logged out successfully.");
    }

    return loginModel;
}

@RequestMapping(value="/updateStatus", method = RequestMethod.GET)
public ModelAndView updateStatus()
{
    System.out.println("updateStatus method called");
    //set checkPing to false so updatePingStatus method doesn't update model concurrentlly which was causing the table to flash
    checkPing = false;
    if(osName.matches("^.*Windows.*$"))
    {

        /*test code */long startTime = System.nanoTime();
        manager.getStatusData(site.getHubs(), site.getDeviceErrors(), true);
        /*test code */long endTime = System.nanoTime();
        /*test code */long duration = (endTime - startTime) / 1000000;
        /*test code*/logger.info("updateStatus took " + duration + " ms");
    }
    else
    {
        manager.getStatusData(site.getHubs(), site.getDeviceErrors(), false);
    }
    checkPing = true;

    return model;
}

}

这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/j2ee"   xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

<servlet>
<servlet-name>connector</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>connector</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/connector-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<welcome-file-list>
<welcome-file>customLogin.jsp</welcome-file>
</welcome-file-list>
</web-app>

这是我的servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<context:component-scan base-package="com.sick.controller" />
<mvc:resources mapping="/pages/**" location="/pages/" />
<mvc:annotation-driven />

<beans:bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/pages/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<http pattern="/pages/**" security="none"/>

<http auto-config="true">
    <intercept-url pattern="/login*" access="permitAll"/>
    <intercept-url pattern="/customLogin*" access="permitAll"/>
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
    <logout logout-success-url="/customLogin?logout" />
    <form-login login-page="/customLogin" authentication-failure-url="/customLogin?error" default-target-url="/connector" />
    <session-management><concurrency-control max-sessions="10" error-if-maximum-exceeded="true"/></session-management>
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="admin" password="admin" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

1 个答案:

答案 0 :(得分:0)

经过大量的谷歌搜索后,终于想出了答案。我在会话控制器类中添加了会话,以便每个客户端请求都更新自己的会话对象,而不会影响其他打开的浏览器。

@RequestMapping("/connector")
public ModelAndView init(HttpServletRequest request) {

    SiteManager manager = new SiteManager();
    ModelAndView model = new ModelAndView("SiteConnectorPage");
    SiteStatus siteStatus = new SiteStatus();
    //create session if one doesn't exist
    HttpSession session = request.getSession(true);

    System.out.println("Connector method called");

    try
    {
        if(osName.matches("^.*Windows.*$"))
        {
            siteStatus = manager.buildSiteStatus("C:/SICK/Site Connector/SiteList.csv");

            //set the ping status and URL's for each hub
            if(!siteStatus.getHubs().isEmpty())
            {
                //set URL's for each hub and determines their reachability status
                manager.buildURL(siteStatus.getHubs(), true);
            }
            else
            {
                logger.error("Site List is empty, please check contents of input file");//throw empty list exception
            }
        }
        else //path to Linux location
        {
            siteStatus = manager.buildSiteStatus("/home/engineering/SVP/site-connector/site-list/SiteList.csv");

            if(!siteStatus.getHubs().isEmpty())
            {
                //set URL's for each hub and determines their reachability status
                manager.buildURL(siteStatus.getHubs(), false);
            }
            else
            {
                logger.error("Site List is empty, please check contents of input file");//throw empty list exception
            }
        }

    }
    catch (IOException e)
    {
        logger.error(e.getMessage());
    }

    session.setAttribute("site", siteStatus);
    model.addObject("site", siteStatus);
    return model;
}