Java进阶学习第三十二天(SpringMVC)

版权声明:使用本品须Jack Gao同意,违者必究 https://blog.csdn.net/Mr_GaoYang/article/details/85048156

一、回顾struts2+Spring开发

1、需求:学生注册【add.jsp > StudentAction.java > addOK.jsp】
① Emp.java

public class Emp {
	private String id;//编号
	private String username;//姓名
	private Double salary;//薪水
	public Emp(){}
	public Emp(String username, Double salary) {
		this.username = username;
		this.salary = salary;
	}
	public String getId() {
		return UUID.randomUUID().toString();
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
}

② JdbcUtil.java

public class JdbcUtil {
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}
}

③ c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
		<property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
		<property name="user">scott</property>
		<property name="password">tiger</property>
		<property name="acquireIncrement">2</property>
		<property name="initialPoolSize">5</property>
		<property name="minPoolSize">1</property>
		<property name="maxPoolSize">5</property>
	</default-config>
</c3p0-config>

④ EmpDao.java

public class EmpDao {
	/**
	 * 增加员工
	 */
	public void add(Emp emp) throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
		String sql = "INSERT INTO EMPS(ID,USERNAME,SALARY) VALUES(?,?,?)";
		Object[] params = {emp.getId(),emp.getUsername(),emp.getSalary()};
		runner.update(sql,params);
	}

	/**
	 * 测试 
	 */
	public static void main(String[] args) throws Exception{
		EmpDao dao = new EmpDao();
		dao.add(new Emp("测试",5000D));
	}
}

⑤ EmpService.java

public class EmpService {
	private EmpDao empDao;
	public void setEmpDao(EmpDao empDao) {//springioc自动注入
		this.empDao = empDao;
	}
	/**
	 * 增加员工
	 */
	public void addEmp(Emp emp) throws Exception{
		if(emp == null){
			throw new RuntimeException("EmpService参数不能为空");
		}
		empDao.add(emp);
	}
}

⑥ EmpAction.java

public class EmpAction extends ActionSupport{
	private EmpService empService;//业务层
	public void setEmpService(EmpService empService) {//springioc自动注入实现类
		this.empService = empService;
	}
	private Emp emp;//模型
	public Emp getEmp() {
		return emp;
	}
	public void setEmp(Emp emp) {
		this.emp = emp;
	}
	/**
	 * 注册员工
	 */
	public String registerMethod() throws Exception{
		empService.addEmp(emp);
		return "success";
	}
}

2、struts2框架的特点
① 每次请求action时,都会创建action实例
② action类一成不变的直接或间接继续ActionSupport类
③ action类中的业务控制方法总是相类似的签名且无参
④ action类中,接收参数要用实例变量和对应的set方法或set/get方法
⑤ struts.xml配置文件,必须以struts.xml命名,且放在src目录下
… … …

二、SpringMVC基础

1、JavaWeb中的MVC设计模式
MVC这种设计模式,不光运用于Web领域,而且也能用于非Web领域;这里提到的MVC特指一种表现层设计模式,不限于Java语言

2、什么是springmvc,它与spring有什么关系
springmvc属于spring框架的后续产品,用在基于MVC的表现层开发,类似于struts2框架

3、springmvc与struts2的区别
① springmvc的入口是servlet,即前端控制器,例如:*.action;struts2入口是filter过虑器,即前端过滤器,例如:/*
② springmvc是基于方法开发,传递参数是通过方法形参,可以设计为单例;struts2是基于类开发,传递参数是通过类的属性,只能设计为多例
③ springmvc通过参数解析器是将request对象内容进行解析成方法形参,以方法参数形式收集值;struts采用值栈存储请求和响应的数据,以类形式收集值
④ springmvc的结果先绑定在ModelAndView对象中,再放入request域对象中;struts的结果先绑定在ValueStack对象中,再放入request域对象中
⑤ springmvc开发运行速度比struts相对快
……

4、springmvc工作流
① 客户端发出http请求,只要请求形式符合web.xml文件中配置的*.action的话,就由DispatcherServlet来处理,然后DispatcherServlet再将http请求委托给映射器的对象,把http请求交给对应的Action来处理
② 映射器根据客户的http请求,再对比<bean name="/hello.action>,如果匹配正确,再将http请求交给程序员写的Action
③ 执行Action中的业务方法,最终返回一个名叫ModelAndView的对象,其中封装了向视图发送的数据和视图的逻辑名
④ ModelAndView对象随着响应到到DispatcherServlet中
⑤ 这时DispatcherServlet收到了ModelAndView对象,它也不知道视图逻辑名是何意,又得委托一个名叫视图解析器的对象去具体解析ModelAndView对象中的内容
⑥ 将视图解析器解析后的内容,再次交由DispatcherServlet核心控制器,这时核心控制器再将请求转发到具体的视图页面,取出数据,再显示给用户

5、springmvc快速入门(XML版本)
① 创建springmvc-day01一个web应用
② 导入springioc,springweb , springmvc相关的jar包
③ 在/WEB-INF/下创建web.xml文件

    <!-- 注册springmvc核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 通知DispatcherServlet去指定的目录下加载springmvc.xml配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

	<!-- 注册spring提供的针对POST请求的中文乱码问题 -->
	<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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

④ 创建HelloAction.java控制器类

/**
 * 单例
 * 控制器Action
 * 处理器Action
 */
