1. 程式人生 > >二、Springmvc+Mybatis 引數繫結之預設引數繫結 簡單型別繫結 POJO繫結 POST亂碼問題

二、Springmvc+Mybatis 引數繫結之預設引數繫結 簡單型別繫結 POJO繫結 POST亂碼問題

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springmvc-mybatis</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
 <!--  Spring監聽器,載入spring配置檔案applicationContext.xml -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- POST提交亂碼問題 -->
  <filter>
  	<filter-name>encoding</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>encoding</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
   <!--  前端控制器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<!-- 
  		1./* 攔截所有 jsp js png .css 真的全攔截,不建議使用
  		2.*.action *.do 攔截以do action 結尾的請求,肯定能使用
  		3./ 攔截所有(不包括jsp) 包含.js .png .css 強烈建議使用, 前臺,面向消費者  /對靜態資源放行
  	 -->
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
</web-app>

sqlMapConfig.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>
		<!-- 2. 指定掃描包,會把包內所有的類都設定別名,別名的名稱就是類名,大小寫不敏感 -->
		<package name="com.itheima.springmvc.pojo" />
	</typeAliases>
	
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

   <!-- 載入配置檔案 -->
   <context:property-placeholder location="classpath:db.properties" />

	<!-- 資料庫連線池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>

	<!-- 配置SqlSessionFactory -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置mybatis核心配置檔案 -->
		<property name="configLocation" value="classpath:sqlMapConfig.xml" />
		<!-- 配置資料來源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- Mapper動態代理開發 掃描 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 基本包 -->
		<property name="basePackage" value="com.itheima.springmvc.dao"></property>
	</bean>
	
	<!-- 註解事務 -->
	<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	<!-- 開啟註解 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
</beans>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 掃描@Controller @Service -->
	<context:component-scan base-package="com.itheima"></context:component-scan>
	
	 
	<!-- 處理器對映器 -->
<!-- 	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> -->
	<!-- 處理器介面卡 -->
<!-- 	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
	

	<!-- 註解驅動 -->
        <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
        
    <!-- 配置Conveter轉換器  轉換工廠 (日期、去掉前後空格)。。 -->
       <bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       	<!-- 配置 多個轉換器-->
       	<property name="converters">
       		<list>
       			<bean class="com.itheima.springmvc.conversion.DateConverter"/>
       		</list>
       	</property>
       </bean>
	
	<!-- 檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
</beans>

Items

package com.itheima.springmvc.pojo;

import java.util.Date;

public class Items {
    private Integer id;

    private String name;

    private Float price;

    private String pic;

    private Date createtime;

    private String detail;
    
    

    public Items() {
		super();
	}

	public Items(Integer id, String name, Float price, Date createtime, String detail) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.createtime = createtime;
		this.detail = detail;
	}

	public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic == null ? null : pic.trim();
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }
}

ItemsMapper

package com.itheima.springmvc.dao;

import com.itheima.springmvc.pojo.Items;
import com.itheima.springmvc.pojo.ItemsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface ItemsMapper {
    int countByExample(ItemsExample example);

    int deleteByExample(ItemsExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Items record);

    int insertSelective(Items record);

    List<Items> selectByExampleWithBLOBs(ItemsExample example);

    List<Items> selectByExample(ItemsExample example);

    Items selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByPrimaryKeySelective(Items record);

    int updateByPrimaryKeyWithBLOBs(Items record);

    int updateByPrimaryKey(Items record);
}

ItemController

package com.itheima.springmvc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.itheima.springmvc.pojo.Items;
import com.itheima.springmvc.pojo.QueryVo;
import com.itheima.springmvc.service.ItemService;

/**
 * 商品管理
 * @author mjl
 *
 */
@Controller
public class ItemController {

	@Autowired
	private ItemService itemService;
	
	//顯示所有商品
	@RequestMapping(value="/item/itemList.action")
	public ModelAndView itemList(){
		
		//從Mysql查詢資料
		List<Items> list = itemService.selectItemList();
		System.out.println(list);
		
		ModelAndView mv = new ModelAndView();
		//新增資料
		mv.addObject("itemList", list);
		mv.setViewName("itemList");
		return mv;
	}
	
