如果使用Ajax,如何在Servlet中不编写HTML代码 [英] How to not write HTML code in Servlet in case of Ajax

查看:59
本文介绍了如果使用Ajax,如何在Servlet中不编写HTML代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我,在Servlet中将HTML写入到response.getWriter()并不是一个好习惯,这就是JSP成为现实的原因.

I was told that writing HTML to the response.getWriter() in a Servlet is not a good practice and thats why JSP comes into picture.

但是对于Ajax,我所看到的是我必须将HTML编写到Servlet中的response.getWriter()中,以使其由JSP中XMLHttpRequest对象的responseText属性选择.

But in case of Ajax what I have seen is that I have to write HTML to the response.getWriter() in a Servlet for it to be picked by responseText property of the XMLHttpRequest object in the JSP.

Ajax是否还有其他方法可以完成相同的任务?

Is there any other way for Ajax to accomplish the same task?

这是我的例子.我有2个下拉菜单 Location 部门.当用户选择特定位置时,我会使用Ajax在部门下拉列表中显示其部门.出于测试目的,对位置和部门进行了硬编码.

This is my example. I have 2 dropdowns Location and Department. When user selects a specific location, I display its departments in Department dropdown using Ajax. For testing purpose Locations and Departments are hard-coded.

我有2个班级位置部门:

public class Location implements Serializable {
    private int id;
    private String description;
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    @Override
    public String toString() {
        return "Location [id=" + id + ", description=" + description + "]";
    }
}

public class Department implements Serializable {
    private int id;
    private String description;
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    @Override
    public String toString() {
        return "Department [id=" + id + ", description=" + description + "]";
    }
}

我有一个JSP LocationDepartment.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function locationChanged() {
    var newLocation = document.getElementById("select_location").value; 
    var ajaxCallObject = getAjaxCallObject();
    ajaxCallObject.onreadystatechange=function() {
        if (ajaxCallObject.readyState==4) {
            if (ajaxCallObject.status==200) {
                alert("locationChanged(): success of ajaxCallObject");
                document.getElementById("div_department").innerHTML = ajaxCallObject.responseText;
            } else {
                alert("locationChanged(): failure of ajaxCallObject");
            }
        }
    }

    ajaxCallObject.open("GET", "DepartmentServlet?location=" + newLocation, true);
    ajaxCallObject.send(null);  
}

function getAjaxCallObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject('Microsoft.XMLHTTP');
    }
}
</script>
</head>
<body>
<form action="">
<table>
    <tr>
        <td>Location</td>
        <td>
        <div id="div_location">
        <select id="select_location" onchange="locationChanged();">
            <option></option>
            <option id="1">Head Office</option>
            <option id="2">Regional Office</option>
        </select>
        </div>
        </td>
    </tr>
    <tr>
        <td>Department</td>
        <td>
        <div id="div_department">
        <select id="select_department">
        </select>
        </div>
        </td>
    </tr>   
</table>
</form>
</body>
</html>

这是我的servlet DepartmentServlet :

And this is my servlet DepartmentServlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("DepartmentServlet: doGet(): START -----");
    String location = null;
    List<Department> departmentList = null;
    Department department = null;
    StringBuffer sb = null;


    location = request.getParameter("location");

    if (location != null && location.equalsIgnoreCase("Head Office")) {

        departmentList = new ArrayList<Department>();

        department = new Department();
        department.setId(1);
        department.setDescription("Sales");
        departmentList.add(department);

        department = new Department();
        department.setId(2);
        department.setDescription("Support");
        departmentList.add(department);

    } else if (location != null && location.equalsIgnoreCase("Regional Office")) {

        departmentList = new ArrayList<Department>();

        department = new Department();
        department.setId(1);
        department.setDescription("Sales");
        departmentList.add(department);
    }

    sb = new StringBuffer();        
    sb.append("<select id=\"select_department\">");
    if (departmentList != null) {
        for (Department d : departmentList) {
            sb.append("<option id=\"" + d.getId() + "\">");
            sb.append(d.getDescription());
            sb.append("</option>");
        }
    }       
    sb.append("</select>");

    PrintWriter out = response.getWriter();
    out.write(sb.toString());       
}

我遇到的一个问题是,现在Servlet需要知道JSP中"部门"下拉列表的选择标签的ID是什么,即"select_department".

One problem I have is that now the Servlet needs to know what is the id of the select tag for Department dropdown in the JSP i.e. "select_department".

我更希望servlet将List作为请求属性发送.因此,基本上Servlet没有以下代码行:

I would prefer that the servlet sends the List as the request attribute instead. So basically Servlet does not have these lines of codes:

sb = new StringBuffer();        
sb.append("<select id=\"select_department\">");
if (departmentList != null) {
    for (Department d : departmentList) {
        sb.append("<option id=\"" + d.getId() + "\">");
        sb.append(d.getDescription());
        sb.append("</option>");
    }
}       
sb.append("</select>");
PrintWriter out = response.getWriter();
out.write(sb.toString());       

相反,Servlet具有以下代码行:

And instead Servlet have this line of code:

request.setAttribute("DepartmentList", departmentList);

,然后在JSP中,我可以在Ajax的回调函数中访问request的此属性,并遍历它,并构建select标签的新HTML,然后替换当前的HTML.

and then in the JSP I can access this attribute of request in the callback function of Ajax and loop through it and build the new HTML of select tag and then replace the current one.

谢谢

推荐答案

以下是 getJSON 我已在评论中提到:

Here is an example with getJSON I've mentioned in the comment:

JSP:

$(document).ready(function() {
      $.getJSON("http://localhost:8080/TestWeb/test", function(data) {
      $.each(data, function(key, val) {
        console.log(key+' '+ val);
    });
  });
});

Servlet:

Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().println(json);

这篇关于如果使用Ajax,如何在Servlet中不编写HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