暑假项目天地图SSH整合之增加逻辑
(一)前台页面
<section class="content-header">
<ol class="breadcrumb">
<li><a href="/AdminTianditu/main/showInfo"><i
class="fa fa-dashboard"></i> 首页</a></li>
<li>更新日志管理</li>
<li class="active">添加日志</li>
</ol>
</section>
<!-- Main content -->
<section class="content"> <!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<!-- Horizontal Form -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">添加日志</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<!-- action="/AdminTianditu/changde/insert" -->
<form id="member_add_form" class="form-horizontal" method="post">
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">更新地点</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-6">
<!-- class="form-control hour" id="start_hour" -->
<select name="place" class="form-control select2"
id="update_place" style="width: 100%">
<option>常德市</option>
<option>永州市</option>
<option>株洲市</option>
<option>岳阳市</option>
<option>长沙市</option>
<option>怀化市</option>
<option>衡阳市</option>
<option>郴州市</option>
<option>张家界市</option>
<option>邵阳市</option>
<option>益阳市</option>
<option>吉首市</option>
<option>湘潭市</option>
<option>娄底市</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="update_title" class="col-sm-2 control-label">更新标题</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="update_title"
name="title" maxlength="10" placeholder="请输入更新标题" required>
</div>
</div>
<div class="form-group">
<label for="update_extra" class="col-sm-2 control-label">更新内容</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="update_extra"
name="extra" placeholder="请输入更新的日志内容"></textarea>
</div>
</div>
<div class="form-group">
<label for="patrol_date" class="col-sm-2 control-label">日期</label>
<div class="col-sm-10">
<input type="date" class="form-control pull-right"
name="updatetime" id="patrol_date"
placeholder="请输入xxxx-xx-xx格式日期">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="reset" class="btn btn-default">重置</button>
<!-- -->
<button id="member_add_button" type="submit"
class="btn btn-info pull-right" data-loading-text="添加中...">添加</button>
</div>
<!-- /.box-footer -->
</form>
</div>
<!-- /.box -->
</div>
</div>
</section>
前台JS函数中 ajax请求:
<script type="text/javascript">
$(function() {
**//定义member_add_form绑定id为member_add_form的form表单**
var $member_add_form = $("#member_add_form");
**//表单数据submit提交后触发点击事件**
$member_add_form.submit(function() {
//绑定添加按钮
var $add_btn = $("#member_add_button");
//实现提交序列化后赋值给md(百度序列化的作用)
var md = $("#member_add_form").serialize();
//弹窗显示序列化的提交结果,实现可持久化
alert($("#member_add_form").serialize());
$.ajax({ //ajax请求地址
url : "/AdminTianditu/changde/insert",
//请求类型
type : "POST",
//数据类型
dataType : "json",
//数据
data : md,
//contentType: "application/json; charset=utf-8",
beforeSend : function() {
$add_btn.button("loading");
},
complete : function() {
$add_btn.button("reset");
},
success : function(data) {
alert(data.msg);
//更新成功后返回列表
window.location.href = "/AdminTianditu/changde/showList";
if (data.success) {
$member_add_form[0].reset();
}
},
error : function(XMLHttpRequest, textStatus) {
if (textStatus === "timeout") {
alert("添加超时!");
} else {
alert("添加失败!");
}
}
});
return false;
});
})
</script>
(二)后台功能
1.Controller层接收ajax请求
@RequestMapping(value = "/insert")
@ResponseBody
public void insert(MemberDto md,HttpServletRequest request, HttpServletResponse response) throws ParseException {
System.out.println(md);
/* String title = request.getParameter("title");
String extra = request.getParameter("extra");
System.out.println("title " + title);
System.out.println("extra "+ title);
String updatetime = request.getParameter("updatetime");
System.out.println("updatetime" +updatetime);*/
System.out.println(md.getPlace());
Tianditu Changde=new Tianditu();
Changde.setTitle(md.getTitle());
Changde.setExtra(md.getExtra());
Changde.setPlace(md.getPlace());
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(md.getUpdatetime()));
Changde.setUpdatetime(date);
success = ChangdeService.save(Changde);
// 构造方法注入 Changde Changde = new Changde(title, extra,timestamp);
//success = ChangdeService.save(Changde);
if (success)
msg = "添加成功";
else
msg = "添加失败";
resultJson.put("msg", msg);
resultJson.put("success", success);
ResponseUtil.writeJson(response, resultJson);
}
2.建立实体类Tianditu,接收前端传来的各项参数。
package com.zhang.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "tianditu")
public class Tianditu implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String place;
private String title;
private String extra;
private Date updatetime;
public Tianditu() {
}
public Tianditu(String place, String title, String extra, Date updatetime) {
super();
this.title = title;
this.extra = extra;
this.updatetime = updatetime;
}
public Tianditu(int id, String place, String title, String extra, Date updatetime) {
super();
this.id = id;
this.place = place;
this.title = title;
this.extra = extra;
this.updatetime = updatetime;
}
@Id
@Column(name = "id", nullable = false, unique = true)
@GenericGenerator(name = "generator", strategy = "native")
@GeneratedValue(generator = "generator")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "title", nullable = true, length = 30)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "extra", nullable = true, length = 30)
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
@Column(name = "place", nullable = true, length = 30)
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
@Column(name = "update_time", nullable = true, length = 100)
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
@Override
public String toString() {
return "Changsha [id=" + id + ", title=" + title + ", extra=" + extra + ", updatetime=" + updatetime + "]";
}
}
3.Dao层与数据库交互
package com.zhang.dao;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.zhang.entity.PageBean;
import com.zhang.entity.Tianditu;
@Repository
public class ChangdeDao {
@Resource
private HibernateTemplate hibernateTemplate;
@Resource
private SessionFactory sessionFactory;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean save(Tianditu Changde) {
Session session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(Changde);
tx.commit();
session.close();
return true;
}
public boolean update(Tianditu Changde) {
Session session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.merge(Changde);
tx.commit();
session.close();
return true;
}
public boolean delete(int id) {
Tianditu Changde = this.findById(id);
Session session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tr = session.beginTransaction();
session.delete(Changde);
tr.commit();
session.close();
return true;
}
@SuppressWarnings("unchecked")
public List<Tianditu> find(PageBean pageBean, Tianditu s_Changde) {
//from + Entity 实体类名称 limt index,pageSize 起始行,多少条数据
//条件查询
StringBuffer sb = new StringBuffer("from Tianditu where place='常德市' order by update_time");
Session session = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query q = session.createQuery(sb.toString());
q.setFirstResult(pageBean.getStart());
q.setMaxResults(pageBean.getPageSize());
List<Tianditu> ChangdeList = q.list();
tx.commit();
session.close();
System.err.println(ChangdeList);
return ChangdeList;
}
@SuppressWarnings("unchecked")
public List<Tianditu> findAll() {
String queryString = "from Tianditu order by update_time";
return (List<Tianditu>) this.hibernateTemplate.find(queryString);
}
public Tianditu findById(int id) {
return (Tianditu) this.hibernateTemplate.get(Tianditu.class, id);
}
}
4.Service层实现增删改查功能
package com.zhang.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.zhang.dao.ChangdeDao;
import com.zhang.entity.PageBean;
import com.zhang.entity.Tianditu;
@Service
public class ChangdeService {
@Resource
private ChangdeDao ChangdeDao;
public ChangdeDao getChangdeDao() {
return ChangdeDao;
}
public void setChangdeDao(ChangdeDao ChangdeDao) {
this.ChangdeDao = ChangdeDao;
}
public boolean save(Tianditu Changde){
return ChangdeDao.save(Changde);
}
public boolean update(Tianditu Changde) {
return ChangdeDao.update(Changde);
}
public boolean delete(int id) {
return ChangdeDao.delete(id);
}
public List<Tianditu> find(PageBean pageBean,Tianditu s_Changde){
return ChangdeDao.find(pageBean, s_Changde);
}
public List<Tianditu> findAll(){
return ChangdeDao.findAll();
}
public Tianditu findById(int id){
return ChangdeDao.findById(id);
}
}
5.拦截器拦截请求,防止直接输入URL访问静态资源。
package com.zhang.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//配置拦截器
/* 1、权限检查:如检测请求是否具有登录权限,如果没有直接返回到登陆页面。
* 2、性能监控:用请求处理前和请求处理后的时间差计算整个请求响应完成所消耗的时间。
* 3、日志记录:可以记录请求信息的日志,以便进行信息监控、信息统计等。
*
*
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String URI = request.getRequestURI();
// 防止相关资源被拦截
if (URI.indexOf("/static/") > 0)
return true;
// 前台页面
if (URI.indexOf("login") > 0 || URI.indexOf("login.jsp") > 0) {
return true;
}
// 登陆验证请求,放行。
if (URI.indexOf("login") > 0)
return true;
if (request.getSession().getAttribute("admin") != null) {
return true;
}
response.sendRedirect("/AdminTianditu/login");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3)
throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception arg3) throws Exception {
}
}