首页 > 代码库 > SSM(maven)项目搭建全过程+实现用户登录功能
SSM(maven)项目搭建全过程+实现用户登录功能
项目创建之前确保eclipse中已经配置好了jdk,tomcat,maven如果没有配置下面有配置教程的链接
eclipse中配置jdk的教程url:
配置tomcat的教程url:
配置maven的教程url:
一,创建maven项目
1,新建一个maven项目
2,点击Next后进入下个页面直接点击Next,进入到下面这个页面
3,我们选择最后单词为webapp的这个选项选中后点击Next,进入到下面的这个页面
此处的Group Id代表的是项目的包路径,
Artifact Id代表的是项目的名称
Version 代表版本号
Package代表生成的包名
点击完成我们的项目就算搭建好了,下面我们需要对项目做一些配置
4,配置项目的jdk,Tomcat,
右键单击项目名称选择Build path ==>Configure Build path进入到如下选项
我们将原有的jre Remove掉,然后 Add Library==>JRE System Library==>Next==>Alternate JRE==>Finish ==>Apply
jre配置完成,开始配置Tomcat,前面几步跟配置jdk是一样的,
Build path ==>Configure Build path==>Add Library==>Server Runtime
选择自己的Tomcat,点击下一步,然后Apply==>OK,
jdk与Tomcat就配置完成了,
5,下面我们还需要做如下的配置,
右击项目,选择Properties==>Maven==>Project Facets
修改dynamic web module的url:http://www.cnblogs.com/2016-10-07/p/7297826.html
我们的maven项目到这就算建好了,下面开始搭建SSM框架,
二,搭建SSM框架
1,在src/main/resources目录下创建SSM项目所需要的xml文件和properties文件
jdbc.properties(连接数据的配置文件)
driver=com.mysql.jdbc.Driver #数据库的路径 url=jdbc:mysql://localhost:3306/maven username=root password=root #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
logj.properties(日志的配置文件)
#log的输出级别 log4j.rootLogger=WARN, Console, RollingFile #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #RollingFile log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender #文件的输出目录 log4j.appender.RollingFile.File=/var/log/ssm_maven.log log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #Hibernate level #log4j.logger.org.hibernate=ERROR log4j.logger.org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory=ERROR log4j.logger.org.hibernate.search.impl.ConfigContext=ERROR log4j.logger.net.sf.ehcache.config.CacheConfiguration=ERROR #Project defalult level #log4j.logger.com.thinkgem.jeesite=DEBUG log4j.logger.com.maven=DEBUG
spring-tx.xml(Spring的事务管理器配置文件)
<?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" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!--事务管理 --> <!--注意事务管理是spring的而不是springMVC的不要弄混了导致事务不回滚 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启注解方式声明事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
spring-dao.xml(指定包下的所有dao文件都会注入到Spring中)
<?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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--basePackage指定要扫描的包,在此包之下的Dao接口文件都会被Spring搜索到,可以指定多个包,包与包之间用逗号或分号分隔 --> <property name="basePackage" value="http://www.mamicode.com/com.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="http://www.mamicode.com/sqlSessionFactory" /> </bean> </beans>
spring-db.xml(此文件用于获取jdbc.properties连接数据库的配置文件连接数据库,以及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: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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="http://www.mamicode.com/classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="http://www.mamicode.com/${driver}" /> <!--数据库连接的url --> <property name="url" value="http://www.mamicode.com/${url}" /> <!--用户名 --> <property name="username" value="http://www.mamicode.com/${username}" /> <!--密码 --> <property name="password" value="http://www.mamicode.com/${password}" /> <!--初始化连接大小 --> <property name="initialSize" value="http://www.mamicode.com/${initialSize}" /> <!--连接池最大数量 --> <property name="maxActive" value="http://www.mamicode.com/${maxActive}" /> <!--连接池最大空闲 --> <property name="maxIdle" value="http://www.mamicode.com/${maxIdle}" /> <!--连接池最小空闲 --> <property name="minIdle" value="http://www.mamicode.com/${minIdle}" /> <!--获取连接最长等待时间 --> <property name="maxWait" value="http://www.mamicode.com/${maxWait}" /> </bean> <!--spring与mybatis完美整合,不需要mybatis配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件,classpath后需要输入自己的mapper文件的路径 --> <property name="mapperLocations" value="http://www.mamicode.com/classpath:com/ssm/mapper/*.xml"></property> </bean> </beans>
spring-mvc.xml(用于配置SpringMVC)
<?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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--添加注解驱动 --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!--设置使用注解的类所在的包 --> <context:component-scan base-package="com.ssm.controller" /> <!--完成请求和注解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="http://www.mamicode.com/WEB-INF/jsp/" /> <property name="suffix" value="http://www.mamicode.com/.jsp" /> </bean> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="http://www.mamicode.com/utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="http://www.mamicode.com/10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="http://www.mamicode.com/40960" /> </bean> </beans>
applicationContext.xml(将其他几个配置文件整合到这个Spring配置文件中)
<?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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--使用注解方式注入 --> <context:annotation-config /> <!--自动扫描包 base-package为你的代码的路径--> <context:component-scan base-package="com.ssm" /> <!--导入dao配置 --> <import resource="spring-dao.xml" /> <!--导入数据库配置 --> <import resource="spring-db.xml" /> <!--导入事务管理器配置 --> <import resource="spring-tx.xml" /> </beans>
2,项目的pom.xml文件如下(所需的jar已经全部导入)
<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.maven</groupId> <artifactId>ssm_maven</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm_maven Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 用来设置版本号 --> <properties> <srping.version>4.0.2.RELEASE</srping.version> <mybatis.version>3.2.8</mybatis.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <!-- 用到的jar包 --> <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- java ee包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- spring框架包 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${srping.version}</version> </dependency> <!-- spring框架包 end --> <!-- mybatis框架包 start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis框架包 end --> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- jstl标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <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>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 start --> <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.10</version> </dependency> <!-- 上传组件包 end --> </dependencies> <build> <finalName>ssm_maven</finalName> </build> </project>
3,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_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <!-- 加载spring bean --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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 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> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
至此,我们的项目的配置就结束了
三,开始敲代码
1,我们的代码是放在src/main/java这个目录下的,在这个目录下新建如下的包
创建好这几个包
2,在controller这层中创建userController.java
package com.ssm.controller;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ssm.entity.User;
import com.ssm.service.IUserService;
/**
*
* @author liyongqiang
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
/**
* 用户登录
*
* @param req
* @param mv
* @return
*/
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest req, ModelAndView mv) {
Map<String, String> map = new HashMap<String, String>();
map.put("username", req.getParameter("username"));
map.put("password", req.getParameter("password"));
User user = userService.login(map);
if (user != null) {//登录成功进入首页
mv.setViewName("index");
} else {//登录失败回到登录页面
mv.addObject("message", "用户名或密码输入错误,请重新输入");
mv.setViewName("login");
}
return mv;
}
}
3,dao层IUserDao.java
package com.ssm.dao; import java.util.Map; import com.ssm.entity.User; public interface IUserDao { /** * 登录 * * @param map * @return */ public User login(Map<String, String> map); }
4,entity层User.java
package com.ssm.entity; import java.io.Serializable; import java.math.BigDecimal; public class User implements Serializable { private static final long serialVersionUID = 1L; private int id; private String username; private String password; private String email; private String createTime; private String lastLoginTime; private int status; private BigDecimal account; public BigDecimal getAccount() { return account; } public void setAccount(BigDecimal account) { this.account = account; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(String lastLoginTime) { this.lastLoginTime = lastLoginTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public static long getSerialversionuid() { return serialVersionUID; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
5,service层IUserService.java
package com.ssm.service; import java.util.Map; import com.ssm.entity.User; public interface IUserService { /** * 登录 * * @param map * @return */ public User login(Map<String, String> map); }
6,service下的impl中UserServiceImpl.java
package com.ssm.service.impl; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.ssm.dao.IUserDao; import com.ssm.entity.User; import com.ssm.service.IUserService; @Service("UserService") public class UserServiceImpl implements IUserService { @Resource private IUserDao userDao; public User login(Map<String, String> map) { // TODO Auto-generated method stub return userDao.login(map); } }
7,mapper下的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="com.ssm.dao.IUserDao"> <resultMap id="BaseResultMap" type="com.ssm.entity.User"> <result column="id" property="id" jdbcType="INTEGER" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> </resultMap> <!--用户登录 --> <select id="login" parameterType="java.util.Map" resultType="com.ssm.entity.User"> SELECT * FROM u_user WHERE username=#{username,jdbcType=VARCHAR} AND password=#{password,jdbcType=VARCHAR} </select> </mapper>
项目所需的sql文件:
-- ---------------------------- -- Table structure for u_user -- ---------------------------- DROP TABLE IF EXISTS `u_user`; CREATE TABLE `u_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL COMMENT ‘用户昵称‘, `email` varchar(128) DEFAULT NULL COMMENT ‘邮箱|登录帐号‘, `password` varchar(32) DEFAULT NULL COMMENT ‘密码‘, `create_time` datetime DEFAULT NULL COMMENT ‘创建时间‘, `last_login_time` datetime DEFAULT NULL COMMENT ‘最后登录时间‘, `status` bigint(1) DEFAULT ‘1‘ COMMENT ‘1:有效,0:禁止登录‘, `account` decimal(15,2) DEFAULT NULL COMMENT ‘账户‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of u_user -- ---------------------------- INSERT INTO `u_user` VALUES (‘14‘, ‘admin‘, null, ‘123456‘, null, null, ‘1‘, ‘1500.00‘); INSERT INTO `u_user` VALUES (‘16‘, ‘zhangsan‘, null, ‘123456‘, null, null, ‘1‘, ‘3500.00‘);
前端的页面代码在我上传的项目源码中,直接复制过去用就行了,我就不在这写了
项目源码百度云盘链接: https://pan.baidu.com/s/1i4397Hr 密码: ptma
下面我们看下登录页面的效果,项目的访问路径:http://localhost:80/ssm_maven
点击登录后
好了,到这项目就算完成了。
SSM(maven)项目搭建全过程+实现用户登录功能