Spring 3 MVC会话变量有多长?

时间:2012-07-20 14:16:21

标签: java spring-mvc session-variables

我正在尝试实现一种客户端分页,其中我一次只显示X条记录,然后当客户端想要查看更多数据时,我会显示下一条X记录,依此类推。为此,我尝试使用会话变量,但每次检查其值时,它都是空的。我真的不太了解Spring MVC,所以任何帮助都会受到赞赏:

@Controller
@RequestMapping(value = "/api/rest/da")
@SessionAttributes({"sessionRowKey"})
public class DAController {
    /**
     * Default constructor for DAController
     */
    public DAController() {
    }

    /**
     *  Initialize the SessionAttribute 'sessionRowKey' if it does not exist
     */
    @ModelAttribute("sessionRowKey")
    public String createSessionRowKey()
    {
        return "";
    }

在这里,我检查值是否为空,这是我将其初始化为,然后设置值:

@RequestMapping(value = "/getModelData/{namespace}/{type}/{rowkey:[^\\.]*\\.[^\\.]*}", method = RequestMethod.GET)
public
@ResponseBody
Map<String, Map<String, String>> getModelData(String namespace,
                                              String type,
                                              String rowkey,
                                              @ModelAttribute("sessionRowKey") String sessionRowKey,
                                              HttpServletRequest request)
{
    try 
    {
        ModelType modelType = ModelType.fromString(type);
        Model model;
        if(modelType == ModelType.STATISTICAL)  //page the data
        {
            //code abstracted
            List<KeyValue> records = results_arr[30].list();

            if(sessionRowKey.equals(""))
            {
                model = modelReader.readModel(namespace, modelType, rowkey);
                request.getSession().setAttribute("sessionRowKey", records.get(0).toString());
            }
            else model = modelReader.readModel(namespace, modelType, sessionRowKey);
        }
        else
        {
            model = modelReader.readModel(namespace, modelType, rowkey);
        }
    } 
    catch (Exception e) 
    {
        logger.log(Level.ERROR, "Error in DAController.getModelData: " + e.getMessage());
    }
}

每次检查会话变量时,它总是“”,会话变量有多长?

1 个答案:

答案 0 :(得分:1)

使用HttpSession参数代替@ModelAttribute注释参数(sessionRowKey),并使用此参数获取sessionRowKey。例如:

... HttpSession httpSession, ...

...

String sessionRowKey = (String)httpSession.getAttribute("sessionRowKey");

...

注意:以上内容适用于Java EE 5及更高版本。对于J2EE 1.4和之前使用HttpSession.getValue和HttpSession.setValue方法。