今天交完作业了,虽然做的不是很好,但也是自己一个人从头摸索做出来的一个东西,还是挺满足的。
整个小项目昨天完成了删除和页面更新等问题,遇到了一个很小的错误,由于疏忽一直卡着,就是String类型数据的值的比较是否相等要用String1.equals(String2)来获取是否相等,String是基本类型,这样用==是判断两个对象的地址是否相等。
还有就是页面刷新的问题,就是直接用window.location.reload();来直接刷新界面,但是页面会闪烁,至于不闪烁属于异步传输的问题,用JQuery和Ajax可以实现,时间有限,就没做这个了。
delete方法的代码如下,数据量小的时候可以用这个方法,写代码比较快捷,直接查询数据库所有对象,然后遍历进行对比查询,最好做成模糊查询,用sql语句可以实现
public String delete(){
try {
request.setCharacterEncoding("utf-8");
String deleteinfo = request.getParameter("deleteinfo");
System.out.println(deleteinfo);
JSONObject obj = (JSONObject)JSONObject.parse(deleteinfo);
String dtype = obj.get("deletetype").toString();
System.out.println(dtype);
String dpath = obj.get("deletepath").toString();
System.out.println(dpath);
//将要被返回到客户端的对象
List<Geometry> list = this.geoService.findAll();
int nCount = list.size();
for(int i = 0; i < nCount; i++) {
geometry = list.iterator().next();
String type = geometry.getType();
System.out.println(type);
String path = geometry.getGeo();
System.out.println(path);
if(type.equals(dtype) && path.equals(dpath)) {
this.geoService.deleteGeo(geometry);
this.setResult(SUCCESS);
}
list.remove(0);
}
}catch (Exception e){
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
下面贴出全部代码:
DeleteAction.java
package cn.wwx.ssh.action;
import cn.wwx.ssh.domain.Geometry;
import cn.wwx.ssh.service.GeoService;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.interceptor.ServletRequestAware;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author 信爸爸
*/
public class DeleteAction extends ActionSupport implements ServletRequestAware ,ModelDriven<Geometry> {
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private String [] results = new String[3];
private String result;
private GeoService geoService;
private JSONObject resultObj;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String[] getResults() {
return results;
}
public void setResults(String[] results) {
this.results = results;
}
public JSONObject getResultObj() {
return resultObj;
}
public void setResultObj(JSONObject resultObj) {
this.resultObj = resultObj;
}
//封装数据
private Geometry geometry = new Geometry();
@Override
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setGeoService(GeoService geoService) {
this.geoService = geoService;
}
@Override
public Geometry getModel() {
return this.geometry;
}
public String delete(){
try {
request.setCharacterEncoding("utf-8");
String deleteinfo = request.getParameter("deleteinfo");
System.out.println(deleteinfo);
JSONObject obj = (JSONObject)JSONObject.parse(deleteinfo);
String dtype = obj.get("deletetype").toString();
System.out.println(dtype);
String dpath = obj.get("deletepath").toString();
System.out.println(dpath);
//将要被返回到客户端的对象
List<Geometry> list = this.geoService.findAll();
int nCount = list.size();
for(int i = 0; i < nCount; i++) {
geometry = list.iterator().next();
String type = geometry.getType();
System.out.println(type);
String path = geometry.getGeo();
System.out.println(path);
if(type.equals(dtype) && path.equals(dpath)) {
this.geoService.deleteGeo(geometry);
this.setResult(SUCCESS);
}
list.remove(0);
}
}catch (Exception e){
e.printStackTrace();
return ERROR;
}
return SUCCESS;
}
}
SaveAction.java
package cn.wwx.ssh.action;
import cn.wwx.ssh.domain.Geometry;
import cn.wwx.ssh.service.GeoService;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.interceptor.ServletRequestAware;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import static com.opensymphony.xwork2.Action.SUCCESS;
public class SaveAction implements ServletRequestAware,ModelDriven<Geometry> {
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private String [] results = new String[3];
private String result;
private GeoService geoService;
private JSONObject resultObj;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String[] getResults() {
return results;
}
public void setResults(String[] results) {
this.results = results;
}
public JSONObject getResultObj() {
return resultObj;
}
public void setResultObj(JSONObject resultObj) {
this.resultObj = resultObj;
}
//封装数据
private Geometry geometry = new Geometry();
@Override
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setGeoService(GeoService geoService) {
this.geoService = geoService;
}
@Override
public Geometry getModel() {
return this.geometry;
}
/**
* 处理ajax请求
*/
public String save(){
try {
//polyline
request.setCharacterEncoding("utf-8");
String lpath = request.getParameter("lpath");
System.out.println(lpath);
String lpaths[] = lpath.split("%");
String lineinfo = request.getParameter("lineinfo");
String lineinfos [] = lineinfo.split("%");
//polygon
String gpath = request.getParameter("gpath");
String gpaths[] = gpath.split("%");
String goninfo = request.getParameter("goninfo");
String goninfos [] = goninfo.split("%");
//savepolyline
for(int i = 1; i < lpaths.length; i++){
List<Map<String,Integer>> list = (List<Map<String,Integer>>) JSONObject.parse(lpaths[i]);
JSONObject obj = (JSONObject)JSONObject.parse(lineinfos[i]);
results[0] = list.toString();
results[1] = obj.get("length").toString();
results[2] = obj.get("width").toString();
geometry.setType("polyline");
geometry.setGeo(results[0]);
geometry.setLength(Double.parseDouble(results[1]));
geometry.setWidth(Double.parseDouble(results[2]));
geometry.setArea(null);
geometry.setGroundtype(null);
this.geoService.saveGeo(geometry);
}
//savepolygon
for(int j = 1; j < gpaths.length; j++){
List<Map<String,Integer>> list = (List<Map<String,Integer>>) JSONObject.parse(gpaths[j]);
JSONObject obj = (JSONObject)JSONObject.parse(goninfos[j]);
results[0] = list.toString();
results[1] = obj.get("area").toString();
results[2] = obj.get("groundtype").toString();
geometry.setType("polygon");
geometry.setGeo(results[0]);
geometry.setArea(Double.parseDouble(results[1]));
geometry.setGroundtype(results[2]);
geometry.setLength(null);
geometry.setWidth(null);
this.geoService.saveGeo(geometry);
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
RedrawAction.java
package cn.wwx.ssh.action;
import cn.wwx.ssh.domain.Geometry;
import cn.wwx.ssh.service.GeoService;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.interceptor.ServletRequestAware;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import static com.opensymphony.xwork2.Action.SUCCESS;
public class RedrawAction implements ServletRequestAware,ModelDriven<Geometry> {
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private String [] results = new String[3];
private String result;
private GeoService geoService;
private JSONObject resultObj;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String[] getResults() {
return results;
}
public void setResults(String[] results) {
this.results = results;
}
public JSONObject getResultObj() {
return resultObj;
}
public void setResultObj(JSONObject resultObj) {
this.resultObj = resultObj;
}
//封装数据
private Geometry geometry = new Geometry();
@Override
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.request = httpServletRequest;
}
public void setGeoService(GeoService geoService) {
this.geoService = geoService;
}
@Override
public Geometry getModel() {
return this.geometry;
}
public String redraw(){
//将要被返回到客户端的对象
List<Geometry> list = this.geoService.findAll();
JSONObject json = new JSONObject();
String rejson = "";
int nCount = list.size();
for(int i = 0; i < nCount; i++){
String type = list.iterator().next().getType();
String path = list.iterator().next().getGeo();
double length = 0;
double width = 0;
double area = 0;
if(null != list.iterator().next().getLength()){
length = list.iterator().next().getLength();
}
if(null != list.iterator().next().getWidth()){
width = list.iterator().next().getWidth();
}
if(null != list.iterator().next().getArea()){
area = list.iterator().next().getArea();
}
String groundtype = list.iterator().next().getGroundtype();
list.remove(0);
rejson += type + ":" + path + "?" + length + "?"
+ width + "?" + area + "?" + groundtype + "%" ;
}
json.fluentPut("allpath",rejson);
this.setResult(json.toString());
//将数据以json字符串形式传到请求页面end
return SUCCESS;
}
}
GeoDao.java
package cn.wwx.ssh.dao;
import cn.wwx.ssh.domain.Geometry;
import java.util.List;
/**
* @author 信爸爸
*/
public interface GeoDao {
/**
* 添加空间图形
*/
public void saveGeo(Geometry geometry);
/**
* 修改空间图形
*/
public void updateGeo(Geometry geometry);
/**
* 删除空间图形
*/
public void deleteGeo(Geometry geometry);
public List<Geometry> findAll();
/**
* 查询空间图形属性
*/
// public String findInfor(Geometry geometry);
}
GeoDaoImmpl.java
package cn.wwx.ssh.dao.impl;
import cn.wwx.ssh.dao.GeoDao;
import cn.wwx.ssh.domain.Geometry;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.util.List;
/**
* @author 信爸爸
*/
public class GeoDaoImpl extends HibernateDaoSupport implements GeoDao {
@Override
public void saveGeo(Geometry geometry) {
this.getHibernateTemplate().save(geometry);
}
@Override
public void updateGeo(Geometry geometry) {
this.getHibernateTemplate().update(geometry);
}
@Override
public void deleteGeo(Geometry geometry) {
this.getHibernateTemplate().delete(geometry);
}
@Override
public List<Geometry> findAll() {
return this.getHibernateTemplate().find("from Geometry ");
}
}
实体类Geometry.java
package cn.wwx.ssh.domain;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Geometry {
private int id;
private String geo;
private String type;
private Double width;
private Double length;
private Double area;
private String groundtype;
@Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "geo", nullable = true, length = 1024)
public String getGeo() {
return geo;
}
public void setGeo(String geo) {
this.geo = geo;
}
@Basic
@Column(name = "type", nullable = true, length = 30)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Basic
@Column(name = "width", nullable = true, precision = 0)
public Double getWidth() {
return width;
}
public void setWidth(Double width) {
this.width = width;
}
@Basic
@Column(name = "length", nullable = true, precision = 0)
public Double getLength() {
return length;
}
public void setLength(Double length) {
this.length = length;
}
@Basic
@Column(name = "area", nullable = true, precision = 0)
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
}
@Basic
@Column(name = "groundtype", nullable = true, length = 50)
public String getGroundtype() {
return groundtype;
}
public void setGroundtype(String groundtype) {
this.groundtype = groundtype;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Geometry geometry = (Geometry) o;
if (id != geometry.id) return false;
if (geo != null ? !geo.equals(geometry.geo) : geometry.geo != null) return false;
if (type != null ? !type.equals(geometry.type) : geometry.type != null) return false;
if (width != null ? !width.equals(geometry.width) : geometry.width != null) return false;
if (length != null ? !length.equals(geometry.length) : geometry.length != null) return false;
if (area != null ? !area.equals(geometry.area) : geometry.area != null) return false;
if (groundtype != null ? !groundtype.equals(geometry.groundtype) : geometry.groundtype != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (geo != null ? geo.hashCode() : 0);
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (width != null ? width.hashCode() : 0);
result = 31 * result + (length != null ? length.hashCode() : 0);
result = 31 * result + (area != null ? area.hashCode() : 0);
result = 31 * result + (groundtype != null ? groundtype.hashCode() : 0);
return result;
}
}
配置文件Geometry.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.wwx.ssh.domain.Geometry" table="geometry" schema="mappolygon">
<id name="id">
<column name="id" sql-type="int(30)"/>
</id>
<property name="geo">
<column name="geo" sql-type="varchar(1024)" length="1024" not-null="true"/>
</property>
<property name="type">
<column name="type" sql-type="varchar(30)" length="30" not-null="true"/>
</property>
<property name="width">
<column name="width" sql-type="double(30)" precision="30" not-null="true"/>
</property>
<property name="length">
<column name="length" sql-type="double(30)" precision="30" not-null="true"/>
</property>
<property name="area">
<column name="area" sql-type="double(50)" precision="50" not-null="true"/>
</property>
<property name="groundtype">
<column name="groundtype" sql-type="varchar(50)" length="50" not-null="true"/>
</property>
</class>
</hibernate-mapping>
GeoService.java
package cn.wwx.ssh.service;
import cn.wwx.ssh.domain.Geometry;
import java.util.List;
/**
* @author 信爸爸
*/
public interface GeoService {
public void saveGeo(Geometry geometry);
public void updateGeo(Geometry geometry);
public void deleteGeo(Geometry geometry);
public List<Geometry> findAll();
}
GeoServiceImpl.java
package cn.wwx.ssh.service.impl;
import cn.wwx.ssh.dao.GeoDao;
import cn.wwx.ssh.domain.Geometry;
import cn.wwx.ssh.service.GeoService;
import java.util.List;
/**
* @author 信爸爸
*/
public class GeoServiceImpl implements GeoService{
private GeoDao geoDao;
public void setGeoDao(GeoDao geoDao) {
this.geoDao = geoDao;
}
@Override
public void saveGeo(Geometry geometry) {
this.geoDao.saveGeo(geometry);
}
@Override
public void updateGeo(Geometry geometry) {
this.geoDao.updateGeo(geometry);
}
@Override
public void deleteGeo(Geometry geometry) {
this.geoDao.deleteGeo(geometry);
}
@Override
//查询所有部门的方法
public List<Geometry> findAll() {
return geoDao.findAll();
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置连接池属性 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 指定连接数据库连接池的最大连接数 -->
<property name="maxPoolSize" value="20"/>
</bean>
<!-- 配置Hibernate SessionFactory相关属性 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 注入连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.autoReconnect">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/mappolygon</prop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key=""/>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:cn/wwx/ssh/domain/Geometry.hbm.xml</value>
</list>
</property>
</bean>
<!--配置Dao-->
<bean id="geoDao" class="cn.wwx.ssh.dao.impl.GeoDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--配置Service-->
<bean id="geoService" class="cn.wwx.ssh.service.impl.GeoServiceImpl">
<property name="geoDao" ref="geoDao"/>
</bean>
<!-- 配置Spring事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--增强事务-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save * "/>
<tx:method name="update * "/>
<tx:method name="delete * "/>
<tx:method name="find * " read-only="true"/>
</tx:attributes>
</tx:advice>
<!--<!–切面:将切入点与通知关联–>-->
<!--<aop:config>-->
<!--<aop:advisor advice-ref="txAdvice" pointcut="cn.wwx.ssh.service. * . * (...)"/>-->
<!--</aop:config>-->
<!-- 开启注解式事务管理 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="saveAction" class="cn.wwx.ssh.action.SaveAction" scope="prototype">
<property name="geoService" ref="geoService"/>
</bean>
<bean id="redrawAction" class="cn.wwx.ssh.action.RedrawAction" scope="prototype">
<property name="geoService" ref="geoService"/>
</bean>
<bean id="deleteAction" class="cn.wwx.ssh.action.DeleteAction" scope="prototype">
<property name="geoService" ref="geoService"/>
</bean>
</beans>
jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssh_employee?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
log4j.properties
log4j.rootLogger=DEBUG,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.s=console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.appender.org.apache=INFO
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.devMode" value="true"/>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="SSH-e_master" namespace="/" extends="json-default">
<action name="saveAction_*" class="cn.wwx.ssh.action.SaveAction" method="{1}">
<!-- 返回类型为json-->
<result type="json">
<!--tips 参数root的含义-->
<param name="root">result</param>
</result>
</action>
<action name="redrawAction_*" class="cn.wwx.ssh.action.RedrawAction" method="{1}">
<!-- 返回类型为json-->
<result type="json">
<!--tips 参数root的含义-->
<param name="root">result</param>
</result>
</action>
<action name="deleteAction_*" class="cn.wwx.ssh.action.DeleteAction" method="{1}">
<!-- 返回类型为json-->
<result type="json">
<!--tips 参数root的含义-->
<param name="root">result</param>
</result>
</action>
</package>
</struts>
由于未知原因,我引入了json的包,但是照不到json-default这个package,自己把json的struts文件复制了一份
struts-json.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="json-default" extends="struts-default">
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"/>
</result-types>
<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- struts2容器控制器 -->
<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>
<!-- spring容器配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring容器监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 欢迎页面 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
页面就写了一个index.jsp
<%--<%--%>
<%--String path = request.getContextPath();--%>
<%--String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";--%>
<%--%>--%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>高德地图</title>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<style>
input[type="text"] {
height: 25px;
outline: none;
border: 0;
border: 1px solid #CCCCCC;
padding: 0 4px;
}
</style>
<script src="http://webapi.amap.com/maps?v=1.4.3&key=58c13d389e4fe07b767e9e7c4d42f110&plugin=AMap.MouseTool,AMap.PolyEditor"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<div id="container"></div>
<div class="button-group">
<input type="button" class="button" value="鼠标绘制线" id="polyline"/>
<input type="button" class="button" value="鼠标绘制面" id="polygon"/>
<input type="button" class="button" value="保存" id="save"/>
<input type="button" class="button" value="清除" id="clear"/>
<input type="button" class="button" value="再现" id="show"/>
<input type="button" class="button" value="卫星图" id="Satellite"/>
<input type="button" class="button" value="路网图" id="RoadNet"/>
<input type="button" class="button" value="交通图" id="Traffic"/>
<input id="cityName" class="inputtext" placeholder="请输入城市的名称" type="text"/>
<input id="query" class="button" value="到指定的城市" type="button"/>
</div>
<div id="lineinfo">
<table>
<tr><td>长度</td><td><input type="text" id="length"></td></tr>
<tr><td>宽度</td><td><input type="text" id="width"></td></tr>
<br>
<input type="button" class="button" value="提交" id="savelineinfo"/>
</br>
</table>
</div>
</div>
<style>
#lineinfo{
display: none;
position: absolute;
left:50%;
top:50%;
width:250px;
height:100px;
background-color:white;
text-align: center;
}
</style>
<div id="goninfo">
<table>
<tr><td>面积</td><td><input type="text" name="area" id="area"></td></tr>
<tr><td>用地方式</td><td><input type="text" name="groundtype" id="groundtype"></td></tr>
<br>
<input type="button" class="button" value="保存" id="savegoninfo"/>
</br>
</table>
</div>
</div>
<style>
#goninfo{
display: none;
position: absolute;
left:50%;
top:50%;
width:250px;
height:100px;
background-color:white;
text-align: center;
}
</style>
<script>
var isVisaiable = [false,true,false];
var satelliteLayer = new AMap.TileLayer.Satellite();
var roadNetLayer = new AMap.TileLayer.RoadNet();
var trafficLayer = new AMap.TileLayer.Traffic({
'autoRefresh': true, //是否自动刷新,默认为false
'interval': 180 //刷新间隔,默认180s
});
var map = new AMap.Map("container", {
resizeEnable: true,
layers:[
satelliteLayer,
roadNetLayer,
trafficLayer
],
});
//设置城市
AMap.event.addDomListener(document.getElementById('query'), 'click', function() {
var cityName = document.getElementById('cityName').value;
if (!cityName) {
cityName = '北京市';
}
map.setCity(cityName);
});
satelliteLayer.hide();roadNetLayer.show();trafficLayer.hide();
AMap.event.addDomListener(document.getElementById('Satellite'), 'click', function() {
if(isVisaiable[0] == false){
satelliteLayer.show();
isVisaiable[0] = true;
}else if(isVisaiable[0] == true){
satelliteLayer.hide();
isVisaiable[0] = false;
}
}, false);
AMap.event.addDomListener(document.getElementById('RoadNet'), 'click', function() {
if(isVisaiable[1] == false){
roadNetLayer.show();
isVisaiable[1] = true;
}else if(isVisaiable[1] == true){
roadNetLayer.hide();
isVisaiable[1] = false;
}
}, false);
AMap.event.addDomListener(document.getElementById('Traffic'), 'click', function() {
if(isVisaiable[2] == false){
trafficLayer.show();
isVisaiable[2] = true;
}else if(isVisaiable[2] == true){
trafficLayer.hide();
isVisaiable[2] = false;
}
}, false);
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true,//是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:无穷大
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
buttonPosition:'RB'
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息
});
onload(redraw());
AMap.event.addDomListener(document.getElementById('clear'), 'click', function() {
map.clearMap();
});
AMap.event.addDomListener(document.getElementById('show'), 'click', function() {
redraw();
});
//重绘,打开页面即出现数据库有的图形
var TypeAndPaths = [];
var All = [];
var jarr = [];
var geo = [];
var geotype = [];
function redraw() {
$.ajax({
type : 'POST',
url : "redrawAction_redraw",
data:{},
// 对象参数转换json格式字符串
contentType: "application/x-www-form-urlencoded",
dataType:'json',
Async:true,
success:function(data) {
if(data){
//将json字符串转换为json对象,因为要通过点的方法来拿它的属性 eval('('+str+')');
var obj = eval('(' + data + ')');
TypeAndPaths = obj.allpath.split("%");
for(var m in TypeAndPaths){
All = TypeAndPaths[m].split("?");
if("polygon" == TypeAndPaths[m].substring(0,7)){
var jobj = JSON.parse(All[0].substring(8,All[0].length));
jarr.push(jobj);
geotype.push("polygon");
var arr = [];
for(var k in jobj){
arr.push([jobj[k].lng,jobj[k].lat]);
}
geo[m] = new AMap.Polygon({
path: arr, //设置线覆盖物路径
fillColor: '#fff236', // 多边形填充颜色
fillOpacity:0.8,//多边形填充透明度
strokeOpacity:0.5, // 线条透明度
borderWeight: 8, // 线条宽度,默认为 1
strokeColor: '#ff504e', // 线条颜色
lineJoin: 'round'// 折线拐点连接处样式
});
var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
geo[m].content = '面积'+All[3]+"\t"+"用地方式:"+All[4];
geo[m].on('mouseover', function (e) {
infoWindow.setContent(e.target.content);
infoWindow.open(map, e.lnglat);
});
geo[m].extData = JSON.stringify({"deletetype":geotype[m],"deletepath":jarr[m]});
geo[m].on("rightclick",function (e) {
var sTarget = e.target.extData;
var deleteMenu = new AMap.ContextMenu();
//删除菜单项
deleteMenu.addItem("删除", function () {
$.ajax({
type: 'POST',
url: "deleteAction_delete",
data: {"deleteinfo": sTarget},
// 对象参数转换json格式字符串
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
Async: false,
success: function () {
alert("success");
window.location.reload();
},
error: function () {
alert("error");
}
});
}, false);
deleteMenu.open(map, e.lnglat);
});
map.add(geo[m]);
}
else if("polyline" == TypeAndPaths[m].substring(0,8)){
var jobj = JSON.parse(All[0].substring(9,All[0].length));
jarr.push(jobj);
geotype.push("polyline");
var arr = [];
for(var k in jobj){
arr.push([jobj[k].lng,jobj[k].lat]);
}
geo[m] = new AMap.Polyline({
path: arr, //设置线覆盖物路径
borderWeight: 10, // 线条宽度,默认为 1
strokeOpacity:0.5, // 线条透明度
strokeColor: '#ff504e', // 线条颜色
lineJoin: 'round' // 折线拐点连接处样式
});
var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
geo[m].content = '长度:'+All[1]+"\t"+"宽度:"+All[2];
geo[m].on('mouseover', function (e) {
infoWindow.setContent(e.target.content);
infoWindow.open(map, e.lnglat);
});
geo[m].extData = JSON.stringify({"deletetype":geotype[m],"deletepath":jarr[m]});
geo[m].on("rightclick",function (e) {
var sTarget = e.target.extData;
var deleteMenu = new AMap.ContextMenu();
//删除菜单项
deleteMenu.addItem("删除", function () {
$.ajax({
type: 'POST',
url: "deleteAction_delete",
data: {"deleteinfo": sTarget},
// 对象参数转换json格式字符串
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
Async: false,
success: function () {
alert("success");
window.location.reload();
},
error: function () {
alert("error");
}
});
}, false);
deleteMenu.open(map, e.lnglat);
});
map.add(geo[m]);
}
}
}else{
alert("传值为null");
}
},
error:function (){
alert("error");
}
});
}
//在地图中添加MouseTool插件
var mouseTool = new AMap.MouseTool(map);
var LineOrGon = null;//标记绘制图形type
AMap.event.addDomListener(document.getElementById('polyline'), 'click', function() {
mouseTool.polyline({
strokeColor:"#f053ff", // 线条颜色,十六进制
strokeOpacity:0.5, // 线条透明度
strokeWeight:10, // 线条宽度
lineJoin: 'round', // 折线拐点连接处样式
draggable:true
});
LineOrGon = "polyline";
}, false);
AMap.event.addDomListener(document.getElementById('polygon'), 'click', function() {
mouseTool.polygon({
fillColor: '#17ff27', // 多边形填充颜色
fillOpacity:0.8,//多边形填充透明度
strokeOpacity:0.5, // 线条透明度
borderWeight: 8, // 线条宽度,默认为 1
strokeColor: '#ffb822', // 线条颜色
lineJoin: 'round'// 折线拐点连接处样式
});
LineOrGon = "polylgon";
}, false);
var lspath = [];//画的线的点坐标集
var dpolyline = [];//线的集合
var lcount = 0;//线的个数
var gspath = [];//画的面的点坐标集
var dpolylgon = [];//面的集合
var gcount = 0;//面的个数
var lineinfo = [];//线的属性
var goninfo = [];//面的属性
AMap.event.addListener(mouseTool, 'draw', function draw(e) { //添加事件
if("polyline" == LineOrGon){
console.log("ggggg==" + e.obj.getPath());//获取经纬度值
var lpath = e.obj.getPath();
for (var i in lpath){
lspath.push({"lng":lpath[i].getLng(),"lat":lpath[i].getLat()});
}
var polyline = new AMap.Polyline({
path: lpath, //设置线覆盖物路径
strokeColor:"#ff504e", // 线条颜色,十六进制
strokeOpacity:0.5, // 线条透明度
strokeWeight:10, // 线条宽度
draggable:true,
lineJoin: 'round' // 折线拐点连接处样式
});
map.add(polyline);
console.log(lspath);
document.getElementById("lineinfo").style.display="block";
dpolyline[lcount] = JSON.stringify(lspath);//每条线的JSON类型数据
lcount++;
lspath = [];
}else if("polylgon" == LineOrGon){
console.log("ggggg==" + e.obj.getPath());//获取经纬度值
var gpath = e.obj.getPath();
for (var j in gpath){
gspath.push({"lng":gpath[j].getLng(),"lat":gpath[j].getLat()});
}
var polygon = new AMap.Polygon({
path: gpath, //设置线覆盖物路径
fillColor:'#17ff27', // 多边形填充颜色
fillOpacity:0.8,//多边形填充透明度
strokeOpacity:0.5, // 线条透明度
borderWeight: 8, // 线条宽度,默认为 1
strokeColor: '#ffb822' // 线条颜色
});
map.add(polygon);
console.log(gspath);
document.getElementById("goninfo").style.display="block";
var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
polygon.content = '面积:'+$("#area").val()+"\t"+"用地方式:"+$("#groundtype").val();
polygon.on('mouseover', function (e) {
infoWindow.setContent(e.target.content);
infoWindow.open(map, e.lnglat);
});
dpolylgon[gcount] = JSON.stringify(gspath);//每条线的JSON类型数据
gcount++;
gspath = [];
}
});
//保存线信息
AMap.event.addDomListener(document.getElementById('savelineinfo'), 'click', function() {
lineinfo.push({"length":$("#length").val(),"width":$("#width").val()});
$("#length").val(null);$("#width").val(null);
document.getElementById("lineinfo").style.display="none";
}, false);
//保存多边形信息
AMap.event.addDomListener(document.getElementById('savegoninfo'), 'click', function() {
goninfo.push({"area":$("#area").val(),"groundtype":$("#groundtype").val()});
$("#area").val(null);$("#groundtype").val(null);
document.getElementById("goninfo").style.display="none";
}, false);
//保存
var wholedpolyline = null;//所有线构成的String
var wholedpolylgon = null;//所有面构成的String
var wholelineinfo = null;//所有线的信息构成的String
var wholegoninfo = null;//所有面的信息构成的String
AMap.event.addDomListener(document.getElementById('save'), 'click', function() {
for(var k in dpolyline){
wholedpolyline += "%" + dpolyline[k];
wholelineinfo += "%" + JSON.stringify(lineinfo[k]);
}
for(var m in dpolylgon){
wholedpolylgon += "%" + dpolylgon[m];
wholegoninfo += "%" + JSON.stringify(goninfo[m]);
}
$.ajax({
type : 'POST',
url : "saveAction_save",
data:{"lpath":wholedpolyline,
"gpath":wholedpolylgon,
"lineinfo":wholelineinfo,
"goninfo":wholegoninfo
},
// 对象参数转换json格式字符串
contentType: "application/x-www-form-urlencoded",
dataType:'json',
Async:true,
success:function() {
alert("success");
window.location.reload();
},
error:function (){
alert("error");
}
});
}, false);
</script>
</body>
</html>
我用的maven管理,pom.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>learing</groupId>
<artifactId>SSH_002</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.1.1.RELEASE</spring.version>
<hibernate.version>3.6.5.Final</hibernate.version>
<struts2.version>2.1.8.1</struts2.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.1_3</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<!--config-browser-plugin插件,使用了这个插件之后,就可以很方便的浏览项目中的所有action及其与 jsp view的映射 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>${struts2.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.struts</groupId>-->
<!--<artifactId>struts2-json-plugin</artifactId>-->
<!--<version>${struts2.version}</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<!-- 添加对数据库的支持 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<!-- 添加对数据源的支持 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<webResources>
<resource>
<directory>src\main\webapp</directory>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
<finalName>com</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.hbm.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
</project>
上传的项目正在审核,通过后会在本页面贴出链接供大家参考