idea搭建ssm+maven項目


項目結構如下


0. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <display-name>ssm</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>

    <!-- 配置靜態資源文件路徑 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

    <!-- spring mvc 請求響應 -->
    <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:/spring/spring-*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
    <!-- 字符過濾,防止post請求亂碼 -->
    <filter>
        <filter-name>SpringCharacterEncodingFilter</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>SpringCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

1. spring-mvc

<?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:util="http://www.springframework.org/schema/util"
       xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 開始組件掃描 -->
    <context:component-scan base-package="com.qmylzx.ssm"></context:component-scan>

    <!-- 啓用註解驅動 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 處理靜態資源 -->
    <mvc:default-servlet-handler/>

    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.qmylzx.ssm.intercept.LTIntercept"/> <!--禁止直接訪問後臺(沒有登陸的情況下)-->
        </mvc:interceptor>
    </mvc:interceptors>
    <!--全局異常處理器-->
    <bean class="com.qmylzx.ssm.exception.MyExceptionResolver"></bean>
</beans>
2.spring-mybatis
<?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:util="http://www.springframework.org/schema/util"
       xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <util:properties id="config" location="classpath:/spring/db.properties"></util:properties>
    <!-- 配置數據庫連接參數及連接池 -->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="#{config.driver}" />
        <property name="url" value="#{config.url}" />
        <property name="username" value="#{config.username}" />
        <property name="password" value="#{config.password}" />
    </bean>

    <!-- spring集成mybatis,不再需要mybatis的配置文件 -->
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入連接池 -->
        <property name="dataSource" ref="ds"></property>
        <!-- 映射文件的位置 -->
        <property name="mapperLocations" value="classpath:/sql/*.xml"></property>
    </bean>

    <!-- 該bean負責調用SqlSession的getMapper函數 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qmylzx.ssm.dao" />
    </bean>

    <!-- 開啓事務註解驅動 -->
    <tx:annotation-driven />
    <!-- (事務管理) -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds" />
    </bean>
</beans>

3.db.properties  //尾部不能有空格

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://數據庫ip:端口/數據庫名?useUnicode=true&characterEncoding=utf-8
username=帳號
password=密碼

4.sql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.qmylzx.ssm.dao.IUserInfoDAO">
	
	<!-- 建立sql查詢結果字段與實體屬性的映射關係 -->
	<resultMap id="UserInfoMap" type="com.qmylzx.ssm.view.UserInfo">
		<result column="id" property="id" />
		<result column="login_name" property="loginName" />
		<result column="pass_word" property="passWord" />
	</resultMap>
	
	<!-- 校驗用戶 -->
	<select id="selectUser" resultMap="UserInfoMap">
		SELECT
			*
		FROM
			user_info
		WHERE
			login_name = #{loginName} 
		AND pass_word = #{passWord}
	</select>
</mapper>
<select id="list" resultMap="UserInfoMap">
	// sql語句
	// 如果返回int、String、hashmap等,需要將resultMap改成:resultType="int"等
</select>

insert

<insert id="insert">
	INSERT INTO type_info
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="sort!=null and sort!=''">sort,</if>
		<if test="name!=null and name!=''">name,</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="sort!=null and sort!=''">#{sort},</if>
		<if test="name!=null and name!=''">#{name},</if>
	</trim>
</insert>

update

<update id="update">
	UPDATE type_info
	<set>
		<if test="sort!=null">sort=#{sort},</if>
		<if test="name!=null">name=#{name},</if>
	</set>
	WHERE id = #{id}
</update>

delete

<delete id="delete">
	DELETE FROM user_info WHERE id = #{id}
</delete>
數組、list循環:需要注意,其中的idArr指的是接口中的參數註解,如果沒寫註解,則數組寫array,list寫list
<delete id="delete">
	DELETE FROM user_info WHERE id IN
	<foreach collection="idArr" index="index" item="item" open="(" separator="," close=")">
		#{item}
	</foreach>
</delete>
子查詢(單參數)
<collection property="type" ofType="ssm.view.TypeInfo"
	column="id" javaType="ssm.view.TypeInfo"
	select="ssm.dao.type_info.ITypeInfoDAO.queryById">
</collection>
子查詢(多參數)
<collection property="teacherList" ofType="ssm.view.record"
	column="{activityId=activity_id, postCode=post_code}" javaType="list"
	select="ssm.dao.post_selection_record.IPostSelectionRecordDAO.queryTeacherList">
