今天花了点时间搭建了一个Spring+SpringMVC+mybatis的框架完成了,省市区级联查询;下面介绍我的具体步骤
注意:我的shengid,shengname,字段起的不规范(读者注意下);
首先是搭建SSM框架:先看下整个项目的结构:
首先是配置springmvc-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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">
<!-- 配置handleMapping
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
-->
<!-- 配置HandlerAdapter
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
-->
<!-- springmvc上传图片 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
<!-- 用于将对象转为JSON -->
<bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter"/>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
<!-- 对模型视图添加前后缀
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
-->
<!-- 注解 -->
<context:component-scan base-package="com.controller"/>
</beans>
再来配置applicationContext.xml文件(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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd"
default-lazy-init="false" default-autowire="byName">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/ssq"></property>
<property name="username" value="root"></property>
<property name="password" value="DCX5201314"></property>
</bean>
<bean id="sqlsessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
</bean>
<!-- 配置事务3个步骤 1、配置事务管理器 2、配置拦截规则,需要选择事物管理器 3、配置拦截范围,需要选择拦截规则
-->
<!-- 1、事务管理器
-->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2、配置拦截规则 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="select*" read-only="true" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* service.*.*(..))"
id="serviceMethod" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
<!-- 注解扫描com包下的全部类文件 -->
<context:annotation-config />
<context:component-scan base-package="com"/>
<!-- 因为我采用的是注解的方式所以就不用配置ioc了 -->
<!-- ioc
<bean id="shengDao" class="com.dao.imp.shengDaoImp">
<property name="sqlSessionFactory" ref="sqlsessionFactory"></property>
</bean>
<bean id="shengService" class="com.service.imp.shengServiceImp">
<property name="shengDao" ref="shengDao"></property>
</bean>
<bean id="stuaction" class="action.studetnaction">
<property name="shengService" ref="shengService"></property>
</bean> -->
</beans>
再配置mybatis.cfg.xml文件:
<?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">
<configuration>
<mappers>
<mapper resource="com/entity/shengMapper.xml"/>
</mappers>
</configuration>
再来看下配置这个框架需要导入的包:可以通过我的网址http://download.csdn.net/download/qq_34178998/10025027下载(或者私聊我发),把这些文件放在WEB-INF/lib文件夹下,
再新建com包再里面建立各个层文件:
首先是controller层:
shengController.java文件内容:
package com.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.service.shengService;
import com.utils.to_json;
@Controller
@RequestMapping("sheng")
public class shengController {
@Autowired
private shengService shengService;
public shengService getShengService() {
return shengService;
}
public void setShengService(shengService shengService) {
this.shengService = shengService;
}
/******************************查看**********************************************/
@RequestMapping("/selectAll")
@ResponseBody
public void selectAll(HttpServletRequest request,HttpServletResponse response,int typeid){
System.out.println("123");
List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
try {
list=shengService.selectAll(typeid);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("回来了"+list);
to_json.writeJson(list, request, response);
}
}
接下来是service层:
先是shengService.java接口层:
package com.service;
import java.util.List;
import java.util.Map;
public interface shengService {
//查询
public List<Map<String, Object>> selectAll(int typeid);
}
接着是shengServiceImp.java实现层:
package com.service.imp;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.shengDao;
import com.service.shengService;
@Service("shengService")
public class shengServiceImp implements shengService{
@Autowired
private shengDao shengDao;
public shengDao getShengDao() {
return shengDao;
}
public void setShengDao(shengDao shengDao) {
this.shengDao = shengDao;
}
/*******************查询所有**************************************************/
public List<Map<String, Object>> selectAll(int typeid) {
List<Map<String, Object>> list=shengDao.selectAll(typeid);
return list;
}
}
最后是dao层
先是shengDao.java接口层:
package com.dao;
import java.util.List;
import java.util.Map;
public interface shengDao {
//查询
public List<Map<String, Object>> selectAll(int typeid);
}
接着是shengDaoImp.java实现层:
package com.dao.imp;
import java.util.List;
import java.util.Map;
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.dao.shengDao;
@Repository("dao")
public class shengDaoImp implements shengDao{
@Autowired
private SqlSessionFactory sqlSessionFactory;//因为采用mybatis所以SqlSessionFactory
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
/*****************查询所有******************************************************/
public List<Map<String, Object>> selectAll(int typeid) {
//查询
System.out.println("laidao ");
SqlSession session=getSqlSession();
List<Map<String, Object>> list=session.selectList("selectall",typeid);
return list;
}
}
然后就要建立实体了:
先是实体里面的字段,要与数据库里面的符合:
sheng.java文件:
package com.entity;
public class sheng {
private int shengid;
private String shengname;
private int typeid;
public int getTypeid() {
return typeid;
}
public void setTypeid(int typeid) {
this.typeid = typeid;
}
public int getShengid() {
return shengid;
}
public void setShengid(int shengid) {
this.shengid = shengid;
}
public String getShengname() {
return shengname;
}
public void setShengname(String shengname) {
this.shengname = shengname;
}
}
接下累就是实体的配置文件了shengMapper.xml:
<?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">
<!-- namespace必须写 -->
<mapper namespace="com.entity.sheng">
<select id="selectall" resultType="com.entity.sheng" parameterType="int">
<!-- 说明查询所有返回值是实体所以resultType里面是实体,parameterType是从页面传过去的值因为只传了int类型,所以就传个int型 -->
select shengid,shengname from sheng where typeid=#{shengid}
</select>
</mapper>
最后就要来写个工具包了:
to_json.java文件:
package com.utils;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
public class to_json{
/**
* 方法功能:将对象转换成JSON字符串,并响应回前台
* 参数:object
* 返回值:void
* 异常:IOException
*/
public static void writeJson(Object object,HttpServletRequest request,HttpServletResponse response) {
PrintWriter out = null;
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
response.setContentType("text/html;charset=utf-8");
out = response.getWriter();
//System.out.println(json);
out.write(json);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
再来配置web.xml的文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>
org.jfree.chart.servlet.DisplayChart <!--这个固定不变-->
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/DisplayChart</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定位置加载pringmvc配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 乱码过滤器 begin -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 乱码过滤器 end -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
show.jsp页面代码(注意要js文件):
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function show_1(){
alert("nihao ");
$.ajax({
url:'sheng/selectAll.action',
type:'post',
data:{'typeid':0},
dataType:'json',
success:function(data){
var t="<option value=''>--请选择省份--</option>";
for(var i=0;i<data.length;i++){
t+="<option value="+data[i].shengid+">"+data[i].shengname+"</option>"
}
$("#p").html(t);
}
})
}
function show_2(){
var shengid=$("#p").val();
$.ajax({
url:'sheng/selectAll.action',
type:'post',
data:{'typeid':shengid},
dataType:'json',
success:function(data){
var t="<option value=''>----请选择城市</option>";
for(var i=0;i<data.length;i++){
t+="<option value="+data[i].shengid+">"+data[i].shengname+"</option>"
}
$("#c").html(t);
}
})
}
function show_3(){
var shiid=$("#c").val();
$.ajax({
url:'sheng/selectAll.action',
type:'post',
data:{"typeid":shiid},
dataType:'json',
success:function(data){
var t="<option value=''>----请选择区</option>";
for(var i=0;i<data.length;i++){
t+="<option value="+data[i].shengid+">"+data[i].shengname+"</option>"
}
$("#a").html(t);
}
})
}
</script>
</head>
<body οnlοad="show_1()">
省份<select id="p" οnchange="show_2()"></select>
省会<select id="c" οnchange="show_3()"></select>
区<select id="a" ></select>
</body>
</html>
好了,最后的一部份也完成了。
再把数据库,建下数据库名叫做ssq,
最后效果:
这边是打包好的文件:http://download.csdn.net/download/qq_34178998/10025597
好了,今天就到这,欢迎大家留言一起讨论