SpringMVC4+spring3+Myibats3

简单整合了ssm一下


1.添加jar包    (项目下载地址:http://download.csdn.net/detail/fyhjuyol/8672947)

2.配置 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">
  <display-name>springMVCMyibats</display-name>	
  
  <!-- 加载Srping配置文件 -->
	<!--
		[ <context-param></context-param ] =>用来设定web站台的环境参数 * [
		<param-name></param-name> ] (子元素)=> 用来指定参数的名称 * [
		<param-value></param-value> ] (子元素)=> 用来设定参数值 
		从类路径下加载spring的配置文件, 多个配置文件可以用逗号和空格区分 * 
		classpath: 关键字特指类路径下加载  /web-inf/classes/
	-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-*.xml</param-value>
	</context-param>
	
    <context-param>
		<param-name>extremecomponentsPreferencesLocation</param-name>
		<param-value>/extremetable.properties</param-value>
	</context-param>
	<context-param>
		<param-name>extremecomponentsMessagesLocation</param-name>
		<param-value>/extremetableResourceBundle</param-value>
	</context-param>
	<filter>             
    <filter-name>eXtremeExport</filter-name>           
    <filter-class>org.extremecomponents.table.filter.ExportFilter</filter-class>           
</filter>            
<filter-mapping>             
    <filter-name>eXtremeExport</filter-name>           
    <url-pattern>/*</url-pattern>          
</filter-mapping>  

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
		    <!--不能省略 -->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-servlet.xml</param-value>
		</init-param>
		<!--启动时 加载一次 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!--tomcat 的为default weblogic的为FileServlet 
	<servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.css</url-pattern>
</servlet-mapping>
-->	
	<!-- 请求后缀设为.action  或.do-->
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 设置编码格式为UTF8 -->
	<filter>
		<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


3.配置spring  spring-config.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	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/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">

<!-- 1. 数据源 : DriverManagerDataSource -->  
    <bean id="dataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
<!--   <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
       <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> --> 
       <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
       <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
        <property name="username" value="db_fx" />  
        <property name="password" value="123456" />  
    </bean>  
  
    <!--  
        2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源  
  
        MyBatis定义数据源,同意加载配置  
    -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  
       <!--  <property name="configLocation" value="classpath:config/mybatis-config.xml" />    -->
         <property name="configLocation" value="classpath:mybatis-config.xml" />  
    </bean>  
  
    <!--  
        3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory  
  
        basePackage:指定sql映射文件/接口所在的包(自动扫描)  
    -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.bea.mapper"></property>  
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- 
        4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 
    -->  
    <bean id="txManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"></property>  
    </bean>  
  
    <!-- 5. 使用声明式事务  
         transaction-manager:引用上面定义的事务管理器  
     -->  
    <tx:annotation-driven transaction-manager="txManager" />  


</beans>

4.配置springMVC spring-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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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
       http://www.springframework.org/schema/mvc
	   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 注册aop功能 -->
	<aop:aspectj-autoproxy/>
	
	<!-- 开启注解 3.06可以不加, 但4.0必须加上-->
	<mvc:annotation-driven />
    
	<!-- 自动扫面com.springmvc目录及其子目录下面所有类文件,自动注入所有带注解的类 -->
	<context:component-scan base-package="com.bea.*" />
	

	<!-- 处理请求response返回值,如下配置能正确返回字符串型返回值,如返回值为对象,则自动转为json -->
	<bean id="handleAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">  
		  <list>  
		   <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->  
		   <ref bean="mappingStringHttpMessageConverter" />
		  </list>  
		</property>
	</bean>
	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 
	<bean id="mappingStringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" />

	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		  <property name="prefix" value="/" />
		  <property name="suffix" value=".jsp"></property>
		  <property name="order" value="1"></property>
	</bean>

	<!-- spring文件上传编码 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
		p:defaultEncoding="utf-8" />
		
	<!--
		配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能	
	<mvc:resources mapping="/img/**" location="/img/" />
	<mvc:resources mapping="/js/**" location="/js/" />
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="/html/**" location="/html/" />	
    -->
    <!--配置静态资源  与mvc:resources功能相同  -->
   <mvc:default-servlet-handler/>
</beans>

5.配置myibats  myibats-config.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>  
  
    <!-- 实体类,简称 -设置别名 -->  
    <typeAliases>  
        <typeAlias alias="Employe" type="com.bea.model.Employe" />  
    </typeAliases>  
    <!-- 实体接口映射资源 -->  
    <!-- 
        说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml 
    -->  
    <mappers>  
        <mapper resource="com/bea/mapper/empMapper.xml" />  
    </mappers>  
  
</configuration>    


com.bea.mapper 下:empMapper.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:必须与对应的接口全类名一致  
    id:必须与对应接口的某个对应的方法名一致      
 -->  
<mapper namespace="com.bea.mapper.EmpMapper">  
      
    <insert id="save" parameterType="Employe" >  
        insert into employ
   (id,
    name,
    sex,
    birthday,
    photo,
    age,
    education,
    address,
    remark,
    email,
    pwd)
 values
   (emp.nextval,
    #{name},
    #{sex},
    to_date(#{birthday}, 'yyyy-mm-dd'),
    #{photo,jdbcType=VARCHAR},        <!-- 防止photo为null 报无效的列类型 Exception-->
    #{age},
    #{education},
    #{address},
    #{remark},
    #{email},
    #{pwd})
    </insert>  
      
    <update id="update" parameterType="Employe">  
    update employ set
    name =#{name},
    sex =#{sex},
    birthday = to_date(#{birthday}, 'yyyy-mm-dd'),
    age =#{age},
    education =#{education},
    address =#{address},
    remark =#{remark},
    email =#{email},
    pwd =#{pwd}
where id=#{id}    
    </update>  
      
    <delete id="delete" parameterType="int" >  
        delete from employ where id=#{id}  
    </delete>  
      
     <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路劲    字段不一致 可以通过map映射 或查询别名-->    
    <select id="findById" parameterType="int" resultType="Employe">  
         select id,
         name,
         age,
         sex,
         education,
         pwd,
         remark,
         photo,
         to_char(birthday, 'yyyy-mm-dd') birthday
    from employ
   where id = #{id}
  
    </select>  
      
    <select id="findAll" resultType="Employe" >  
        select id,
        name,
        age,
        decode(sex,1,'男',2,'女','男') sex,
        education,
        to_char(birthday, 'yyyy-mm-dd') birthday
   from employ
    </select>  
      
</mapper>  
接口:empMapper.java

public interface EmpMapper {
	boolean save(Employe employe);    //myibats自动添加返回值
    boolean update(Employe employe);  
    boolean delete(int id);  
    Employe findById(int id);  
    List<Employe> findAll();  
}

6.编写controller类  empAction.java:

package com.bea.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.bea.model.Employe;
import com.bea.service.EmpService;


//调试时 修改注解需要重启服务
@Controller
@RequestMapping("/emp")     //@RequestMapping(value="/emp")
public class EmpAction {  //参数不共享
	@Autowired
	private EmpService empService;
    @RequestMapping("/toList")
	public String  toList(Model model){
    	List<Employe> list = empService.findAll();
    	model.addAttribute("list", list);
		return"jsp/em/tolist";
	}
    
    //url rest风格   ../emp/123
	@RequestMapping("/{id}")	
	public String  toDetail(@PathVariable int id,Model model){
	    Employe	employ = empService.findById(id);
	    model.addAttribute("employ",employ); 
		return"jsp/em/todetail";	
	}
	@RequestMapping("/toAdd")
	public String toAdd(){
		return"jsp/em/addemp";
	}
	@RequestMapping("/NoaddEmp")
	public String NOaddEmp(@RequestParam("file") CommonsMultipartFile file, Employe employe,HttpServletRequest request) {	  //不是File file
		Long begin = System.currentTimeMillis();
		String fileUrl = request.getRealPath("/img/photo/")+File.separator+file.getOriginalFilename();   //file.getName()  获取的是file表单 name值 TT..
		FileOutputStream os=null;                                             //getRealPath("/img/photo/")   .../img/photo  对你没看错 不是.../img/photo/
		InputStream is =null;
		try {
			os = new FileOutputStream(fileUrl);
		  //is = new FileInputStream(file);
			is = file.getInputStream();
				
			/*
			 * byte[] buffer =new byte[1024];
			   int len=0;
			   while((len=is.read(buffer))!=-1){    //读取文件 方法1
			   os.write(buffer,0,len);
			}
			 */					       
			   int len=0;
			   while((len=is.read())!=-1){    //读取文件2
			   os.write(len);
			}		 
			    os.flush();
			    is.close();
			    os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Long end = System.currentTimeMillis();
		System.out.println("耗时"+(end-begin)+"ms");
	    employe.setPhoto("/img/photo/"+file.getOriginalFilename());
	    boolean bl = empService.save(employe);
		return"redirect:/emp/toList";
	}
	
	
	@RequestMapping("/addEmp")
	public String addEmp(Employe employe,HttpServletRequest request) {
		String photo ="";
		Long begin = System.currentTimeMillis();
		CommonsMultipartResolver  cmr = new CommonsMultipartResolver(request.getSession().getServletContext());
	try {
		if(cmr.isMultipart(request)){  //判断请求中是否有文件上传
			MultipartHttpServletRequest msr =  (MultipartHttpServletRequest)request;
			Iterator<String> it = msr.getFileNames();
			while(it.hasNext()){
				MultipartFile  file =  msr.getFile(it.next());
				if(file!=null){
					String fileUrl = request.getRealPath("/img/photo/")+File.separator+file.getOriginalFilename(); 	
					File localFile = new File(fileUrl);				
						file.transferTo(localFile);
						photo= "/img/photo/"+file.getOriginalFilename();
				}
			}
		}    
		} catch (IllegalStateException e) {					
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		Long end = System.currentTimeMillis();
		System.out.println("耗时"+(end-begin)+"ms");
	    employe.setPhoto(photo);
	    boolean bl = empService.save(employe);
		return"redirect:/emp/toList";
	}
	
	@RequestMapping("/update/{id}")
	public String toUpdate(@PathVariable int id, Model model){
		Employe	employ = empService.findById(id);
	    model.addAttribute("employ",employ); 
		return"jsp/em/updatemp";
	}
	@RequestMapping("/updateEmp")
	public String updateEmp(Employe employe){
	 boolean bl = empService.update(employe);
		return"redirect:/emp/toList";         //重定向 to servlet
	}
	
	/*
	 *一般方法
	 *  @RequestMapping("/deleteEmp")
	  public String deleteEmp(int id){
		empService.delete(id);
		return"redirect:/emp/toList";
	  }
	
  */
	
	
	/*
	 *  
	   @ResponseBody  相当于 response.getWriter().println(...);如果返回值某个实体对象,则会自动转成json返回
	      必须在配置文件中配置json 转换器
	
	@RequestMapping("/deleteEmp")
	public @ResponseBody Object deleteEmp(int id){
		boolean flag= empService.delete(id);
		return flag;
	}
    */
	
	@RequestMapping("/delete/{id}")
	public void deleteEmp(@PathVariable int id, HttpServletRequest request,HttpServletResponse response){
		String result="";
		PrintWriter out =null;		
		boolean flag= empService.delete(id);
		if(flag){
			result="{\"flag\":\"true\"}";
		}else{
			result="{\"flag\":\"false\"}";
		}
		try {
		response.setContentType("application/json");
		 out =	response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.print(result);
			out.flush();
			out.close();
		}
	}
	
	
	
}