public class HelloAction implements Controller{
	public HelloAction(){
		System.out.println("HelloAction()::" + this.hashCode());
	}
	/**
	 * 业务方法
	 */
	public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		System.out.println("HelloAction::handleRequest()");
		/**
		 * ModelAndView表示向视图封装的数据和真实路径
		 */
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","这是我的第一个springmvc应用程序,映射器_适配器_视图解析器_都可省略");
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
}

⑤ 在/WebRoot/下创建jsp/success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>这是我的第一个springmvc应用程序</title>
  </head>
  <body>
	success.jsp<br/>
	${message}
  </body>
</html>

⑥ 在/WEB-INF/创建DispatcherServlet-servlet.xml配置文件,xml头部信息与spring.xml相同
注意:该配置文件的命名规则:web.xml文件中配置的<servlet-name>的值-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:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
	  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/context
      http://www.springframework.org/schema/context/spring-context-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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">

	<!-- 控制器(程序员) :name表示请求路径,class表示处理类的全路径,必选-->
    <bean name="/hello.action" class="cn.itcast.javaee.springmvc.base.HelloAction"></bean>  

    <!-- 映射器(框架):BeanNameUrlHandlerMapping表示将bean标签的name属性当做url请求,可选 -->  
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>  
         
    <!-- 适配器(框架):SimpleControllerHandlerAdapter用于寻找实现了Controller接口的Action类,可选 -->  
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>  
      
    <!-- 视图解析器(框架) :InternalResourceViewResolver表示ModelAndView对象封装的视图名找到真正的页面,可选-->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>  
</beans>

⑦ 部署web应用到tomcat中,通过浏览器访问URL

6、springmvc快速入门(注解版本)
① 创建springmvc-day02这么一个web应用
② 导入springioc,springweb和springmvc相关的jar包

   ------------------------------------------------------springWEB模块
   org.springframework.web-3.0.5.RELEASE.jar
   org.springframework.web.servlet-3.0.5.RELEASE.jar(mvc专用)
   ------------------------------------------------------springIOC模块
   org.springframework.asm-3.0.5.RELEASE.jar
   org.springframework.beans-3.0.5.RELEASE.jar
   org.springframework.context-3.0.5.RELEASE.jar
   org.springframework.core-3.0.5.RELEASE.jar
   org.springframework.expression-3.0.5.RELEASE.jar

③ 在/WEB-INF/下创建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">
  
	<!-- 注册springmvc核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<!-- 注册spring核心编码过滤器 -->
	<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>
	</filter>	
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

④ 创建HelloAction.java控制器类

@Controller
public class HelloAction{
	public HelloAction(){
		System.out.println("HelloAction()::" + this.hashCode());
	}
	/**
	 * 业务方法
	 * 只要是/hello.action的请求,都交由HelloAction对象中的hello()方法去处理
	 */
	@RequestMapping(value="/hello.action")   
	public String hello(Model model) throws Exception{
		System.out.println("HelloAction::hello()");
		model.addAttribute("message","你好");
		return "success";
	}
	
	/**
	 * 业务方法
	 * 只要是/bye.action的请求,都交由HelloAction对象中的bye()方法去处理
	 */
	@RequestMapping(value="/bye.action")   
	public String bye(Model model) throws Exception{
		System.out.println("HelloAction::bye()");
		model.addAttribute("message","再见");
		return "success";
	}
}

⑤ 在/WebRoot/下创建success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	/ok.jsp<br/>
	成功<br/>
	${message}<br/>
  </body>
</html>

⑥ 在/src/目录下创建spring.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:mvc="http://www.springframework.org/schema/mvc"
	  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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
        
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
        
      ">

	<!-- Action,让springioc容器去扫描带@Controller的类 -->
	<context:component-scan base-package="cn.itcast.javaee.springmvc.app14"/>
	
	<!-- 视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>      

⑦ 部署web应用到tomcat中,通过浏览器访问URL

三、springmvc.xml文件

1、加载自定义目录下的springmvc.xml配置文件
在默认情况下:springmvc框架的配置文件必须叫<servlet-name>-servlet.xml
且必须放在/WEB-INF/目录下,我们可以在web.xml文件中,为DispatcherServlet配置一个初始化参数,让它去我们指定的目录下加载springmvc.xml配置文件,web.xml代码如下:

    <!-- 注册springmvc框架核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/classes/cn/itcast/javaee/springmvc/config/springmvc.xml</param-value>	
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

如果springmvc.xml配置文件放在src目录下,web.xml代码如下:

<!-- 注册springmvc框架核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring.xml</param-value>	
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

2、视图解析器【作用:解析视图逻辑名对应的真实路径】
ModelAndView对象中即可以封装真实视图路径名,也可以封装视图路径的逻辑名

 <!-- 注册Action(必须配置) -->
      <bean name="/hello.action" class="cn.itcast.javaee.springmvc.app07.HelloAction"></bean> 
      <!-- 
      	如果Action中书写的是视图逻辑名称,那么视图解析器就必须配置 
      	如果Action中书写的是视图真实名称,那么视图解析器就可选配置 
      -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		<!-- 路径前缀 -->
      		<property name="prefix" value="/jsp/"/>
      		<!-- 路径后缀 -->
      		<property name="suffix" value=".jsp"/>
      		<!-- 前缀+视图逻辑名+后缀=真实路径 -->
      </bean>
public class HelloAction implements Controller{
	public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","这是我的第二个springmvc应用程序,视图使用逻辑名");
		//原来封装视图的真实路径
		//modelAndView.setViewName("/jsp/success.jsp");
		//现在封装视图的逻辑名称
		modelAndView.setViewName("success");
		return modelAndView;
	}
}

