前面讲到easyUI的基本使用,其他的组件会在项目中一一提到,先根据easyUI+springmvc来搭建一个简单的项目,能达到前后台都通的目的。这样流程走起来比较直观,比较容易理解。
先看一看项目的基本目录结构,当然我这并不是唯一,只是个人风格而已,项目的真实搭建还得由有工作经验或者架构师来实现,因为他们的大局观意识比较强,搭建的项目能够适应不断加入的新需求。
由于这个架构比较简单,不想传统的SSH那么复杂,配置文件也显得通俗易懂。
那么先来看一下目录结构:
看起来是不是挺舒服的,搞笑我们是认真的。
神经病啊,我们来看看具体是怎么来搭建的。
1.前端搭建
2.后台搭建
2.1 包的引入
另外一种就是使用maven进行jar的管理,我们只需要将需要的jar在xml文件中进行依赖配置,那么在我们执行
maven update的时候就会去远程下载你需要的jar包。
2.2 maven配置
1.下载并安装maven
2.安装maven
3.eclipse集成maven
<mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | <mirror> <id>mirrorId</id> <mirrorOf>repositoryId</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://my.repository.com/repo/path</url> </mirror> --> <!-- 配置下载镜像 --> <mirror> <id>UK</id> <mirrorOf>central</mirrorOf> <name>UK Central</name> <url>http://uk.maven.org/maven2</url> </mirror> </mirrors>
(3) eclipse配置maven
(4) 引入settings文件
点击user setting,然后选择config文件下的settings.xml,点击Apply,点击OK.
(5) 创建maven项目
上面的准备工作做完了,我们就可以开始创建maven项目了。
点击new,创建一个新的project,在搜索框中输入maven,选中maven project,然后点击next。
进去之后是一个默认的项目路径,这个可以不用管他,当然你也可以自己创建一个项目路径。
点击next,然后选中这条,双击一下
双击之后就可以跳到另一个窗口:
group id和artfact id随便填写,package会自动生成,然后点击finish按钮。就会生成一个maven project。
创建项目之后会发现,jsp中存在错误,我们知道jsp是依赖于httpservlet的,而我们的项目中并没有引入
javax对应的jar包,所以会出现这个错误。
我们可以在pom文件中依赖注入就行了。
项目右键maven---->update maven project,点击OK。如果还是报错,选中
这样jsp错误就会解决了,但是MMP我的pom.xml文件报错了,报了个奇怪的错误。我得好好看看,什么
东西。
吃惊!!!!!
其实看到这个东西 com.thoughtworks.xstream:xstream: 我们就会潜意识的认为,MMP的估计这货是缺少
jar包了,所以呢我们要找到这种jar包需要怎么依赖注入到pom文件中。
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.3.1</version> </dependency>
确实呢,我们加上这段代码,然后在maven-->update maven project,然后错误就没了,如果还报错,就还勾选
那个暴力更新,你别说还真是。现在就成了一个新的没有一点错误的项目了。是不是有点小激动呢?
哎,扯了那么多,感觉跑题了呢?
我们这个项目是不需要maven的,因为没有太多的jar需要引入,正常的一个web project就足以应对easyUI的
组件了,为了简单起见,我们还是使用web project吧。
3. xml文件配置
3.1 web.xml文件配置
DispatcherServlet
ContextLoaderListener
<?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" xmlns:web="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>springMVC</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring/applicationContext.xml</param-value> </context-param> </web-app>
3.2 spring 配置文件
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="com.chenqk.springmvc.controller"></context:component-scan> <!-- 完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/"
p:suffix=".jsp" /> </beans>
3.3 ApplicationContext配置
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="com.chenqk.springmvc.dao.impl"/> <context:component-scan base-package="com.chenqk.springmvc.service.impl"/> <context:component-scan base-package="com.chenqk.springmvc.entity"/> <context:component-scan base-package="com.chenqk.springmvc.controller"/> <context:property-placeholder location="classpath:config/properties/jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName ="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" p:initialSize="${jdbc.initialSize}" p:maxActive="${jdbc.maxActive}" p:maxIdle="${jdbc.maxIdle}" p:minIdle="${jdbc.minIdle}" p:defaultAutoCommit="${jdbc.defaultAutoCommit}" p:poolPreparedStatements="${jdbc.poolPreparedStatements}" p:validationQuery="${jdbc.validationQuery}" p:testOnBorrow="${jdbc.testOnBorrow}" p:testOnReturn="${jdbc.testOnReturn}" p:testWhileIdle="${jdbc.testWhileIdle}" p:timeBetweenEvictionRunsMillis="${jdbc.timeBetweenEvictionRunsMillis}" p:numTestsPerEvictionRun="${jdbc.numTestsPerEvictionRun}" p:minEvictableIdleTimeMillis="${jdbc.minEvictableIdleTimeMillis}" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:com/chenqk/springmvc/mapper/applicationContext-mybatis.xml"/> <bean class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"/> </bean> <!-- 引入资源 --> <import resource="applicationContext-user.xml"/> <import resource="applicationContext-tree.xml"/> </beans>在scan中定义加载之后所需要扫描的包,和实例化数据库对象以及sessionfactory,将sqlsession指向我们的mybatis配置文件,同时加载其他的配置文件。
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="userDao" class="com.chenqk.springmvc.dao.impl.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <bean id="userService" class="com.chenqk.springmvc.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <bean id="userController" class="com.chenqk.springmvc.controller.UserController"> <property name="userService" ref="userService"></property> </bean> </beans>
我们配置了实例对象,并指向了引用,这样在项目启动之后spring加载完事就会为我们创建这些对象,我们就不需要在class定义初始化这些实例。其实这里都是一些简单的应用,实例化一些对象。当然spring的用处绝不止这些,感兴趣的可以去深入研究一下,我们这里主要讲到的始终是easyUI,后端的东西,我会捎带提一下,但是不会深入,因为后台要是讲起来,恐怕很难讲得清楚,又因为笨博主两年没碰后台了,忘得都差不多了,捡起来虽然也快,但是还是要耗时间的。
3.4 mybatis文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 注意:每个标签必须按顺序写,不然蛋疼的DTD会提示错误:
The content of element type "configuration" must match
"(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,
objectWrapperFactory?,plugins?,environments?,mappers?)". -->
<configuration>
<!-- 属性配置 -->
<properties resource="config/properties/jdbc.properties">
<!-- 相同属性:最高优先级的属性是那些作为方法参数的,然后是资源/url 属性,
最后是 properties元素中指定的属性 -->
<property name="username" value="root"/>
<property name="password" value="123qwe"/>
</properties>
<!-- 设置缓存和延迟加载等等重要的运行时的行为方式 -->
<settings>
<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<!-- 别名 -->
<typeAliases>
<typeAlias alias="userMap" type="com.chenqk.springmvc.entity.UserMessage"/>
<typeAlias alias="treeMap" type="com.chenqk.springmvc.entity.Tree"/>
</typeAliases>
<environments default="development">
<!-- environment 元素体中包含对事务管理和连接池的环境配置 -->
<environment id="development">
<transactionManager type="JDBC" />
<!-- type分三种:
UNPOOLED是每次被请求时简单打开和关闭连接
UNPOOLED的数据源仅仅用来配置以下 4 种属性driver,url,username,password
POOLED :JDBC连接对象的数据源连接池的实现,不直接支持第三方数据库连接池
-->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- ORM映射文件 -->
<mappers>
<mapper resource="com/chenqk/springmvc/mapper/user-mapper.xml"/>
<mapper resource="com/chenqk/springmvc/mapper/tree-mapper.xml"/>
</mappers>
</configuration>
3.5 mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.chenqk.springmvc.entity.UserMessage"> <resultMap type="com.chenqk.springmvc.entity.UserMessage" id="userMap"> <id property="userId" column="userId"/> <result property="userName" column="userName"/> <result property="password" column="password"/> </resultMap> <select id="selectUserByNameAndPwd" resultType="userMap" parameterType="userMap"> select * from user_info where userName=#{userName} and password=#{password}; </select> <select id="selectAllUser" resultType="userMap" parameterType="userMap"> select * from user_info; </select> </mapper>
简单吧,看起来搜酷,namespace以及后面的resultmap,在mybatis配置文件中都有声明。
3.6 jdbc配置
jdbc.initialSize=5 jdbc.maxActive=15 jdbc.maxIdle=10 jdbc.minIdle=5 jdbc.defaultAutoCommit=false jdbc.poolPreparedStatements=true jdbc.validationQuery=SELECT 1 jdbc.testOnBorrow=false jdbc.testOnReturn=false jdbc.testWhileIdle=false jdbc.timeBetweenEvictionRunsMillis=6000 jdbc.numTestsPerEvictionRun=15 jdbc.minEvictableIdleTimeMillis=-1 jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/springmvc-easyui?characterEncoding=utf8 jdbc.username=root jdbc.password=123qwe
4.代码code
4.1 实体类
package com.chenqk.springmvc.entity; /** * 测试:用户对象 * @author chenqk * 2014年4月22日10:48:29 */ public class UserMessage { private int userId; private String userName; private String password; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
4.2 DAO数据层
package com.chenqk.springmvc.dao; import java.util.List; import com.chenqk.springmvc.entity.UserMessage; /** * 测试框架:dao层 * @author Administrator * */ public interface UserDao { public UserMessage selectUserByNameAndPwd(UserMessage user); public List<UserMessage> selectAllUser(); }
4.3 DAO实现类
package com.chenqk.springmvc.dao.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.chenqk.springmvc.dao.UserDao; import com.chenqk.springmvc.entity.UserMessage; @Repository("UserDao") public class UserDaoImpl implements UserDao{ @Autowired private SqlSessionFactory sqlSessionFactory; public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public UserMessage selectUserByNameAndPwd(UserMessage user) { SqlSession sqlSession =(SqlSession) this.getSqlSessionFactory().openSession(); System.out.println(user.getPassword()+"-------"+user.getUserName()); return sqlSession.selectOne("com.chenqk.springmvc.entity.UserMessage.selectUserByNameAndPwd", user); } public List<UserMessage> selectAllUser() { SqlSession sqlSession =(SqlSession) this.getSqlSessionFactory().openSession(); return sqlSession.selectList("com.chenqk.springmvc.entity.UserMessage.selectAllUser"); } }
这里就开始使用注解的形式了,当然这里也不会讲解这些注解怎么用的,感兴趣的可以去看看springmvc注解。
4.4 Service业务逻辑层及其实现类
package com.chenqk.springmvc.service; import java.util.List; import com.chenqk.springmvc.entity.UserMessage; public interface UserService { public UserMessage selectUserByNameAndPwd(UserMessage user); public List<UserMessage> selectAllUser(); }
package com.chenqk.springmvc.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.chenqk.springmvc.dao.UserDao; import com.chenqk.springmvc.entity.UserMessage; import com.chenqk.springmvc.service.UserService; @Service("UserService") public class UserServiceImpl implements UserService{ @Autowired @Qualifier("UserDao") private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public UserMessage selectUserByNameAndPwd(UserMessage user) { return userDao.selectUserByNameAndPwd(user); } public List<UserMessage> selectAllUser() { return userDao.selectAllUser(); } }
4.5 controller控制层
package com.chenqk.springmvc.controller; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.chenqk.springmvc.entity.UserMessage; import com.chenqk.springmvc.service.UserService; import com.chenqk.springmvc.util.DBUtil; import com.chenqk.springmvc.util.LocationVo; import com.chenqk.springmvc.util.StationEntity; @Controller @RequestMapping("/") public class UserController{ @Autowired @Qualifier("UserService") private UserService userService; private UserMessage user; private List<UserMessage>userList; private String staMac; public String getStaMac() { return staMac; } public void setStaMac(String staMac) { this.staMac = staMac; } public List<UserMessage> getUserList() { return userList; } public void setUserList(List<UserMessage> userList) { this.userList = userList; } public UserMessage getUser() { return user; } public void setUser(UserMessage user) { this.user = user; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping("/login") public ModelAndView login(UserMessage user){ UserMessage userinfo =new UserMessage(); //userinfo.setUserName(request.getParameter("userName")); //userinfo.setPassword(request.getParameter("password")); //user =userService.selectUserByNameAndPwd(userinfo); userList = userService.selectAllUser(); String username ="1111"; if(user!=null){ return new ModelAndView("loginSuccess","userList",userList); }else { return new ModelAndView("loginError","userList",userList); } } @RequestMapping("/showListener") @ResponseBody public void showListener(@RequestParam("staMac") String staMac, PrintWriter printWriter){ System.out.println("启动监听--------------------"+staMac); //Map<String,Map<String, Integer>> mapInfo = new HashMap<String,Map<String, Integer>>() ; // 创建集合存放ap List<List<String>> apList = new ArrayList<List<String>>(); // 数据值 List<List<Double>> rssiList = new ArrayList<List<Double>>(); // 获取时间轴坐标 List<String> collTimeList = DBUtil.searchAllApByColltime(); // 实体类封装集合 StationEntity stationEntity = new StationEntity(); for (int i = 0; i < 3; i++) { int num = 0; // 创建集合存放ap List<String> apList1 = new ArrayList<String>(); List<Double> rssiList1 = new ArrayList<Double>(); String collTime = collTimeList.get(i); List<LocationVo> locationVo = DBUtil.getAllStaMacByTime(collTime); for (int j = 0; j <5; j++) { if(num<5){ num++; apList1.add(locationVo.get(j).getApMac()); rssiList1.add(locationVo.get(j).getRSSI()); }else break; } apList.add(apList1); rssiList.add(rssiList1); } stationEntity.setApList(apList); stationEntity.setCollTimeList(collTimeList); stationEntity.setRssiList(rssiList); // int numFlag = 0; // List<LocationVo> locationVo = DBUtil.getAllStaMac(); // String collTime = locationVo.get(0).getCollTime(); // List<LocationVo> locationVo1 = DBUtil.getAllStaMacByTime(collTime); // String apMac = ""; // List<Station> stationList = new ArrayList<Station>(); // double rssi = 0; // //Map<String,Integer> vo = new HashMap<String,Integer>(); // for (int i = 0; i < locationVo1.size(); i++) { // numFlag++; // if(numFlag<6){ // //vo.put(locationVo1.get(i).getApMac(), locationVo1.get(i).getRSSI()); // apMac = locationVo1.get(i).getApMac(); // rssi = locationVo1.get(i).getRSSI(); // Station station = new Station(); // station.setApMac(apMac); // station.setRssi(rssi); // stationList.add(station); // } // } // StationEntity entity = new StationEntity(); // entity.setColltime(collTime); // entity.setStationList(stationList); JSONObject jSONObject = JSONObject.fromObject(stationEntity); System.out.println(jSONObject.toString()); printWriter.print(jSONObject); //return jSONObject ; } }
这些代码没啥好说的,有一点在使用自动注入的时候,需要给getter,setter方法,比如在controller中会自动注入