tolist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/extremecomponents.tld" prefix="ec"%>
<%
String path = request.getContextPath()+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript" src="<%=path%>js/jquery-1.7.1.js"></script>
    <link rel="stylesheet" type="text/css" href="<%=path%>js/ectable/css/td_style_ec.css" />
	<script language="JavaScript" src="<%=path%>js/ectable/js/eccn.js"></script>
    <title>用户列表</title>
    
<script type="text/javascript">

	function del(id){
<%--	
      $.ajax(
	 {    
	       type: "post",
	       url : "<%=path%>emp/deleteEmp",
	       data:
	             {
	                 id:id
	             },
	      async: false,
	   dataType: "json",
	    success: function(msg){
	        if(msg.flag="true"){
	          $("#"+id).remove();
	          alert("删除成功!");
	        }else{
	          alert("删除失败!");
	        }
	    }    
	 
	 });		
--%>
	
	   // dataType 默认为 text
	   //$.post("<%=path%>emp/deleteEmp",{id:id},function(msg,status)
	
	$.post("<%=path%>emp/delete/"+id,function(msg,status){
	          //alert("status>>"+status);
	    if(msg.flag=="true"){
	          //window.location.reload();
	          $("#"+id).remove();
	          alert("删除成功!");
	        }else{
	          alert("删除失败!");
	        }
	}); 
}
</script>
  </head>
  
  <body>
    <h6><a href="<%=path%>emp/toAdd">添加用户</a></h6>
    
    <table border=0 CellPadding=0 cellSpacing=0 width="88%" align=center>
			<tr>
				<td align="center">
					<ec:table items="list" var="emp" action="${pageContext.request.contextPath}/emp/toList" width="100%" rowsDisplayed="10" paginationLocation="bottom"
						showExports="true" filterable="false" sortable="true" showPagination="true" showGotoPage="true" showRowsDisplayed="no">
						<ec:exportXls fileName="dzqd.xls" tooltip="导出EXCEL"></ec:exportXls>
						<ec:row>
							<ec:column property="id" title="编号" width="12%" style="align:cneter" />
							<ec:column property="name" title="姓名" width="8%" style="align:cneter" />
							<ec:column property="age" title="年龄" width="9%" style="align:cneter" />
							<ec:column property="birthday" title="生日" width="25%" style="align:cneter" />
							<ec:column property="sex" title="性别" width="8%" style="align:cneter" />
							<ec:column property="education" title="学历" width="8%" style="align:cneter" />
							<ec:column property="cz" title="操作" width="8%" style="align:cneter" sortable="false">
								<a href="<%=path%>emp/update/${emp.id}">编辑</a>							
							    <a href="javascript:del(${emp.id})">删除</a>
							</ec:column>
						</ec:row>
					</ec:table>
				</td>
			</tr>
		</table>
	<table border="1">
		<tbody>
			<tr>
			    <th>编号</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>生日</th>
				<th>性别</th>
				<th>学历</th>
				<th>操作</th>
			</tr>
		       <c:if test="${!empty list}">
				<c:forEach items="${list}" var="emp">
					<tr id="${emp.id}">
					   <%-- <td><a href="<%=path%>emp/toDetail?id=${emp.id}">${emp.id }</a></td> --%>
					   <td><a href="<%=path%>emp/${emp.id}">${emp.id }</a></td>
						<td>${emp.name}</td>
						<td>${emp.age}</td>
						<td>${emp.birthday}</td>
						<td>${emp.sex}</td>
						<td>${emp.education}</td>
						<td>
							<a href="<%=path%>emp/update/${emp.id}">编辑</a>
							<%--<a href="<%=path%>emp/deleteEmp?id=${emp.id}">删除</a> --%>
							 <a href="javascript:del(${emp.id})">删除</a>
						</td>
					</tr>				
				</c:forEach>
			</c:if>
		</tbody>
	</table>
  </body>
</html>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值