3、映射器【作用:把什么样的请求交给Action】
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping(核心)
将程序员定义的Action所对应的<bean>标签的name属性作为请求路径

      <!-- 注册控制器(程序员) -->
      <bean name="/add.action" class="cn.itcast.javaee.springmvc.mapping.UserAction"></bean>

      <!-- 注册映射器(handler包)(框架) -->
	  <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
把/delete.action和/update.action和/find.action请求路径都交由<bean>标签为id的Action,即多个路径对应同一个Action

      <!-- 注册控制器(程序员) -->
	  <bean id="userActionID" class="cn.itcast.javaee.springmvc.mapping.UserAction"></bean>
		
	  <!-- 注册映射器(handler包)(框架) -->
	  <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
	  		<property name="mappings">
	  			<props>
	  				<prop key="/delete.action">userActionID</prop>
	  				<prop key="/update.action">userActionID</prop>
	  				<prop key="/find.action">userActionID</prop>
	  			</props>
	  		</property>
	  </bean>

4、适配器Adapter【作用:找实现了Controller接口的Action】

/**
 * 控制器是实现Controller接口的类
 */
public class EmpAction implements Controller{
	public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView  modelAndView = new ModelAndView();
		//设置编码方式
		request.setCharacterEncoding("UTF-8");
		//获取员工姓名
		String username = request.getParameter("username");
		//显示
		System.out.println("员工姓名:" + username);
		//将员工姓名封装到ModelAndView对象中去
		modelAndView.addObject("message",username);
		//将真实路径名封装到ModelAndView对象中去
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
}

5、控制器Controller
org.springframework.web.servlet.mvc.ParameterizableViewController
如果请求是/hello.action的请求路径,则直接跳转到/jsp/success.jsp页面,不经过程序员定义的控制器Action

<!-- 专用于jsp到jsp/html的转发控制器 -->
    <bean name="/index.action" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
    	<!-- 转发到真实视图名 -->
    	<property name="viewName" value="/WEB-INF/05_index.jsp"/>
    </bean>

	<!-- 注册Action -->
	<bean name="/add.action" class="cn.itcast.javaee.springmvc.app10.EmpAction"></bean>
	
	<!-- 映射器 -->
    <!-- 适配器(SimpleControllerHandlerAdapter去找实现了Controller接口的Action,
    	       也能去找继承了AbstractCommandController类的Action,...)-->
	<!-- 视图解析器 -->

</beans>      

org.springframework.web.servlet.mvc.AbstractCommandController
能够以实体的形式,收集客户端参数(原因:Action类实现Controller接口,带来了代码耦合;如果参数过多,实现Controller接口的Action收集起来不便)

@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
	public EmpAction(){
		//将表单参数封装到Emp对象中去
		this.setCommandClass(Emp.class);
	}
	/**
	 * 自定义类型转换器,将String->Date类型(格式yyyy-MM-dd)
	 */
	@Override
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		//向springmvc内部注入一个自定义的类型转换器
		//参数一:将String转成什么类型的字节码
		//参数二:自定义转换规则
		//true表示该日期字段可以为空
		binder.registerCustomEditor(
				Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	/**
	 * obj表示封装后的实体
	 * error表示封装时产生的异常
	 */
	@Override
	protected ModelAndView handle(
			HttpServletRequest request,
			HttpServletResponse response, 
			Object obj, 
			BindException error)throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","增加员工成功");
		Emp emp = (Emp) obj;
		System.out.println(emp.getUsername()+":"+emp.getGender()+":"+emp.getHiredate().toLocaleString());
		//将Emp封装到ModeAndView对象中
		modelAndView.addObject("emp",emp);
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
}

四、SpringMVC细节

1、日期转换器
在默认情况下,springmvc不能将String类型转成Date类型,必须自定义类型转换器

@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
	public EmpAction(){
		//将表单参数封装到Emp对象中去
		this.setCommandClass(Emp.class);
	}
	/**
	 * 自定义类型转换器,将String->Date类型(格式yyyy-MM-dd)
	 */
	@Override
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		//向springmvc内部注入一个自定义的类型转换器
		//参数一:将String转成什么类型的字节码
		//参数二:自定义转换规则
		//true表示该日期字段可以为空
		binder.registerCustomEditor(
				Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	/**
	 * obj表示封装后的实体
	 * error表示封装时产生的异常
	 */
	@Override
	protected ModelAndView handle(
			HttpServletRequest request,
			HttpServletResponse response, 
			Object obj, 
			BindException error)throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message","增加员工成功");
		Emp emp = (Emp) obj;
		System.out.println(emp.getUsername()+":"+emp.getGender()+":"+emp.getHiredate().toLocaleString());
		//将Emp封装到ModeAndView对象中
		modelAndView.addObject("emp",emp);
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
}

success.jsp:

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	success.jsp<br/>
	成功<br/>
	${requestScope.message}<br/>
	姓名:${requestScope.emp.username}<br/>
	性别:${requestScope.emp.gender}<br/>
	
	入职时间:${requestScope.emp.hiredate}<br/>
	<hr/>
	入职时间:<fmt:formatDate 
				value="${requestScope.emp.hiredate}"
				type="date"
				dateStyle="medium"
			/>
	<!-- 
		1)fmt:formatDate 来源于 http://java.sun.com/jsp/jstl/fmt
		2)fmt:formatDate作用是格式化日期的显示,例如:2015年5月10日 星期日
		3)value表示需要格式化的值
		4)type表示显示日期,时间,都显示
		  type=date表示只显示日期
		  type=time表示只显示时间
		  type=both表示日期时间均显示
		5)dateStyle表示显示日期的格式:short/medium/default/long/full
	-->
  </body>
