ssm整合 柔光的暖阳◎ 2022-07-13 11:19 154阅读 0赞 整合:spring4.2.5+mybatis3.2.8+springMVC+maven 环境:Myeclipse2014+mysql5.5.20+tomcat8+jdk1.7+linux 目标:实现对用户表的简单添加(分别有表单数据提交和json提交)、分页查看和文件上传 源码在github上:[https://github.com/fuckyourdick/myRegisterSystem/tree/master/mavenSSM][https_github.com_fuckyourdick_myRegisterSystem_tree_master_mavenSSM] 效果图: ![这里写图片描述][SouthEast] ![这里写图片描述][SouthEast 1] ![这里写图片描述][SouthEast 2] ![这里写图片描述][SouthEast 3] ![这里写图片描述][SouthEast 4] 项目结构图: ![这里写图片描述][SouthEast 5] ![这里写图片描述][SouthEast 6] 1).创建maven项目,引入所需的jar包 pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hsp.maven</groupId> <artifactId>mavenSSH</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mavenSSH</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.2.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.8</mybatis.version> <!-- mysql驱动版本号 --> <mysql-driver.version>5.1.29</mysql-driver.version> <!-- log4j日志包版本号 --> <slf4j.version>1.7.18</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- 添加jstl依赖 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 添加spring核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- 添加mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- 添加mybatis/spring整合包依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 添加mysql驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-driver.version}</version> </dependency> <!-- 添加数据库连接池依赖 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- 添加fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <!-- 添加日志相关jar包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- 本地环境要求 --> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1-b07</version> </dependency> </dependencies> <build> <finalName>mavenSSM</finalName> </build> </project> 2).建立各种资源文件 <1>jdbc.properties driverClasss=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/maven?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull username=root password=XXXXXXXX #\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570 initialSize=0 #\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570 maxActive=10 #\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2 maxIdle=10 #\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2 minIdle=1 #\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4 maxWait=60000 <2>log4j.properties log4j.rootLogger=INFO,Console,File #控制台日志 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n #普通文件日志 log4j.appender.File=org.apache.log4j.RollingFileAppender log4j.appender.File.File=logs/ssm.log log4j.appender.File.MaxFileSize=10MB #输出日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.File.Threshold=ALL log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n <3>common.properties 该文件暂时不需要添加 <4>spring-mybatis.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="ssm"/> <!-- 第一种方式:加载一个properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 第二种方式:加载多个properties文件 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:common.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> </bean> --> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClasss}"/> <property name="url" value="${jdbcUrl}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="ssm.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> <5>spring-mvc.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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 @Controller--> <context:component-scan base-package="ssm.controller"/> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> <!-- 文件上传配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="UTF-8"/> <!-- 上传文件大小限制为31M,31*1024*1024 --> <property name="maxUploadSize" value="32505856"/> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="4096"/> </bean> </beans> <6>web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app 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_3_0.xsd" version="3.0"> <display-name>ssm</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring内存溢出监听器,比如quartz --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 访问静态文件 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <!-- spring mvc servlet--> <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-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处也可以配置成 *.do 形式 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- session配置 --> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app> 3).建立实体类和对应的实体dao和Mapper.xml文件 <1>先在数据库建立数据库和表(数据库名根据自己的实际而定) ![这里写图片描述][SouthEast 7] <2>ssm.model–User.java package ssm.model; public class User { private Integer id; private String userName; private String userPhone; private String userEmail; private String userPwd; 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 == null ? null : userName.trim(); } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone == null ? null : userPhone.trim(); } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail == null ? null : userEmail.trim(); } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd == null ? null : userPwd.trim(); } } <3>ssm.dao–UserDao.java package ssm.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import ssm.model.User; public interface UserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> getAllUser(); public List<User> selectUserByPage(@Param(value="startPos") Integer startPos,@Param(value="pageSize") Integer pageSize); public int selectUserCount(); } <4>mapping–UserMapper.xml <?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="ssm.dao.UserDao" > <resultMap id="BaseResultMap" type="ssm.model.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="user_phone" property="userPhone" jdbcType="VARCHAR" /> <result column="user_email" property="userEmail" jdbcType="VARCHAR" /> <result column="user_pwd" property="userPwd" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, user_name, user_phone, user_email, user_pwd </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="ssm.model.User" > insert into user (id, user_name, user_phone, user_email, user_pwd) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPhone,jdbcType=VARCHAR}, #{userEmail,jdbcType=VARCHAR}, #{userPwd,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="ssm.model.User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="userName != null" > user_name, </if> <if test="userPhone != null" > user_phone, </if> <if test="userEmail != null" > user_email, </if> <if test="userPwd != null" > user_pwd, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="userPhone != null" > #{userPhone,jdbcType=VARCHAR}, </if> <if test="userEmail != null" > #{userEmail,jdbcType=VARCHAR}, </if> <if test="userPwd != null" > #{userPwd,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="ssm.model.User" > update user <set > <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="userPhone != null" > user_phone = #{userPhone,jdbcType=VARCHAR}, </if> <if test="userEmail != null" > user_email = #{userEmail,jdbcType=VARCHAR}, </if> <if test="userPwd != null" > user_pwd = #{userPwd,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="ssm.model.User" > update user set user_name = #{userName,jdbcType=VARCHAR}, user_phone = #{userPhone,jdbcType=VARCHAR}, user_email = #{userEmail,jdbcType=VARCHAR}, user_pwd = #{userPwd,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="getAllUser" resultMap="BaseResultMap"> SELECT * FROM user </select> <!-- 分页SQL语句 --> <select id="selectUserByPage" resultMap="BaseResultMap"> select * from user limit #{startPos},#{pageSize} </select> <!-- 取得记录的总数 --> <select id="selectUserCount" resultType="java.lang.Integer"> SELECT COUNT(*) FROM user </select> </mapper> 4).建立service层 <1>ssm.service–UserService.java package ssm.service; import ssm.model.User; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserService { /*添加用户*/ void addUser(User user); /*获得所有用户*/ List<User> getAllUsers(); public List<User> getUserByPage(Integer startPos, Integer pageSize); public int getUserCount(); } <2>ssm.service.impl–UserServiceImpl.java package ssm.service.impl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ssm.dao.UserDao; import ssm.model.User; import ssm.service.UserService; import ssm.util.Page; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Service @Transactional(rollbackFor = Exception.class) public class UserServiceImpl implements UserService { @Resource private UserDao userDao; public void addUser(User user) { userDao.insert(user); } public List<User> getAllUsers() { return userDao.getAllUser(); } public List<User> getUserByPage(Integer startPos, Integer pageSize) { return userDao.selectUserByPage(startPos, pageSize); } public int getUserCount() { return userDao.selectUserCount(); } } 5).在工具包添加文件上传和分页的工具类 <1>ssm.util–FileUpload.java package ssm.util; import java.io.File; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.web.multipart.MultipartFile; public class FileUpload { public String upload(HttpServletRequest request, MultipartFile file) { String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); fileName=UUID.randomUUID()+fileName.substring(fileName.indexOf("."),fileName.length()); File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } return fileName; } } <2>ssm.util–Page.java package ssm.util; import java.io.Serializable; public class Page implements Serializable { private static final long serialVersionUID = -3198048449643774660L; private int pageNow = 1; // 当前页数 private int pageSize = 5; // 每页显示记录的条数 private int totalCount; // 总的记录条数 private int totalPageCount; // 总的页数 @SuppressWarnings("unused") private int startPos; // 开始位置,从0开始 @SuppressWarnings("unused") private boolean hasFirst;// 是否有首页 @SuppressWarnings("unused") private boolean hasPre;// 是否有前一页 @SuppressWarnings("unused") private boolean hasNext;// 是否有下一页 @SuppressWarnings("unused") private boolean hasLast;// 是否有最后一页 /** * 通过构造函数 传入 总记录数 和 当前页 * @param totalCount * @param pageNow */ public Page(int totalCount, int pageNow) { this.totalCount = totalCount; this.pageNow = pageNow; } /** * 取得总页数,总页数=总记录数/总页数 * @return */ public int getTotalPageCount() { totalPageCount = getTotalCount() / getPageSize(); return (totalCount % pageSize == 0) ? totalPageCount : totalPageCount + 1; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public int getPageNow() { return pageNow; } public void setPageNow(int pageNow) { this.pageNow = pageNow; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } /** * 取得选择记录的初始位置 * @return */ public int getStartPos() { return (pageNow - 1) * pageSize; } public void setStartPos(int startPos) { this.startPos = startPos; } /** * 是否是第一页 * @return */ public boolean isHasFirst() { return (pageNow == 1) ? false : true; } public void setHasFirst(boolean hasFirst) { this.hasFirst = hasFirst; } /** * 是否有首页 * @return */ public boolean isHasPre() { // 如果有首页就有前一页,因为有首页就不是第一页 return isHasFirst() ? true : false; } public void setHasPre(boolean hasPre) { this.hasPre = hasPre; } /** * 是否有下一页 * @return */ public boolean isHasNext() { // 如果有尾页就有下一页,因为有尾页表明不是最后一页 return isHasLast() ? true : false; } public void setHasNext(boolean hasNext) { this.hasNext = hasNext; } /** * 是否有尾页 * @return */ public boolean isHasLast() { // 如果不是最后一页就有尾页 return (pageNow == getTotalCount()) ? false : true; } public void setHasLast(boolean hasLast) { this.hasLast = hasLast; } } 6).测试 <1>ssm.test–TestService.java package ssm.test; import java.util.List; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import ssm.model.User; import ssm.service.UserService; import ssm.service.impl.UserServiceImpl; public class TestService { ApplicationContext ctx; @Before public void setUp() throws Exception { ctx=new ClassPathXmlApplicationContext("spring-mybatis.xml"); } @Test public void test() { } } 7).写前端界面 <1>WEB-INF–index.jsp ... <a href="user/goUser?flag=templet">模板引擎</a><br> <a href="user/goUser?flag=json">json</a><br> <a href="user/goUser?flag=fileupload">文件上传</a><br> ... <2>WEB-INF–jsp–templet.jsp ... <h1>templet</h1> <form> <table> <tr> <td>username</td> <td> <input type="text" name="userName"> </td> </tr> <tr> <td>userphone</td> <td> <input type="text" name="userPhone"> </td> </tr> <tr> <td>useremail</td> <td> <input type="email" name="userEmail"> </td> </tr> <tr> <td>password</td> <td> <input type="password" name="userPwd"> </td> </tr> <td> </td> <td> <input type="button" value="提交" onclick="addUser()"> </td> </tr> </table> </form> <script type="text/javascript"> //添加用户 function addUser() { var form = document.forms[0]; form.action = "user/addUserTemplet?flag=add"; form.method = "post"; form.submit(); } </script> ... <3>WEB-INF–jsp–json.jsp ... <h1>json</h1> <form id="myform"> <table> <tr> <td>username</td> <td> <input type="text" name="userName" id="userName"> </td> </tr> <tr> <td>userphone</td> <td> <input type="text" name="userPhone" id="userPhone"> </td> </tr> <tr> <td>useremail</td> <td> <input type="email" name="userEmail" id="userEmail"> </td> </tr> <tr> <td>password</td> <td> <input type="password" name="userPwd" id="userPwd"> </td> </tr> <tr> <td> </td> <td> <input type="button" value="提交" id="submit" /> </td> </tr> </table> </form> <script type="text/javascript" src="<%=request.getContextPath() %>/resource/js/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function(){ $('#submit').click(function(){ //选取表单 var form = $('#myform'); //获取表单数据 var name = $("#userName").val(); var phone = $("#userPhone").val(); var email = $("#userEmail").val(); var pwd = $("#userPwd").val(); var user = {userName:name,userPhone:phone,userEmail:email,userPwd:pwd};//拼装成json格式 //发送AJAX请求 $.post('user/addUserJson',user,function(user){ alert(user); }); }); }); </script> ... <4>WEB-INF–jsp–showUser.jsp ... <c:if test="${!empty userList}"> <c:forEach var="user" items="${userList}"> 姓名:${user.userName} 手机号:${user.userPhone} 邮箱:${user.userEmail} <br> </c:forEach> </c:if> <!-- 分页 start --> <div align="left"> <font size="2">共 ${page.totalPageCount} 页</font> <font size="2">第 ${page.pageNow} 页</font> <a href="addUserTemplet?pageNow=1">首页</a> <c:choose> <c:when test="${page.pageNow - 1 > 0}"> <a href="addUserTemplet?pageNow=${page.pageNow - 1}">上一页</a> </c:when> <c:when test="${page.pageNow - 1 <= 0}"> <a href="addUserTemplet?pageNow=1">上一页</a> </c:when> </c:choose> <c:choose> <c:when test="${page.totalPageCount==0}"> <a href="addUserTemplet?pageNow=${page.pageNow}">下一页</a> </c:when> <c:when test="${page.pageNow + 1 < page.totalPageCount}"> <a href="addUserTemplet?pageNow=${page.pageNow + 1}">下一页</a> </c:when> <c:when test="${page.pageNow + 1 >= page.totalPageCount}"> <a href="addUserTemplet?pageNow=${page.totalPageCount}">下一页</a> </c:when> </c:choose> <c:choose> <c:when test="${page.totalPageCount==0}"> <a href="addUserTemplet?pageNow=${page.pageNow}">尾页</a> </c:when> <c:otherwise> <a href="addUserTemplet?pageNow=${page.totalPageCount}">尾页</a> </c:otherwise> </c:choose> </div> <!-- 分页 End --> ... <5>WEB-INF–jsp–fileupload.jsp ... <form action="user/addUserFileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /></form> <h3>${message}</h3> ... 8).由于7)的步骤需要jquery,所以需要引进jquery 在webapp下建立resource目录,在resource下建立js目录,在js目录下存放一个jquery-1.9.1.min.js 9).写控制类处理页面逻辑 <1>ssm.controller–UserController.java package ssm.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import ssm.model.User; import ssm.service.UserService; import ssm.util.FileUpload; import ssm.util.Page; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/user") public class UserController { private Logger log = Logger.getLogger(UserController.class); @Resource private UserService userService; /*json数据交互*/ @RequestMapping("/addUserJson") public void addUserJson(HttpServletRequest request, HttpServletResponse response, User user) throws IOException { log.info("添加用户"); System.out.println("添加用户"+user.getUserName()+","+user.getUserPhone()+","+ user.getUserEmail()+","+user.getUserPwd()+"."); userService.addUser(user); List<User> userList = userService.getAllUsers(); JSONArray jsons = new JSONArray(); for(User a_user : userList) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", a_user.getId()); jsonObject.put("UserName", a_user.getUserName()); jsonObject.put("UserPhone", a_user.getUserPhone()); jsonObject.put("UserEmail", a_user.getUserEmail()); jsonObject.put("UserPwd", a_user.getUserPwd()); jsons.add(jsonObject); } /*设置字符集为'UTF-8'*/ response.setCharacterEncoding("UTF-8"); response.getWriter().print(jsons.toString()) ; } /*模板引擎渲染*/ @RequestMapping("/addUserTemplet") public String addUserTemplet(HttpServletRequest request, Model model, User user){ String flag = request.getParameter("flag"); if(null != flag && flag.equals("add")) { log.info("添加用户"); System.out.println("添加用户"+user.getUserName()+","+user.getUserPhone()+","+ user.getUserEmail()+","+user.getUserPwd()+"."); userService.addUser(user); } Page page = null; String pageNow = request.getParameter("pageNow"); List<User> userList = new ArrayList<User>(); int totalCount = userService.getUserCount(); if (pageNow != null) { page = new Page(totalCount, Integer.parseInt(pageNow)); userList = userService.getUserByPage(page.getStartPos(), page.getPageSize()); } else { page = new Page(totalCount, 1); userList = userService.getUserByPage(page.getStartPos(), page.getPageSize()); } model.addAttribute("userList", userList); model.addAttribute("page", page); return "showUser"; } /*文件上传*/ @RequestMapping("/addUserFileUpload") public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model){ log.info("添加用户"); System.out.println("文件上传"); FileUpload fileUpload = new FileUpload(); String filename = fileUpload.upload(request, file); System.out.println(filename); model.addAttribute("message", "文件上传成功"); return "fileupload"; } @RequestMapping("/goUser") public String goUser(HttpServletRequest request, Model model){ log.info("前往用户界面"); String flag = request.getParameter("flag"); if(null != flag && flag.equals("fileupload")) { return "fileupload"; } if(null != flag && flag.equals("templet")) { return "templet"; } else { return "json"; } } } 10).完 [https_github.com_fuckyourdick_myRegisterSystem_tree_master_mavenSSM]: https://github.com/fuckyourdick/myRegisterSystem/tree/master/mavenSSM [SouthEast]: /images/20220713/0e31bc1e1f0c43ee8ea30ca9678a6ba1.png [SouthEast 1]: /images/20220713/111a4fc11fb142c68e1e54abb25ae129.png [SouthEast 2]: /images/20220713/242c8d4301604402aa3ec894a194c2ec.png [SouthEast 3]: /images/20220713/8f0e3d49f5bd4eb8a084689fb2d45d5d.png [SouthEast 4]: /images/20220713/7a6ad55b5b4b44aaa3771483a4f20d69.png [SouthEast 5]: /images/20220713/8f59ff4149d74f298d0198474c61b1d5.png [SouthEast 6]: /images/20220713/6207533fbd3b4b8a9c296f46db198a90.png [SouthEast 7]: /images/20220713/cad02633b5184c3bb0ec71699ac8c679.png
相关 整合 SSM 1.1 相关依赖 <dependency> <groupId>org.springframework</groupId> <art 不念不忘少年蓝@/ 2022年12月05日 05:21/ 0 赞/ 30 阅读
相关 ssm整合 整合:spring4.2.5+mybatis3.2.8+springMVC+maven 环境:Myeclipse2014+mysql5.5.20+tomcat8+jdk1. 柔光的暖阳◎/ 2022年07月13日 11:19/ 0 赞/ 155 阅读
相关 ssm整合 手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis -------------------- > 我们看招聘信息的时候,经常 古城微笑少年丶/ 2022年07月12日 06:27/ 0 赞/ 44 阅读
相关 ssm整合 手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis -------------------- > 我们看招聘信息的时候,经常 墨蓝/ 2022年07月12日 06:27/ 0 赞/ 72 阅读
相关 ssm整合 在mybatis和spring整合后 , 在把springmvc整合进来 在maven里创建web工程 然后进行mybatis和spring的整合步骤(写在其他博客里) 超、凢脫俗/ 2022年02月12日 10:10/ 0 赞/ 445 阅读
相关 ssm整合 一、注入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mav 快来打我*/ 2022年01月23日 12:57/ 0 赞/ 453 阅读
相关 SSM--SSM整合 一、项目层级结构以及所需JAR包: ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9 傷城~/ 2022年01月21日 23:37/ 0 赞/ 485 阅读
相关 ssm整合 ssm整合 项目目录 ![1560559-20190805161522126-1893405258.png][] jar ![1560559-2019080 桃扇骨/ 2021年10月24日 02:56/ 0 赞/ 497 阅读
相关 SSM整合 前提:jdk,maven,tomcat,STS都已经安装配置好了 spring-4.3.7 + mybatis-3.3.0 + maven3.5+jdk8(这个组合会减少很多 悠悠/ 2021年09月28日 07:58/ 0 赞/ 462 阅读
相关 SSM整合 SSM:Spring+SpringMVC+MyBatis 1、导包 1)、Spring 【aop核心】 com.springsource.net.sf. 男娘i/ 2021年09月23日 16:18/ 0 赞/ 513 阅读
还没有评论,来说两句吧...