</collection>
得到剛剛insert到數據表中的記錄的主鍵值
<insert id="insert">
	INSERT INTO user_info
	<trim prefix="(" suffix=")" suffixOverrides=",">
		<if test="loginName!=null and loginName!=''">login_name,</if>
		<if test="passWord!=null and passWord!=''">pass_word,</if>
		<if test="userType!=null and userType!=''">user_type,</if>
		<if test="status!=null and status!=''">status,</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		<if test="loginName!=null and loginName!=''">#{loginName},</if>
		<if test="passWord!=null and passWord!=''">#{passWord},</if>
		<if test="userType!=null and userType!=''">#{userType},</if>
		<if test="status!=null and status!=''">#{status},</if>
	</trim>
	<selectKey keyProperty="id" order="AFTER" resultType="String">
		<!-- 得到剛insert到數據表中的記錄的主鍵值,只適用於自增主鍵 -->
		SELECT IDENT_CURRENT('user_info') AS id
	</selectKey>
</insert>


批量插入
int count = 0;
int batchCount = 50;
List<EvaluationResultScore> evaluationResultScoreList = new ArrayList<EvaluationResultScore>();

for (int i=0; i<length; i++) {
	EvaluationResultScore evaluationResultScore = new EvaluationResultScore();
	evaluationResultScore.setResultId(resultId);
	evaluationResultScore.setItemId(itemId);
	evaluationResultScore.setOptionName(optionName);
	evaluationResultScore.setOptionScore(optionScore);
	evaluationResultScore.setRealScore(realScore);
	
	evaluationResultScoreList.add(evaluationResultScore);
	count++;

	if ((count%batchCount)==0) {
		iEvaluationResultScoreDAO.insertBatch(evaluationResultScoreList);
		evaluationResultScoreList.clear();
	}
}

if (evaluationResultScoreList!=null && evaluationResultScoreList.size()>0) {
	iEvaluationResultScoreDAO.insertBatch(evaluationResultScoreList);
	evaluationResultScoreList.clear();
}
sql文寫法
<insert id="insertBatch">
	INSERT INTO evaluation_result_score (result_id, item_id, option_name, option_score, real_score)
	VALUES
	<foreach collection="list" item="item" index="index" separator=",">
		(#{item.resultId}, #{item.itemId}, #{item.optionName}, #{item.optionScore}, #{item.realScore})
	</foreach>
</insert>

UserInfoAction.java

package com.qmylzx.ssm.action;

import com.qmylzx.ssm.exception.MyException;
import com.qmylzx.ssm.service.UserInfoService;
import com.qmylzx.ssm.view.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.util.StringUtils;
import com.qmylzx.ssm.view.UserInfo;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("admin")
public class UserInfoAction {
    /* 在類下添加這句話log4j使用方法
       import org.apache.log4j.Logger;
        private Logger log = Logger.getLogger(this.getClass());
        log.debug("登陸開始");
        log.info("登陸開始");
        log.error("登陸開始");
  */
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 首頁跳轉登錄頁面
     */
    @RequestMapping("index.action") //跳轉至管理員頁面
    public String index() {
        return "admin/index";
    }
    @RequestMapping("login.action") //跳轉至管理員登陸
    public String login() {
        return "admin/login";
    }

    @RequestMapping("login.json")
    @ResponseBody
    public Result login2(ModelMap map, HttpServletRequest request) throws MyException {
        //1 獲取參數
        String loginName = request.getParameter("login_name");
        String passWord = request.getParameter("pass_word");
        //2 校驗參數
        if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(passWord)){
            throw  new MyException("用戶名或密碼不能爲空");
        }
        UserInfo userInfo = userInfoService.selectUser(loginName,passWord);
        if (userInfo==null){
            //用戶名密碼不正確
            throw  new MyException("用戶名或密碼錯誤");
        }
        //3設置session
        request.getSession().setAttribute("userInfo",userInfo);
        return Result.success();
    }
    @RequestMapping("login_out.action")
    public  String login_out(HttpSession session){
        session.invalidate();
        return "admin/login";
    }

}
IUserInfoDAO.java
package com.qmylzx.ssm.dao;
import com.qmylzx.ssm.view.UserInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;


@Repository
public interface IUserInfoDAO {

    /**
     * 校驗用戶
     * @param loginName 登錄名
     * @param passWord 登錄密碼
     * @return
     */
    UserInfo selectUser(@Param("loginName") String loginName, @Param("passWord") String passWord);

}
UserInfoService.java
package com.qmylzx.ssm.service;


import com.qmylzx.ssm.dao.IUserInfoDAO;
import com.qmylzx.ssm.view.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("UserInfoService")
public class UserInfoService {
    @Autowired
    private IUserInfoDAO iUserInfoDAO;