</html>

2、编码过滤器
spring提供的,专用于解决POST提交中文乱码问题,需要在web.xml文件中配置

	<!-- 编码过滤器 -->
	<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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

3、一个Action中,如何写多个类似的业务控制方法
方法:通过模块根路径 + 功能子路径 = 访问模块下子功能的路径

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	<form action="${pageContext.request.contextPath}/user/register.action" method="POST">
		<table border="2" align="center">
			<caption><h2>用户注册</h2></caption>
			<tr>
				<th>姓名</th>
				<td><input type="text" name="username"/></td>
			</tr>
			<tr>
				<th>月薪</th>
				<td><input type="text" name="salary" value="7000"/></td>
			</tr>
			<tr>
				<th>入职时间</th>
				<td><input type="text" name="hiredate" value="2015-5-11 12:12:12"/></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="注册" style="width:111px"/>
				</td>
			</tr>
		</table>	
	</form>	
	
	<hr/>
	
	<form action="${pageContext.request.contextPath}/user/login.action" method="POST">
		<table border="2" align="center">
			<caption><h2>用户登录</h2></caption>
			<tr>
				<th>姓名</th>
				<td><input type="text" name="username"/></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="登录" style="width:111px"/>
				</td>
			</tr>
		</table>	
	</form>	
  </body>
</html>
@Controller
@RequestMapping(value="/user")
public class UserAction {
	/**
	 * 用户注册
	 */
	@RequestMapping(value="/register")
	public String registerMethod(Model model) throws Exception{
		model.addAttribute("message","员工注册成功");
		return "/jsp/success.jsp";
	}
	/**
	 * 用户登录
	 */
	@RequestMapping(value="/login")
	public String loginMethod(Model model) throws Exception{
		model.addAttribute("message","员工登录成功");
		return "/jsp/success.jsp";
	}
}

增加用户:http://127.0.0.1:8080/myspringmvc-day02/user/add.action
查询用户:http://127.0.0.1:8080/myspringmvc-day02/user/find.action

4、在业务控制方法中写入普通变量收集参数
方法:可以在业务控制方法中,以参数形式收集客户端参数,springmvc采用方法参数形式的

@Controller
@RequestMapping(value="/user")
public class UserAction {
	/**
	 * 用户注册
	 */
	@RequestMapping(value="/register")
	public String registerMethod(Model model,String username,String salary) throws Exception{
		System.out.println("用户注册-->" + username + ":" + salary);
		model.addAttribute("message","员工注册成功");
		return "/jsp/success.jsp";
	}
	/**
	 * 用户登录
	 */
	@RequestMapping(value="/login")
	public String loginMethod(Model model,String username) throws Exception{
		System.out.println("用户登录-->" + username);
		model.addAttribute("message","员工登录成功");
		return "/jsp/success.jsp";
	}
}

5、限定某个业务控制方法,只允许GET或POST请求方式访问
方法:可以在业务控制方法前,指明该业务控制方法只能接收GET或POST的请求,如果不书写method=RequestMethod.POST的话,GET和POST请求都支持

@Controller
@RequestMapping(value="/user")
public class UserAction {
	/**
	 * 用户注册,只能接收POST请求
	 */
	@RequestMapping(method=RequestMethod.POST,value="/register")
	public String registerMethod(Model model,String username,String salary) throws Exception{
		System.out.println("用户注册-->" + username + ":" + salary);
		model.addAttribute("message","员工注册成功");
		return "/jsp/success.jsp";
	}
	/**
	 * 用户登录,即能接收POST请求,又能接收GET请求
	 */
	@RequestMapping(value="/login")
	public String loginMethod(Model model,String username) throws Exception{
		System.out.println("用户登录-->" + username);
		model.addAttribute("message","员工登录成功");
		return "/jsp/success.jsp";
	}
}

6、在业务控制方法中写入Request,Response等传统web参数
方法:可以在业务控制方法中书写传统web参数【这种方式不提倡,耦合】

@Controller
@RequestMapping(value="/user")
public class UserAction {
	/**
	 * 用户注册,只能接收POST请求
	 */
	@RequestMapping(method=RequestMethod.POST,value="/register")
	public String registerMethod(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//获取用户名和薪水
		String username = request.getParameter("username");
		String salary = request.getParameter("salary");
		System.out.println("用户注册-->" + username + ":" + salary);
		
		//绑定到session域对象中
		request.getSession().setAttribute("username",username);
		request.getSession().setAttribute("salary",salary);
		
		//重定向/jsp/success.jsp页面
		//response.sendRedirect(request.getContextPath()+"/jsp/success.jsp");
		
		//转发/jsp/ok.jsp页面
		request.getRequestDispatcher("/jsp/ok.jsp").forward(request,response);
		
		//转发(提倡)
		return "/jsp/success.jsp";
	}
}

7、在业务控制方法中写入模型变量收集参数,且使用@InitBind来解决字符串转日期类型
原因:在默认情况下,springmvc不能将String类型转成java.util.Date类型,所有我们只能在Action中自定义类型转换器

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	/success.jsp<br/>
	成功<br/>
	${user.id}<br/>
	${user.username}<br/>
	${user.salary}<br/>
	
	<fmt:formatDate
		value="${user.hiredate}"
		type="both"
		dateStyle="full"
		timeStyle="default"
	/>
	<br/>
  </body>
