·······························································································································
前面的两篇因为是在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>