我有一个 MVC 结构的 Web 应用程序。我同时拥有application-
、session-
和request
范围数据,并且我使用定制的基于请求的 MVC 框架,类似于 Spring 和 Struts 中的框架。我已将此问题的答案用作教程。
我有一个名为 的 java 对象ShowModel
,它作为会话范围的数据传递。我使用它来跟踪用户对网页上可见组件的选择。
所有可能的可见性选择都由一个复选框表示。首次设置会话数据时,它们都设置为默认可见/选中。
我在所有复选框上都有一个监听器,它通过类名“toggle”注册更改,并通过 ajax 将其 id 和checked
/unchecked
状态发送到服务器/servlet。请参阅代码示例 1。我想说我对 ajax 的经验非常有限。
由于我的所有调用都被我的前端控制器 Servlet 拦截,我需要进行相应的操作,以执行 ajax POST
-request。此代码已成功到达并执行。请参见代码示例 2。
但是,我的问题是我的操作模式强制重定向。并且以某种神秘的方式,ajax 对象 responsetext 原来是我的索引页面的整个 html。
我的数据模型已经更新,但事实证明,由于前端控制器策略模式,这是一种错误的方法。
那么有谁知道我可以更新会话范围对象的变量而不重新加载整个页面的方法?
代码示例 1
$(document).ready(
function() {
$('.toggle').change(function() {
var id = this.value;
var checked = this.checked;
var json = new Object();
json.id = id;
json.checked = checked;
$.ajax({
url: "selectionmodelupdate",
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
$('.event').each(function (index, event) {
//Here I will put code, to update the ".event"'s to be visible or not
});
},
error:function(data,status,er) {
console.log(arguments);
alert("error: "+data+" status: "+status+" er:"+er);
}
});
});
});
});
代码示例 2
public class SelectionModelUpdateAction implements Action {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
ShowModel showModel = (ShowModel) session.getAttribute("showmodel");
AppData appData = AppData.getInstance();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if(br != null){
json = br.readLine();
}
JsonObject jsonobject = new JsonParser().parse(json).getAsJsonObject();
boolean checked = jsonobject.get("checked").getAsBoolean();
String id = jsonobject.get("id").getAsString();
if(id.equals("A")){
showModel.setASelected(checked);
response.getWriter().write("{isSuccess: true}");
return "index";
}
else if (id.equals("B")){
showModel.setBSelected(checked);
response.getWriter().write("{isSuccess: true}");
return "index";
}
else if (id.equals("C")){
showModel.setCSelected(checked);
response.getWriter().write("{isSuccess: true}");
return "index";
}
response.getWriter().write("{isSuccess: false}");
return "index";
}
}