</html>
public class User {
	private Integer id = 1;
	private String username;
	private Double salary;
	private Date hiredate;
	public User(){}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
	@Override
	public String toString() {
		return this.id+":"+this.username+":"+this.salary+":"+this.hiredate.toLocaleString();
	}
}
@Controller
@RequestMapping(value="/user")
public class UserAction {
	/**
	 * 自定义类型转换器
	 */
	@InitBinder
	public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),true));
	}
	/**
	 * 用户注册,只能接收POST请求
	 */
	@RequestMapping(method=RequestMethod.POST,value="/register")
	public String registerMethod(User user,Model model) throws Exception{
		System.out.println("用户注册:" + user.toString());
		//将user绑定到model对象中
		model.addAttribute("user",user);
		//转发到success.jsp页面
		return "/jsp/success.jsp";
	}
}

8、在业务控制方法中写入User、Admin多个模型(0个或多个)收集客户端的参数
方法:
① 如果多个模型中有相同的属性时,可以用user.name或admin.name来收集客户端参数
② 用一个新的模型将User和Admin再封装一次

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body> 
    普通用户 
	<form action="${pageContext.request.contextPath}/person/register.action" method="POST">
		<table border="2" align="center">
			<tr>
				<th>姓名</th>
				<td><input type="text" name="user.username" value="${user.username}"/></td>
			</tr>
			<tr>
				<th>月薪</th>
				<td><input type="text" name="user.salary" value="${user.salary}"></td>
			</tr>
			<tr>
				<th>入职时间</th>
				<td><input 
						type="text" 
						name="user.hiredate" 
						value='<fmt:formatDate value="${user.hiredate}" type="date" dateStyle="default"/>'/></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="普通用户注册" style="width:111px"/>
				</td>
			</tr>
		</table>	
	</form>	

	<hr/>

	管理员
	<form action="${pageContext.request.contextPath}/person/register.action" method="POST">
		<table border="2" align="center">
			<tr>
				<th>姓名</th>
				<td><input type="text" name="admin.username" value="${admin.username}"/></td>
			</tr>
			<tr>
				<th>月薪</th>
				<td><input type="text" name="admin.salary" value="${admin.salary}"/></td>
			</tr>
			<tr>
				<th>入职时间</th>
				<td><input type="text" name="admin.hiredate" value='<fmt:formatDate value="${admin.hiredate}" type="date" dateStyle="default"/>'/></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="管理员注册" style="width:111px"/>
				</td>
			</tr>
		</table>	
	</form>	
  </body>
</html>
/**
 * 封装User和Admin的对象
 */
public class Bean {
	private User user;
	private Admin admin;
	public Bean(){}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public Admin getAdmin() {
		return admin;
	}
	public void setAdmin(Admin admin) {
		this.admin = admin;
	}
}
@Controller
@RequestMapping(value="/person")
public class PersonAction {
	@InitBinder
	public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}

	// 业务方法
	@RequestMapping(value="/register")
	public String registerMethod(Bean bean,Model model) throws Exception{
		System.out.println("普通用户:" + bean.getUser());
		System.out.println("管理员:" + bean.getAdmin());
		//将user和admin都绑定到Model
		model.addAttribute("user",bean.getUser());
		model.addAttribute("admin",bean.getAdmin());
		//转发
		return "/02_person.jsp";
	}
}

9、在业务控制方法中收集数组参数【例如:批量删除用户】

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body> 
    <form action="${pageContext.request.contextPath}/emp/deleteAll.action" method="POST">
    	<table border="2" align="center">
    		<tr>
    			<th>编号</th>
    			<th>姓名</th>
    		</tr>
    		<tr>
    			<td><input type="checkbox" name="ids" value="1"/></td>
    			<td>哈哈</td>
    		</tr>
    		<tr>
    			<td><input type="checkbox" name="ids" value="2"/></td>
    			<td>呵呵</td>
    		</tr>
    		<tr>
    			<td><input type="checkbox" name="ids" value="3"/></td>
    			<td>嘻嘻</td>
    		</tr>
    		<tr>
    			<td><input type="checkbox" name="ids" value="4"/></td>
    			<td>笨笨</td>
    		</tr>
    		<tr>
    			<td><input type="checkbox" name="ids" value="5"/></td>
    			<td>聪聪</td>
    		</tr>
    		<tr>
    			<td>
    				<input type="submit" value="删除"/>
    			</td>
    		</tr>
    	</table>
    </form>
  </body>
</html>
@Controller
@RequestMapping(value="/emp")
public class EmpAction {
	@RequestMapping(value="/deleteAll",method=RequestMethod.POST)
	public String deleteAll(Model model,int[] ids) throws Exception{
		System.out.println("需要删除的员工编号分别是:");
		for(int id : ids){
			System.out.print(id+" ");
		}
		model.addAttribute("message","批量删除员工成功");
		return "/jsp/ok.jsp";
	}
}