	/**
	 * 1、預設引數繫結(request response session等)
	 * 2、簡單型別
	 * @param id
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @return
	 */
	//去修改頁面入參id
	@RequestMapping(value="/itemEdit.action")
	public ModelAndView toEdit(Integer id,HttpServletRequest request,HttpServletResponse response,
			HttpSession session,Model model){
		
		//servlet時期開發
	//	String id = request.getParameter("id");
	//	Items items = itemService.selectItemsById(Integer.parseInt(id));
		
		//直接繫結簡單型別
		Items items = itemService.selectItemsById(id);
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("item",items);
		mv.setViewName("editItem");
		return mv;
	}
	
	/**
	 * 3.POJO繫結
	 * @param items
	 * @return
	 */
	//提交修改頁面,入參為Items物件
	@RequestMapping(value="/updateitem.action")
	public ModelAndView updateItem(Items items){
		
		//修改 
		itemService.updateItemsById(items);
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("success");
		return mv;
	}
	
	/**
	 * 4、包裝類QueryVo繫結
	 * !!!!!!!!!在jsp頁面獲取屬性時,用包裝類裡面的屬性.屬性,如items.name
	 * @param vo
	 * @return
	 */
	//提交修改頁面,入參為Items的包裝類
	@RequestMapping(value="/updateitemVo.action")
	public ModelAndView updateQueryVo(QueryVo vo){
		itemService.updateItemsById(vo.getItems());
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("success");
		return mv;
	}
}

ItemService

public interface ItemService {

	//查詢列表
	public List<Items> selectItemList();
	
	//根據Id查詢items
	public Items selectItemsById(Integer id);
	
	//修改
	public void updateItemsById(Items items);
	
}

ItemServiceImpl

package com.itheima.springmvc.service;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.springmvc.dao.ItemsMapper;
import com.itheima.springmvc.pojo.Items;

/**
 * 查詢商品資訊
 * @author mjl
 *
 */
@Service
public class ItemServiceImpl implements  ItemService{

	@Autowired
	private ItemsMapper itemsMapper;
	
	//查詢商品列表
	public List<Items> selectItemList(){
		return itemsMapper.selectByExampleWithBLOBs(null);
	}

	//根據Id查詢商品
	public Items selectItemsById(Integer id) {
		return itemsMapper.selectByPrimaryKey(id);
	}

	//修改
	public void updateItemsById(Items items) {
		items.setCreatetime(new Date());
		itemsMapper.updateByPrimaryKeyWithBLOBs(items);
		
	}
}

 

itemList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查詢商品列表</title>
</head>
<body> 
	<form action="${pageContext.request.contextPath }/item/queryitem.action" method="post">
		查詢條件:
		<table width="100%" border=1>
			<tr>
				<td><input type="submit" value="查詢"/></td>
			</tr>
		</table>
		商品列表:
		<table width="100%" border=1>
			<tr>
				<td>商品名稱</td>
				<td>商品價格</td>
				<td>生產日期</td>
				<td>商品描述</td>
				<td>操作</td>
			</tr>
			<c:forEach items="${itemList }" var="item">
				<tr>
					<td>${item.name }</td>
					<td>${item.price }</td>
					<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
					<td>${item.detail }</td>
					
					<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
				
				</tr>
			</c:forEach>
		</table>
	</form>
</body>

</html>

editItem

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品資訊</title>

</head>
<body> 
	<!-- 上傳圖片是需要指定屬性 enctype="multipart/form-data" -->
	<!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
	<form id="itemForm"	action="${pageContext.request.contextPath }/updateitem.action" method="post">
		<input type="hidden" name="id" value="${item.id }" /> 修改商品資訊:
		<table width="100%" border=1>
			<tr>
				<td>商品名稱</td>
				<td><input type="text" name="name" value="${item.name }" /></td>
			</tr>
			<tr>
				<td>商品價格</td>
				<td><input type="text" name="price" value="${item.price }" /></td>
			</tr>
		 
			<tr>
				<td>商品生產日期</td>
				<td><input type="text" name="createtime"
					value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
			</tr>
			<tr>
				<td>商品圖片</td>
				<td>
					<c:if test="${item.pic !=null}">
						<img src="/pic/${item.pic}" width=100 height=100/>
						<br/>
					</c:if>
					<input type="file"  name="pictureFile"/> 
				</td>
			</tr>
			
			<tr>
				<td>商品簡介</td>
				<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center"><input type="submit" value="提交" />
				</td>
			</tr>
		</table>

	</form>
</body>

</html>