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>
        <load-on-startup>1</load-on-startup>
    </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>
     <!-- 解析html文件 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.html</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>

 

 

链接: https://pan.baidu.com/s/1u7skve0sC4dIaDncgBIXqg

 

 

 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值