10、在业务控制方法中收集List<JavaBean>参数【例如:批量注册用户】

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body> 
    <form action="${pageContext.request.contextPath}/emp/addAll.action" method="POST">
    	<table border="2" align="center">
    		<caption><h2>批量注册员工</h2></caption>
    		<tr>
    			<td><input type="text" name="empList[0].username" value="哈哈"/></td>
    			<td><input type="text" name="empList[0].salary" value="7000"/></td>
    		</tr>
    		<tr>
    			<td><input type="text" name="empList[1].username" value="呵呵"/></td>
    			<td><input type="text" name="empList[1].salary" value="7500"/></td>
    		</tr>
    		<tr>
    			<td><input type="text" name="empList[2].username" value="班长"/></td>
    			<td><input type="text" name="empList[2].salary" value="8000"/></td>
    		</tr>
    		<tr>
    			<td><input type="text" name="empList[3].username" value="键状哥"/></td>
    			<td><input type="text" name="empList[3].salary" value="8000"/></td>
    		</tr>
    		<tr>
    			<td><input type="text" name="empList[4].username" value="绿同学"/></td>
    			<td><input type="text" name="empList[4].salary" value="9000"/></td>
    		</tr>
    		<tr>
    			<td colspan="2" align="center">
    				<input type="submit" value="批量注册"/>
    			</td>
    		</tr>
    	</table>
    </form>
  </body>
</html>
public class Emp {
	private String username;//姓名
	private Double salary;//薪水
	public Emp(){}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
}

/**
 * 封装多个Emp的对象 
 * @author AdminTC
 */
public class Bean {
	private List<Emp> empList = new ArrayList<Emp>();
	public Bean(){}
	public List<Emp> getEmpList() {
		return empList;
	}
	public void setEmpList(List<Emp> empList) {
		this.empList = empList;
	}
}
@Controller
@RequestMapping(value="/emp")
public class EmpAction {
	/**
	 * 批量添加员工
	 */
	@RequestMapping(value="/addAll",method=RequestMethod.POST)
	public String addAll(Model model,Bean bean) throws Exception{
		for(Emp emp:bean.getEmpList()){
			System.out.println(emp.getUsername()+":"+emp.getSalary());
		}
		model.addAttribute("message","批量增加员工成功");
		return "/jsp/ok.jsp";
	}
}

11、结果的转发和重定向
在转发情况下,共享request域对象,会将参数从第一个业务控制方法传入第二个业务控制方法;反之,重定向则不行

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body> 
    
    1 哈哈 7000
    &nbsp;&nbsp;&nbsp;&nbsp;
    <a href="${pageContext.request.contextPath}/emp/find.action?id=1" style="text-decoration:none">编辑</a>
    
  </body>
</html>
@Controller
@RequestMapping(value="/emp")				
public class EmpAction {
	@RequestMapping(value="/find")
	public String findEmpById(int id,Model model) throws Exception{
		System.out.println("查询"+id+"号员工信息");
		//转发到EmpAction的另一个方法中去,即再次发送请求
		return "forward:/emp/update.action";
		//重定向到EmpAction的另一个方法中去,即再次发送请求
		//return "redirect:/emp/update.action?id=" + id;
	}

	@RequestMapping(value="/update")
	public String updateEmpById(int id,Model model) throws Exception{
		System.out.println("更新" + id +"号员工信息");
		model.addAttribute("message","更新员工信息成功");
		return "/jsp/ok.jsp";
	}
}

12、异步发送表单数据到JavaBean并响应JSON文本返回到浏览器
方法步骤:
① 导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar
② 在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本
③ 在spring.xml配置文件中编写如下代码:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
				<property name="messageConverters">
						<list>
							<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
						</list>
				</property>
		    </bean>
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  	<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
  </head>
  <body> 

   <input type="button" value="Emp转JSON"/><p>
   <input type="button" value="List<Emp>转JSON"/><p>
   <input type="button" value="Map<String,Object>转JSON"/><p>

   <!-- Map<String,Object>转JSON -->	  
   <script type="text/javascript">
   		$(":button:last").click(function(){
   			var url = "${pageContext.request.contextPath}/emp/map2json.action";
   			var sendData = null;
			$.post(url,sendData,function(backData,textStaut,ajax){
				alert(ajax.responseText);
			});		
   		});
   </script>

   <!-- List<Emp>转JSON -->	  
   <script type="text/javascript">
   		$(":button:eq(1)").click(function(){
   			var url = "${pageContext.request.contextPath}/emp/listbean2json.action";
   			var sendData = null;
			$.post(url,sendData,function(backData,textStaut,ajax){
				alert(ajax.responseText);
			});		
   		});
   </script>
   
   <!-- Emp转JSON -->	  
   <script type="text/javascript">
   		$(":button:first").click(function(){
   			var url = "${pageContext.request.contextPath}/emp/bean2json.action";
   			var sendData = null;
			$.post(url,sendData,function(backData,textStaut,ajax){
				//alert(ajax.responseText);
				var hiredate = backData.hiredate;
				var date = new Date(hiredate);
				alert(date.getFullYear()+"年"+(date.getMonth()+1)+"月"+(date.getDate())+"日");
			});		
   		});
   </script>
  </body>
</html>
@Controller
@RequestMapping(value="/emp")
public class EmpAction {
	/**
     * @ResponseBody Emp 表示让springmvc将Emp对象转成json文本
	 */
	@RequestMapping(value="/bean2json")
	public @ResponseBody Emp bean2json() throws Exception{
		//创建Emp对象
		Emp emp = new Emp();
		emp.setId(1);
		emp.setUsername("哈哈");
		emp.setSalary(7000D);
		emp.setHiredate(new Date());
		return emp;
	}
	
