【Maven+SSM】如何通過Mybatis寫一箇中文查詢請求及所遇到的問題

前言:

小白筆記。

正文:

一、接入Log4j。

可參考這篇文章。唯一不同的就是依賴jar包通過Maven的工具直接查找。

二、寫一個根據中文名搜索的請求

1、寫一個Service接口

package service;

import java.util.List;

import model.Book;

public interface IBookService {
	Book getBookById(String bookId); 
	List<Book> getBookByName(String bookName);
}

2、上一篇文章,之前通過Mybatis自動生成工具生成的代碼查詢Id,本文基於上文添加。

2.1、dao層添加:

package dao;

import java.util.List;

import model.Book;

public interface BookMapper {
    int deleteByPrimaryKey(String id);

    int insert(Book record);

    int insertSelective(Book record);

    Book selectByPrimaryKey(String id);
    //添加搜姓名
    List<Book> selectByName(String bookName);

    int updateByPrimaryKeySelective(Book record);

    int updateByPrimaryKeyWithBLOBs(Book record);

    int updateByPrimaryKey(Book record);
}
2.2、Mapping層(其中添加註釋的兩處地方爲本次添加)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.BookMapper">
  <resultMap id="BaseResultMap" type="model.Book">
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="chapter_name" jdbcType="VARCHAR" property="chapterName" />
    <result column="owner" jdbcType="VARCHAR" property="owner" />
  </resultMap>
  <resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="model.Book">
    <result column="chapter_content" jdbcType="LONGVARCHAR" property="chapterContent" />
  </resultMap>
  <!--BookList: Book對應Model模塊下Book類 -->
  <resultMap id="BookList" type="model.Book">
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="chapter_name" jdbcType="VARCHAR" property="chapterName" />
    <result column="owner" jdbcType="VARCHAR" property="owner" />
    <result column="chapter_content" jdbcType="LONGVARCHAR" property="chapterContent" />
  </resultMap>
  <sql id="Base_Column_List">
    id, name, chapter_name, owner
  </sql>
  <sql id="Blob_Column_List">
    chapter_content
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="ResultMapWithBLOBs">
    select 
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from biquge
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <!-- 添加搜索姓名對應,其中BookList在上面 -->
  <select id="selectByName" parameterType="java.lang.String" resultMap="BookList">
  	select id, name, chapter_name, owner , chapter_content from biquge where name =  #{name,jdbcType=VARCHAR};
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from biquge
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="model.Book">
    insert into biquge (id, name, chapter_name, 
      owner, chapter_content)
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{chapterName,jdbcType=VARCHAR}, 
      #{owner,jdbcType=VARCHAR}, #{chapterContent,jdbcType=LONGVARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="model.Book">
    insert into biquge
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="chapterName != null">
        chapter_name,
      </if>
      <if test="owner != null">
        owner,
      </if>
      <if test="chapterContent != null">
        chapter_content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="chapterName != null">
        #{chapterName,jdbcType=VARCHAR},
      </if>
      <if test="owner != null">
        #{owner,jdbcType=VARCHAR},
      </if>
      <if test="chapterContent != null">
        #{chapterContent,jdbcType=LONGVARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="model.Book">
    update biquge
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="chapterName != null">
        chapter_name = #{chapterName,jdbcType=VARCHAR},
      </if>
      <if test="owner != null">
        owner = #{owner,jdbcType=VARCHAR},
      </if>
      <if test="chapterContent != null">
        chapter_content = #{chapterContent,jdbcType=LONGVARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="model.Book">
    update biquge
    set name = #{name,jdbcType=VARCHAR},
      chapter_name = #{chapterName,jdbcType=VARCHAR},
      owner = #{owner,jdbcType=VARCHAR},
      chapter_content = #{chapterContent,jdbcType=LONGVARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="model.Book">
    update biquge
    set name = #{name,jdbcType=VARCHAR},
      chapter_name = #{chapterName,jdbcType=VARCHAR},
      owner = #{owner,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>
</mapper>

3、寫接口的實現,其中getBookByName方法中調用上面添加的查詢

package service;



import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import dao.BookMapper;
import model.Book;

@Service("userService")
public class BookServiceImpl implements IBookService{
	@Resource
	private BookMapper bookDao;
	