    /**
     * 校驗用戶登錄
     * @param loginName 登錄名
     * @param passWord 登錄密碼
     * @return
     */
    public UserInfo selectUser(String loginName, String passWord) {

        return iUserInfoDAO.selectUser(loginName, passWord);
    }

}
UserInfo.java
package com.qmylzx.ssm.view;

public class UserInfo {
    private String id;	// 主鍵
    private String loginName;	// 登錄名
    private String passWord;	// 登錄密碼

    public String getId() {
        return id;
    }

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

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}
攔截器
package com.qmylzx.ssm.intercept;


import com.qmylzx.ssm.view.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class LTIntercept implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //1 獲取請求的地址
        String url = httpServletRequest.getRequestURI();
        //2 對特殊地址放行
        if (url.indexOf("login") >= 0) {
            return true;
        }
        //3 判定session ,存在可以登陸後臺
        UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo");
        if (userInfo != null) {
            return true;//身份驗證,放行
        }
        //4 執行到這裏表示用戶需要身份驗證跳轉到登陸頁面
        httpServletRequest.getRequestDispatcher("/WEB-INF/page/admin/login.jsp").forward(httpServletRequest,httpServletResponse);
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

exception

package com.qmylzx.ssm.exception;



/*
    全局異常處理
*/
public class MyException extends Exception{
    private static final long serialVersionUID = 1L;
    // 異常信息
    public String message;

    public MyException(String message){
        super(message);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
package com.qmylzx.ssm.exception;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;

import com.google.gson.Gson;

public class MyExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        //1 打印異常信息
        e.printStackTrace();
        //定義一個錯誤信息
        String message = "系統繁忙,請稍候再試!";
        //判斷該錯誤是否是預期的錯誤

        if (e instanceof MyException) {
            message = ((MyException) e).getMessage();
        }
        /* 2 判斷請求類型 */
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody != null) {
            //2.1 如果是json請求,則返回json數據

            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("code", "999999");
            responseMap.put("message", message);
            String json = new Gson().toJson(responseMap);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            try {
                httpServletResponse.getWriter().write(json);
                httpServletResponse.getWriter().flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            // 返回一個空的ModelAndView表示已經手動生成響應
            return new ModelAndView();
        }
        //2.2如果是action請求 則跳轉到錯誤頁面
        // 頁面轉發(跳轉至錯誤頁面)
        ModelAndView modelAndView = new ModelAndView();
        //將錯誤信息傳到頁面
        modelAndView.addObject("message", message);
        //指向錯誤頁面
        modelAndView.setViewName("error");

        return modelAndView;


    }
}

ajax //login.json 是一個json請求,在admin中找對應的login.json 方法執行 其中submit爲組件id 提交需要使用按鈕,否則出現bug

<script>
    $("#submit").click(function () {
        if (javaexVerify()) {
            $.ajax({
                url: "${pageContext.request.contextPath}/admin/login.json",
                type: "POST",
                dataType: "json",
                data: $("#login1").serialize(),
                success: function (rtn) {
                    if(rtn.code=="000000"){
                        window.location.href = "${pageContext.request.contextPath}/admin/index.action";
                    }else{
                        alert(rtn.message);
                    }
                }, error: function (rtn) {
                    console.log(rtn);
                }
            });
        }
    });
</script>

用ajax返回的數據類型,在json方法中 參數列表中傳入ModelMap map用map存放數據

在controller中寫法

public String getList(ModelMap map){

List<javabean> list = javabeanService.getList();
map.put("list",list);
return "admin/javabean/list";  //跳轉到頁面然後顯示list的值
}

package com.qmylzx.ssm.view;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
/*
{   "code": "000000",
    "message":"   ",
    "data": { "code": "000000",    "message":"   ",    "data":data }
}
 */
public class Result {
    private String code; //狀態碼 成功000000 失敗999999
    private String message; //錯誤信息
    //返回數據類型,鏈式結構
    private Map<String,Object> data = new HashMap<String, Object>();

    public static Result success(){
        Result result = new Result();
        result.setCode("000000");
        result.setMessage("操作成功");
        return result;
    }

    public static Result error(String string){
        Result result = new Result();
        result.setCode("999999");
        if(StringUtils.isEmpty(string)){
            result.setMessage("操作失敗");
        }
        result.setMessage(string);
        return result;
    }

    public Result add(String key, Object value) {
        this.getData().put(key, value);
        return this;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }
}

ModelMap map 取值

jstl標籤支持
<%@ 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/functions" prefix="fn"%>


嵌套頁面
<c:import url="head.jsp"></c:import>

轉發
<jsp:forward page="portal/index.action"></jsp:forward>


if
<c:if test="${userInfo.type=='admin'}">
	// 執行
</c:if>