	@RequestMapping(value="/listbean2json")
	public @ResponseBody List<Emp> listbean2json() throws Exception{
		//创建List对象
		List<Emp> empList = new ArrayList<Emp>();
		//向List对象中添加三个Emp对象
		empList.add(new Emp(1,"哈哈",7000D,new Date()));
		empList.add(new Emp(2,"呵呵",8000D,new Date()));
		empList.add(new Emp(3,"嘻嘻",9000D,new Date()));
		//返回需要转JSON文本的对象
		return empList;
	}

	
	@RequestMapping(value="/map2json")
	public @ResponseBody Map<String,Object> map2json() throws Exception{
		//创建List对象
		List<Emp> empList = new ArrayList<Emp>();
		//向List对象中添加三个Emp对象
		empList.add(new Emp(1,"哈哈",7000D,new Date()));
		empList.add(new Emp(2,"呵呵",8000D,new Date()));
		empList.add(new Emp(3,"嘻嘻",9000D,new Date()));
		//创建Map对象
		Map<String,Object> map = new LinkedHashMap<String,Object>();
		//向Map对象中绑定二个变量
		map.put("total",empList.size());
		map.put("rows",empList);
		//返回需要转JSON文本的对象
		return map;
	}
}
<?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:mvc="http://www.springframework.org/schema/mvc"
	  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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
        
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
        
      ">

		<!-- EmpAction类  -->
		<context:component-scan base-package="cn.itcast.javaee.springmvc.app25"/>

		<!-- 注册适配器 -->
		<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
				<property name="messageConverters">
						<list>
							<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
						</list>
				</property>
		</bean>
</beans>      

五、员工管理系统(springmvc + spring + jdbc + oracle)

1、Emp.java(JavaBean的属性用包装类型:Integer、Double;普通方法的参数类型用基础类型:int、double)

public class Emp {
	private String id;//编号
	private String username;//姓名
	private Double salary;//薪水
	private Date hiredate;//入职时间
	public Emp(){}
	public String getId() {
		return UUID.randomUUID().toString();
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
}
public class Emp {
	private Integer empno;
	private String ename;
	private String job;
	private Integer mgr;
	private Date hiredate;
	private Integer sal;
	private Integer comm;
	private Integer deptno;
	public Emp(){}
	public Integer getEmpno() {
		return empno;
	}
	public void setEmpno(Integer empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	public Integer getMgr() {
		return mgr;
	}
	public void setMgr(Integer mgr) {
		this.mgr = mgr;
	}
	public Date getHiredate() {
		return hiredate;
	}
	public void setHiredate(Date hiredate) {
		this.hiredate = hiredate;
	}
	public Integer getSal() {
		return sal;
	}
	public void setSal(Integer sal) {
		this.sal = sal;
	}
	public Integer getComm() {
		return comm;
	}
	public void setComm(Integer comm) {
		this.comm = comm;
	}
	public Integer getDeptno() {
		return deptno;
	}
	public void setDeptno(Integer deptno) {
		this.deptno = deptno;
	}
}

2、JdbcUtil.java

public class JdbcUtil {
	// 去src目录下加载c3p0-config.xml配置文件
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	// 获取数据源
	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}
}

3、c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
		<property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
		<property name="user">scott</property>
		<property name="password">tiger</property>
		<property name="acquireIncrement">2</property>
		<property name="initialPoolSize">5</property>
		<property name="minPoolSize">1</property>
		<property name="maxPoolSize">5</property>
	</default-config>
</c3p0-config>

4、EmpDao.java

/**
 * 员工管理模块
 * 持久层实现类
 */
public class EmpDao {
	// 增加员工
	public void add(Emp emp) throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
		String sql = "insert into emps(id,username,salary,hiredate) values(?,?,?,?)";
		Object[] params = {emp.getId(),emp.getUsername(),emp.getSalary(),emp.new Timestamp(getHiredate()).getTime()};
		runner.update(sql,params);
	}

	public static void main(String[] args) throws Exception{
		Emp emp = new Emp();
		emp.setId("a140a519-6168-4a97-a753-5c5e5cf0a8b2");
		emp.setUsername("哈哈");
		emp.setSalary(7000D);
		String year = "15";
		String month = "5月";
		String date = "10";
		String str = date+"-"+month+"-"+year;
		DateFormat df = new SimpleDateFormat("dd-MM-yy");
		emp.setHiredate(df.parse(str));
		EmpDao dao = new EmpDao();
		dao.add(emp);	
	}
}
@Component("empDao")
public class EmpDao {
	/**
	 * 查询所有员工
	 */	
	public List<Emp> findAll() throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
		String sql = "SELECT EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO FROM EMP";
		return runner.query(sql,new BeanListHandler<Emp>(Emp.class));
	}	

	@Test
	public void testFindAll() throws Exception{
		EmpDao dao = new EmpDao();
		for(Emp emp : dao.findAll()){
			System.out.println(emp.getEmpno()+":"+emp.getEname()+":"+emp.getSal());
		}
	}
}

5、EmpService.java

/**
 * 员工管理模块
 * 业务层实现类
 */
public class EmpService {
	private EmpDao empDao;
	public void setEmpDao(EmpDao empDao) {
		this.empDao = empDao;
	}
	// 增加员工
	public void register(Emp emp) throws Exception{
		empDao.add(emp);
	}
}
@Component("empService")
public class EmpService {
	private EmpDao empDao;
	@Resource(name="empDao")
	public void setEmpDao(EmpDao empDao) {
		this.empDao = empDao;
	}
	
	// 查询所有员工
	public List<Emp> findAllEmp() throws Exception{
		return empDao.findAll();
	}
}

6、EmpAction.java

/**
 * 员工管理模块
 * 控制器
 */
