AJAX displays data in JSON format. The hql statement query corresponds to a class.

Source: Internet
Author: User

Front-End Interface

<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>







My JSP 'index. jsp 'starting page





<Script type = "text/javascript" src = "js/jquery-1.9.1.js"> </script>
<Script type = "text/javascript">
Function showplus (provinceid ){
// Four parameters need to be passed
// 1: Submission path; 2: Passing parameters using objects. Each parameter is passed as an attribute of objects.
// 3: callback function 4: data type. You can select text, xml, or json format.
$. Post ("<% = basePath %> province_showplus.action", {provinceid: provinceid}, showplusCallback, "json ");
}
// JQuery automatically converts the returned string to an object or array and returns the string directly using the callback function parameters.
Function showplusCallback (array ){

// Use the selector to retrieve the drop-down list object
Var citySelect = $ ("# city ");
// Locate the page element to be deleted and call the delete operation
$ ("# City option: gt (0)"). remove (); // avoid overlapping cities under the province selected next time
// Cyclically obtain the id and cname
For (var I = 0; I var cid = array [I]. cid;
Var cname = array [I]. cname;
// JQuery creates page elements and concatenates them directly using strings.
Var option =""+ Cname +"";
// Set option to a subnode of city select
CitySelect. append (option );
}
}
</Script>


Test it.


-- Select -- $ {P. pname}
-- Select --


Action class

Package com. kane. action;
Import java. io. PrintWriter;
Import java. util. Iterator;
Import java. util. List;
Import javax. servlet. http. HttpServletResponse;
Import org. apache. struts2.ServletActionContext;
Import org. json. JSONArray;
Import org. json. JSONObject;
Import com. kane. pojo. City;
Import com. kane. pojo. Province;
Import com. kane. service. IProvinceService;
Import com. opensymphony. xwork2.ActionSupport;


Public class ProvinceAction extends ActionSupport {
Private IProvinceService provinceServiceImpl;
Private List AllProvince;
Public List GetAllProvince (){
Return allProvince;
}
Public void setAllProvince (List AllProvince ){
This. allProvince = allProvince;
}
Public int getProvinceid (){
Return provinceid;
}
Public void setProvinceid (int provinceid ){
This. provinceid = provinceid;
}
Private int provinceid;
Public IProvinceService getProvinceServiceImpl (){
Return provinceServiceImpl;
}
Public void setProvinceServiceImpl (IProvinceService provinceServiceImpl ){
This. provinceServiceImpl = provinceServiceImpl;
}

// Click test. Enter the action first.
Public String indexPre () throws Exception {
AllProvince = provinceServiceImpl. findAll ();

Return "index ";
}
/**
* AJAX call method, return null,
*
* @ Return
* @ Throws Exception
*/
Public String showplus () throws Exception {
// Json String concatenation, high efficiency of single-thread stringbuffer and high efficiency of multi-thread stringbuilder
StringBuilder sBuilder = new StringBuilder ();
List List = provinceServiceImpl. showplus (provinceid );
Iterator Iter = list. iterator ();
/* SBuilder. append ("[");

Int index = 0;
While (iter. hasNext ()){
City city = iter. next ();
If (index> 0 ){
SBuilder. append (","); // except the first one, each object is preceded by a comma
}
SBuilder. append ("{'cid':" + city. getCid ());
SBuilder. append (",");
SBuilder. append ("'cname': '" + city. getCname () + "'");
SBuilder. append ("}");
Index ++;
}
SBuilder. append ("]"); */

// Use the class provided by the org. json package to spell the content
// Create an array
JSONArray array = new JSONArray ();

While (iter. hasNext ()){
City c = iter. next ();
JSONObject obj = new JSONObject ();
// Set attributes for the object, similar to Map
Obj. put ("cid", c. getCid ());
Obj. put ("cname", c. getCname ());
Array. put (obj );
}
HttpServletResponse response = ServletActionContext. getResponse ();
// Set the encoding to prevent garbled data
Response. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/html"); // This method is used for strings and json. xml uses text/xml
// Printwriter must be used to write data to the foreground.
PrintWriter out = response. getWriter ();
Out. print (array); // The array corresponds to the parameters of the foreground callback function.
Out. close (); // step 4 of ajax
Return null;
}
}


Action configuration file


Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">













Display result



DaoImpl

Package com. kane. dao. Impl; <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Signature + signature + CnB1YmxpYyBMaXN0PENpdHk + IGZpbmRCeUlkKEludGVnZXIgaWQpIHRocm93cyBFeGNl CHRpb24gewo8YnI + ClN0cmluZyBocWw9 "FROM City AS c WHERE c. province. pid =? "; // Corresponds to the pojo class
List All = super. getHibernateTemplate (). find (hql, id );
Return all;
}


}

// Click the province to display the corresponding city list


To create a test case, You must select testcase 4.0 when creating a test case.


ServiceImpl


Package com. kane. service. Impl;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;
Import com. kane. dao. ICity;
Import com. kane. dao. IProvince;
Import com. kane. pojo. City;
Import com. kane. pojo. Province;
Import com. kane. service. IProvinceService;
/**
* AOP solves preprocessing and disconnection.
* @ Author lenovo
*
*/
Public class ProvinceServiceImpl implements IProvinceService {
Private IProvince provinceImpl;
Private ICity cityImpl;
Public ICity getCityImpl (){
Return cityImpl;
}

Public void setCityImpl (ICity cityImpl ){
This. cityImpl = cityImpl;
}


Public IProvince getProvinceImpl (){
Return provinceImpl;
}


Public void setProvinceImpl (IProvince provinceImpl ){
This. provinceImpl = provinceImpl;
}

Public void delete (int id) throws Exception {
// TODO Auto-generated method stub

}


Public void insert (Province pro) throws Exception {
// TODO Auto-generated method stub

}

Public List InsertPre () throws Exception {
// TODO Auto-generated method stub
Return null;
}

Public Map List (int pageNo, int pageSize, String keyword,
String column) throws Exception {
Map Map = new HashMap ();
Map. put ("allProvince", provinceImpl. findByPage (pageNo, pageSize, column, keyword ));
Map. put ("allCount", provinceImpl. getCount (column, keyword ));
Return map;
}


Public List Showplus (int pid) throws Exception {
List List = cityImpl. findById (pid );
Return list;
}
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.