if-else
<c:choose>
	<c:when test="${fn:length(list)==0}">
		// 執行
	</c:when>
	<c:otherwise>
		// 執行
	</c:otherwise>
</c:choose>



if-else if-else
<c:choose>
	<c:when test="${userInfo.type=='admin'}">
		// 執行
	</c:when>
	<c:when test="${userInfo.type=='teacher'}">
		// 執行
	</c:when>
	<c:otherwise>
		// 執行
	</c:otherwise>
</c:choose>


遍歷循環 取Map中存放的值

<c:forEach items="${list}" var="entity" varStatus="status" >
	<tr>
		<td>${status.index+1}</td>
		<td>${entity.userName}</td>
		<td>${entity.userCode}</td>
	</tr>
</c:forEach>


項目所需包maven

  <dependencies>
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
     </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.40</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.3.1</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
  </dependencies>

log4j.properties

### Log4j配置 ###
#允許DEBUG級別以上的日誌可以打印到控制檯和寫入日誌文件
log4j.rootLogger=DEBUG,console,file

#-----------------------------------#
#1 定義日誌輸出目的地爲控制檯
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
####可以靈活地指定日誌輸出格式,下面一行是指定具體的格式 ###
#%c: 輸出日誌信息所屬的類目,通常就是所在類的全名
#%m: 輸出代碼中指定的消息,產生的日誌具體信息 
#%n: 輸出一個回車換行符,Windows平臺爲"/r/n",Unix平臺爲"/n"輸出日誌信息換行
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#日誌記錄格式(根據自己喜好更改)
log4j.appender.console.layout.ConversionPattern=%d [%-5p] - %c (%F.%M:%L) - %m%n

#-----------------------------------#
#2 文件大小到達指定尺寸的時候產生一個新的文件 
log4j.appender.file=org.apache.log4j.RollingFileAppender
#日誌文件輸出目錄
log4j.appender.file.File=C\:/Users/Alen/IdeaProjects/logs/log.log
#定義文件最大大小
log4j.appender.file.MaxFileSize=1024kb
#最多生成多少個文件
log4j.appender.file.MaxBackupIndex=20
###輸出日誌信息###
#寫到文件的日誌的最低級別
log4j.appender.file.Threshold=INFO
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#日誌記錄格式(根據自己喜好更改)
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%p] - %c - %F(%L) -%m%n

#-----------------------------------#
#3 mybatis 顯示SQL語句部分
#log4j.logger.com.ibatis = debug
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate =debug
#log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug


分頁的實現

pom.xml

<!-- 引入PageHelper分頁插件 -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.1.2</version>
</dependency>
public String select(ModelMap map, HttpServletRequest request,
                     @RequestParam(value="pageNum", defaultValue="1") int pageNum,
                     @RequestParam(value="pageSize", defaultValue="15") int pageSize) {//學生只能查看本專業的論文

    Student student = (Student) request.getSession().getAttribute("student");

    // pageHelper分頁插件
    // 只需要在查詢之前調用,傳入當前頁碼,以及每一頁顯示多少條
    PageHelper.startPage(pageNum, pageSize);//放在service調用之前
    List<Paper> list = paperService.selectListByMajor(student.getMajor()); //按專業名查詢
    PageInfo<Paper> pageInfo = new PageInfo<Paper>(list);
    map.put("pageInfo", pageInfo);
    return "/student/list";
}

table取元素

<c:forEach items="${pageInfo.list}" var="entity" varStatus="status">

table 下面加

<%--分頁--%>
<div class="page">
    <ul id="page" class="pagination"></ul>
</div>
<script>
    var currentPage = "${pageInfo.pageNum}";
    var pageCount = "${pageInfo.pages}";
    console.log("currentPage"+currentPage);
    console.log("pageCount"+pageCount);
    javaex.page({
        id : "page",
        pageCount : pageCount, // 總頁數
        currentPage : currentPage,// 默認選中第幾頁
        // 返回當前選中的頁數
        callback:function(rtn) {
            //alert(rtn.pageNum);
            searchCurrentPage(rtn.pageNum);
        }
    });
    function  searchCurrentPage(pageNum){
        window.location.href = "select_paper.action?pageNum="+pageNum;
    }
</script>

mybatis-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>
    <!-- 引入分頁插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 分頁參數合理化 -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

spring-mybatis

    <!-- 配置SqlSessionFactoryBean -->
    <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入連接池 -->
        <property name="dataSource" ref="ds"></property>
        <!-- 映射文件的位置 -->
        <property name="mapperLocations" value="classpath:/sql/*.xml"></property>
        <!-- 分頁插件pageHelper -->
        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property> //添加這句
    </bean>







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