@SuppressWarnings("deprecation")
public class EmpAction extends AbstractCommandController{
	//业务层
	private EmpService empService;
	public void setEmpService(EmpService empService) {
		this.empService = empService;
	}
	//将表单参数封装到Emp实体中
	public EmpAction(){
		this.setCommandClass(Emp.class);
	}
	//自定义String到Date的转换器
	@Override
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("dd-MM-yy"),true));
	}
	@Override
	protected ModelAndView handle(
			HttpServletRequest request,
			HttpServletResponse response, 
			Object obj, 
			BindException error)
			throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		Emp emp = (Emp) obj;
		System.out.println(emp.getHiredate().toLocaleString());
		empService.register(emp);
		modelAndView.addObject("message","操作成功");
		modelAndView.setViewName("success");
		return modelAndView;
	}
}
@Controller
@RequestMapping("/emp")
public class EmpAction{ 
	private EmpService empService;
	@Resource(name="empService")
	public void setEmpService(EmpService empService) {
		this.empService = empService;
	}
	
	/**
	 * 查询所有的员工
	 */
	@RequestMapping("/findAllEmpMethod")
	public @ResponseBody Map<String,Object> findAllEmpMethod() throws Exception{
		//调用业务层,返回List对象
		List<Emp> empList = empService.findAllEmp();
		//创建Map对象
		Map<String,Object> map = new LinkedHashMap<String,Object>();
		//封装DataGrid需要的二个参数
		map.put("total",empList.size());
		map.put("rows",empList);
		//返回需要转成JSON文本的对象
		return map;
	}
}

7、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">

	<!-- 注册springmvc核心控制器 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<!-- 注册针对POST请求的编码器 -->
		<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>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

8、spring.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: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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">
      
      <import resource="cn/itcast/emp/config/spring-emp.xml"/>
</beans>    

9、spring-emp.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: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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">
      
      <!-- 注册EmpDao类 -->
      <bean id="empDaoID" class="cn.itcast.emp.dao.EmpDao"></bean>

      <!-- 注册EmpService类 -->
      <bean id="empServiceID" class="cn.itcast.emp.service.EmpService">
      		<property name="empDao" ref="empDaoID"/>
      </bean>
      
	  <!-- 注册Action -->
      <bean name="/add.do" class="cn.itcast.emp.action.EmpAction">
      	<property name="empService" ref="empServiceID"/>
      </bean>	
	  <!-- 映射器 -->	      
	  <!-- 适配器 -->
	  <!-- 视图解析器 -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		<property name="prefix" value="/"/>
      		<property name="suffix" value=".jsp"/>
      </bean>
</beans>      
<?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:mvc="http://www.springframework.org/schema/mvc"
      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/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
      
        
      ">

    <!-- 注册适配器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    	<property name="messageConverters">
    		<list>
    			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    		</list>
    	</property>
    </bean>

	<!-- 注册EmpAction -->
	<context:component-scan base-package="cn.itcast.emp"/>	    

	<!--让springioc容器去解析@Resource这些解的含义,可省 
    	<context:annotation-config/>
    -->
</beans>  

10、index.jsp

<html>
  <head>
    <title>员工管理系统</title>
  </head>
  <body>
		<form action="${pageContext.request.contextPath}/add.do" method="POST">
		<table border="2" align="center">
			<tr>
				<th>姓名</th>
				<td><input type="text" name="username"/></td>				
			</tr>
			<tr>
				<th>期望薪水</th>
				<td>
					<input type="text" name="salary" value="7000"/>
				</td>				
			</tr>
			<tr>
				<th>入职时间</th>
				<td>
					<input type="text" name="hiredate" value="2015-5-10"/>
				</td>				
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="提交"/>
				</td>
			</tr>
		</table>
	</form>
  </body>
</html>

11、success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
	/success.jsp<br/>
	${requestScope.message}<br/>
  </body>
</html>

12、empList.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  		<link rel="stylesheet" href="${pageContext.request.contextPath}/themes/default/easyui.css" type="text/css"></link>
  		<link rel="stylesheet" href="${pageContext.request.contextPath}/themes/icon.css" type="text/css"></link>
  		<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
  		<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script>
  		<script type="text/javascript" src="${pageContext.request.contextPath}/js/easyui-lang-zh_TW.js"></script>
  </head>
  <body>
	<table id="dg"></table>
	<script type="text/javascript">
		$("#dg").datagrid({
			url : "${pageContext.request.contextPath}/emp/findAllEmpMethod.do?time="+new Date().getTime(),
			columns:[[    
		        {field:'empno',title:'编号',width:100},    
		        {field:'ename',title:'姓名',width:100},    
		        {field:'job',title:'职位',width:100},   
		        {field:'mgr',title:'上级编号',width:100},   
		        {field:'hiredate',title:'入职时间',width:100,
		        	formatter:function(value){
		        		var date = new Date(value);
		        		var year = date.getFullYear();
		        		var month = date.getMonth()+1;
		        		var date = date.getDate();
		        		return year+"年"+month+"月"+date+"日";
		        	}
		        },    
		        {field:'sal',title:'薪水',width:100},  
		        {field:'comm',title:'佣金',width:100,
		        	formatter:function(value){
		        		if(value == null){
		        			return 0;
		        		}else{
		        			return value;
		        		}
		        	}
		        },   
		        {field:'deptno',title:'部门编号',width:100}   
		    ]],
		    singleSelect : true,
		    pagination : true  
		});	
	</script>	
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/Mr_GaoYang/article/details/85048156