續上篇,改用struts2實現JQuery的ajax非同步請求
阿新 • • 發佈:2018-11-19
·······························································································································
前面的兩篇因為是在csdn文字上編寫的,可能出現很多錯誤,這次在markdown上編寫,應該錯誤會少很多,然後這次ajax請求也從上一次簡單的入門$.post方法換成了$.ajax方法,剩下改動就是刪除了servlet檔案,加入struts2框架
·······························································································································
1.導包(包括上一次GSON、Hibernate的包)
2.編寫我們的action類,可以把上一次的servlet刪了,建立一個新的類->繼承ActionSupport類->組合鍵shift+alt+s->選擇Override/Implement Methods ->找到execute方法->確定。
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import xxx.xxx.xxx.service.StrutsSearchService;
public class AjaxStruts2Hibernate extends ActionSupport{
private StrutsSearchService ss = new StrutsSearchService();
// 1.使用屬性驅動獲得頁面傳來的引數,要為屬性建立getter和setter方法
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String execute() throws Exception {
System.out.println(content);
// 2.呼叫service方法進行模糊查詢
List<String> list = ss.SearchHname(content);
System.out.println("action:"+list);
// 3.將接受結果list轉化成json格式的字串返回
Gson gson = new Gson();
String json = gson.toJson(list);
// 4.把json字串返回到index.jsp頁面
ServletActionContext.getResponse().getWriter().write(json);
//這裡因為不需要跳轉到新頁面,返回null
return null;
}
}
3.在src下新建我們的struts.xml檔案,然後配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 這個是國際化編碼,處理亂碼的,我們開發可以不寫 -->
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<!-- 這裡是開發者模式,可以支援reload,即我們改寫程式碼不用重啟伺服器就可以重新編譯 -->
<constant name="struts.devMode" value="true"></constant>
<!-- name隨便取,namespace是我們訪問action的名稱空間,extends必須繼承struts-default,否則無法享用struts2功能 -->
<package name="demo" namespace="/" extends="struts-default">
<!-- 這裡是配置action的,name就是我們後面用於訪問路徑的名字,class填寫action完整類名,method是指定將引用該類下的哪個方法 -->
<action name="AjaxStruts2Hibernate" class="xxx.xxx.xxx.action.AjaxStruts2Hibernate" method="execute">
<!-- 如果在action類中return "success",那麼將轉發到/inde.jsp中,
還可以加入type屬性,指定redirect重定向,指定chain轉發到action,
指定redirectAction重定向到action等
-->
<result name="success">/index.jsp</result>
<!-- <result name="error" type="redirectAction">
<param name="actionName">errorAction</param>
<param name="namespace">/error</param>
</result> -->
</action>
</package>
</struts>
4.在web.xml中加入sturts2核心過濾器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ajax_backstage3</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5.大功告成,剩下只用把上一次的service類該一下名字就行了
service類:
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import xxx.xxx.xxx.dao.SearchHibernateDao;
import xxx.xxx.xxx.utils.HibernateUtils;
public class StrutsSearchService {
public List<String> SearchHname(String content) {
// 管理事務
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
//呼叫dao層查詢方法
SearchHibernateDao ssd = new SearchHibernateDao();
List<String> list = ssd.searchHname(content);
System.out.println("service"+list);
tx.commit();
return list;
}
}
dao類:
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import xxx.xxx.xxx.utils.DataBase;
public class SearchDao extends DataBase {
public List<String> search(String content) throws SQLException {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
String sql = "select * from cst_linkman where lkm_name like '%"+content+"%'" ;
rs = commonQuery(sql);
while(rs.next()){
list.add(rs.getString("lkm_name"));
}
return list;
}
}
HibernateUtils:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
private static SessionFactory sf;
static{
Configuration conf = new Configuration().configure();
sf = conf.buildSessionFactory();
}
public static Session getOpenSession(){
Session session = sf.openSession();
return session;
}
public static Session getCurrentSession(){
Session session = sf.getCurrentSession();
return session;
}
}
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="JS/jquery-1.11.0.js"></script>
<script type="text/javascript">
//為搜尋繫結聚焦事件
$(function(){
$("#search").keyup(function(){
var content = $(this).val();
var returnStr = "";
$.ajax({
type:"POST",
url:"/ajax_backstage4/AjaxStruts2Hibernate",
contentType:"application/x-www-form-urlencoded",
data:{"content":content},
dataType:"json",
success:function(data){
//請求正確後的操作
if(data.length>0){
for(var i=0;i<data.length;i++){
returnStr += "<div id='div' style='padding:5px;cursor:pointer' onmouseover='overFn(this)' onmouseout='outFn(this)' onclick='clickFn(this)'>"+data[i]+"</div>";//
}
$("#div").html(returnStr);
$("#div").css("display","block");
}else{
$("#div").css("display","none");
}
},
error:function(result){
//請求失敗後的操作
}
});
});
$("#search").blur(function(){
$("#div").css("display","none");
});
})
//繫結按鈕事件
$(function(){
$("#button").click(function(){
var sub = $("#search").val();
$.ajax({
type:"POST",
url:"/ajax_backstage4/AjaxStruts2Hibernate",
contentType:"application/json",
data:JSON.stringify({"sub":sub}),
dataType:"json",
success:function(result){
//請求正確後的操作
},
error:function(result){
//請求失敗後的操作
}
});
});
})
//對div新增滑鼠移入效果
function overFn(obj){
$(obj).css("background-color","yellow");
}
//對div新增滑鼠移出效果
function outFn(obj){
$(obj).css("background-color","#F0F8FF");
}
//對div內容新增點選效果
function clickFn(obj){
$("#search").val($(obj).html());
$("#div").css("display","none");
}
</script>
<body>
<input type="text" id="search" /><input type="button" id="button" value="按鈕">
<div id="div" style="width:150px;display:none;background-color: #F0F8FF"></div>
<s:debug></s:debug>
</body>
</html>