	public Book getBookById(String bookId) {
		// TODO Auto-generated method stub
		return this.bookDao.selectByPrimaryKey(bookId);
	}
	
	public List<Book> getBookByName(String bookName) {
		return this.bookDao.selectByName(bookName);
	}
}

4、寫一個Controller

@Controller
public class HelloController {
	private static Logger log = LoggerFactory.getLogger(HelloController.class);
	@Resource  
	private IBookService iBookService;
	
	@RequestMapping(value="d.do",produces="text/html;charset=UTF-8")
	public @ResponseBody String viewBook() {
		List<Book> bl = iBookService.getBookByName("大明春色");
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}
}

問題一、根據日誌,發現查詢出來結果爲0條。原因是搜索的中文utf-8。所以在數據庫的連接配置文件上添加如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ebook?useUnicode=true&characterEncoding=UTF-8
username=root
password=haibo1118
initialSize=5
然後就能查出很多條結果了。

5、改造成一個能修改參數的Get請求

覺得我這個固定的搜索名字不像一個請求?那麼我就改改Controller即可。get請求如下:http://localhost:8080/mvnStudy01/e.do?name=大明春色

package controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import model.Book;
import service.IBookService;

@Controller
public class HelloController {
	private static Logger log = LoggerFactory.getLogger(HelloController.class);
	@Resource  
	private IBookService iBookService;
	
	@RequestMapping(value="d.do",produces="text/html;charset=UTF-8")
	public @ResponseBody String viewBook() {
		List<Book> bl = iBookService.getBookByName("大明春色");
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}

	@RequestMapping(value="e.do",produces="text/html;charset=UTF-8")
	public @ResponseBody String viewBookByName(@RequestParam(name="name",defaultValue="大明春色")String name) {
		List<Book> bl = iBookService.getBookByName(name);
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}
}

6、Post請求

package controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import model.Book;
import service.IBookService;

@Controller
public class HelloController {
	private static Logger log = LoggerFactory.getLogger(HelloController.class);
	@Resource  
	private IBookService iBookService;
	
	@RequestMapping(value="d.do",produces="text/html;charset=UTF-8")
	public @ResponseBody String viewBook() {
		List<Book> bl = iBookService.getBookByName("大明春色");
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}

	@RequestMapping(value="e.do",produces="text/html;charset=UTF-8")
	public @ResponseBody String viewBookByName(@RequestParam(name="name",defaultValue="大明春色")String name) {
		List<Book> bl = iBookService.getBookByName(name);
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}
	
	//	Post請求
	@RequestMapping(value="f.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	public @ResponseBody String postBookByName(String name) {
		System.out.println(name.toString());
		List<Book> bl = iBookService.getBookByName(name);
		//添加error日誌
		log.error("----log-----"+bl.toString());
		return "你好";
	}
}
問題二、Post請求時name原本是中文,變成了接收到的是亂碼

大明春色

解決方案:在web.xml中添加如下代碼:

<!-- 配置springMVC編碼過濾器 -->
  <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>
如果添加之後沒效果,重啓服務即可看到Post請求的中文亂碼問題被解決。

7、Rest風格的get請求改造。

Controller代碼如下:即通過PathVariable綁定入參和URL

//	get請求,Rest風格
	@RequestMapping(value="/view/{name}",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	public @ResponseBody String restBookByName(@PathVariable("name")String name) {
		List<Book> bl = iBookService.getBookByName(name);
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好";
	}
請求連接如下:http://localhost:8080/mvnStudy01/view/大明春色

這樣就可以訪問get請求了,當然比之前更加優雅。

PS:此處我對之前web.xml修改了過濾,改成了對所有請求過濾/,web.xml其中的修改部分如下

<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

8、HttpServlet+SpringMVC風格結合:

我就是喜歡這種古樸的風格,那怎麼寫?

//古老風格HttpServlet與SpringMVC的結合
	@RequestMapping(value="/view2",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	public @ResponseBody String httpServletBookByName(HttpServletRequest request) {
		List<Book> bl = iBookService.getBookByName(request.getParameter("name"));
		System.out.println(bl.toString());
		//添加error日誌
		log.error("----log-----");
		return "你好:古老風格HttpServlet與SpringMVC的結合";
	}
請求如下:

http://localhost:8080/mvnStudy01/view2?name=大明春色

完美!到此爲止。



















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章