2008年10月29日 星期三

Dynamic double combo implementation by jQuery, JSON and Java

About the "Dynamic Double Combo", I wrote it before by using DWR. And now I don't think using DWR is a good idea. If your project is combined by frameworks, like Struts, Spring ...etc. To maintain the all xml configuration files will cost lots of time.

In this example, I use jQuery, and the jQuery plugin jQuery - Select box manipulation, JSONObject, and the basic Java Servlet.

In web.xml, add these period of codes.


HelloServlet
HelloServlet


HelloServlet
/Hello



About the JSP file, remember to make the encoding consistent with the servlet.
And we have to include two javascript files, "jquery-1.2.6.min.js" and "jquery.selectboxes.pack.js". Please ignore the ".".

<%@ page language="java" pageEncoding="UTF-8"%>

< html>
< head>
< title>Dynamic double combo< /title>
< meta http-equiv=content-type content="text/html; charset=UTF-8">
< script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.3.2.min.js">< /script>
< script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.selectboxes.pack.js">< /script>
< script type="text/javascript">
$(document).ready(function(){
$("#select1").change(function(){
$("#select2").empty();
$("#select2").addOption("0","------");
$("#select2").ajaxAddOption("<%=request.getContextPath()%>/Hello",
{selVal:$("select[name='select1'] option[selected]").val()},false);
});
});
< /script>
< /head>
< body>
< select id="select1" name="select1">
< option value="A">A< /option>
< option value="B">B< /option>
< option value="C">C< /option>
< /select>
< select id="select2" name="select2">
< option value="0"> --- < /option>
< /select>
< /body>
< /html>


HelloServlet.java

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

public class HelloServlet extends HttpServlet{

public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{

try{
String val = request.getParameter("selVal");
JSONObject obj = new JSONObject();
if(val.equals("A")){
obj.put("A-1", "A-1");
}else if(val.equals("B")){
obj.put("B-1", "B-1");
}else if(val.equals("C")){
obj.put("C-1", "C-1");
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(obj.toString());
return;
}catch(Exception e){
e.printStackTrace();
}
}
}

沒有留言: