1.前言
因为经常换环境,在搭ssm框架的时候老是出错,所以记录一下最近搭建的环境,以供参考。
本文讲解如何使用maven搭建ssm框架,并能用于简单的登录注册。
IDE:IDEA,JDK版本:1.8,数据库:mysql5.7 启动方式:tomcat
首先创建一个简单的数据库表,用于保存用户名和密码,id是主键,如图:
然后创建一个maven的web工程,先上目录结构:
在java中总共有五个包:
- controller:放置控制器,在控制层控制逻辑业务跳转的类文件。
- dao:dao层的接口及其实现类都放在这个包下,其中包含generator逆向生成的类
- bean:存放generator逆向生成实体类
- test:使用逆向时需要的测试类
- service:业务层的接口与实现类放在这个包下,包含具体业务逻辑。
2.maven工程导入依赖
下面是需要在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.xk</groupId> <artifactId>XXXXX</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>xyspgl Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- spring version --> <spring.version>4.3.0.RELEASE</spring.version> <mybatis.version>3.3.0</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring AOP --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <!-- AspectJ Runtime --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.6</version> </dependency> <!-- AspectJ Weaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- mysql-connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- cglib javassist --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.17.1-GA</version> </dependency> <!-- logger --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.0.Final</version> </dependency> <!-- mybatis-spring 整合 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- jstl 标签库 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- file upload part --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <!--分页 --> <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>xyspgl</finalName> <!-- 配置编译依赖工具 --> <plugins> <plugin> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF8</encoding> </configuration> </plugin> </plugins> </build> </project>
3.配置文件
在src/main/resources下新建几个基本的配置文件:
其中,mapper文件夹存放generator逆向生成的mapper配置文件;
db.properties是放置数据库以及数据池的数据:
driver=com.mysql.jdbc.Driver #在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8 url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8 user=root password=root #password=123456 minIdle=50 maxIdle=45 initialSize=5 maxActive=100 maxWait=100 removeAbandonedTimeout=180 removeAbandoned=true timeBetweenEvictionRunsMillis=60000 testWhileIdle=true testOnBorrow=false testOnReturn=false
log4j.properties是日志的相关配置:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
ApplicationContext.xml是Spring的配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!--注解扫描--> <context:component-scan base-package="itle.service"></context:component-scan> <!--数据源连接池--> <context:property-placeholder location="classpath:db.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${driver}" p:url="${url}" p:username="${user}" p:password="${password}" p:minIdle="${minIdle}" p:maxIdle="${maxIdle}" p:initialSize="${initialSize}" p:maxActive="${maxActive}" p:maxWait="${maxWait}" p:removeAbandoned="${removeAbandoned}" p:removeAbandonedTimeout="${removeAbandonedTimeout}" p:testOnBorrow="${testOnBorrow}" p:testOnReturn="${testOnReturn}" p:validationQuery="select 1" p:testWhileIdle="${testWhileIdle}" p:numTestsPerEvictionRun="${maxActive}" p:timeBetweenEvictionRunsMillis="${timeBetweenEvictionRunsMillis}"> </bean> <!--sql的映射文件配置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:typeAliasesPackage="itle.bean" p:mapperLocations="classpath:mapper/UserMapper.xml"></bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="itle.dao"></bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"> </bean> <!-- 事务注解的支持 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
mybatis-config.xml是mybatis的配置文件:
<?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.PageHelper"> <property name="pageSizeZero" value="true"/> <property name="reasonable" value="true"/></plugin> </plugins> </configuration>
SpringMvc.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- @Controller注解扫描 --> <context:component-scan base-package="itle.controller"></context:component-scan> <!-- 注解驱动: 替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 --> <mvc:annotation-driven ></mvc:annotation-driven> <!-- 配置视图解析器 作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称 --> <!--配多视图解析器 --> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="mediaTypes"> <map> <entry key="html" value="text/html;charset=UTF-8"></entry> <entry key="json" value="application/json;charset=UTF-8"></entry> <entry key="xml" value="application/xml;charset=UTF-8"></entry> </map> </property> <property name="defaultContentType" value="text/html"></property> </bean> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="contentNegotiationManager" ref="contentNegotiationManager"></property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:suffix=".jsp" p:prefix="/WEB-INF/jsp/"></bean> </list> </property> </bean> </beans>
接下来是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" id="WebApp_ID" version="2.5"> <display-name>ssm3</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> <!-- 加载spring容器 --> <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> <!-- springmvc前端控制器 --> <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:SpringMvc.xml</param-value> </init-param> <!-- 在tomcat启动的时候就加载这个servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!--编码设置--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
到此,ssm的环境基本算是搭建成功,接下来是要编写java实体代码。
4.Genarator自动构建代码
首先是genarator.xml文件,用于逆向自动生成dao和bean以及mapper的映射文件,需要改动路径的部分都用注释标明,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root" password="root"> </jdbcConnection> <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg" password="yycg"> </jdbcConnection> --> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:指定生成PO类的位置 --> <!--改#####--> <javaModelGenerator targetPackage="itle.bean" targetProject=".srcmainjava"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:指定sql文件mapper映射文件生成的位置 --> <!--改#####--> <sqlMapGenerator targetPackage="mapper" targetProject=".srcmain esources"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:指定dao接口m生成的位置 --> <!--改#####--> <javaClientGenerator type="XMLMAPPER" targetPackage="itle.dao" targetProject=".srcmainjava"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 --> <!-- <table tableName="items"></table> --> <table tableName="user"></table> <!--改#####--> <!-- <table tableName="orderdetail"></table> --> <!-- <table tableName="user"></table> --> <!-- <table schema="" tableName="sys_user"></table> <table schema="" tableName="sys_role"></table> <table schema="" tableName="sys_permission"></table> <table schema="" tableName="sys_user_role"></table> <table schema="" tableName="sys_role_permission"></table> --> <!-- 有些表的字段需要指定java类型 <table schema="" tableName=""> <columnOverride column="" javaType="" /> </table> --> </context> </generatorConfiguration>
配置genarator.xml之后要编写测试类编译生成相关配置类,在itle/test中新建一个类StartServer
import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; //逆向生成映射文件 public class StartServer { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("src\main\resources\genarator.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } public static void main(String[] args) throws Exception { try { StartServer startServer = new StartServer(); startServer.generator(); } catch (Exception e) { e.printStackTrace(); } }
运行这段代码,刷新项目,会dao、bean、mapper三个包中生成相应类,所以这3个包我们是不需要去管的。
5.编写业务层
在service包下新建一个接口 IUserService
import java.util.List; import itle.bean.User; public interface IUserService { public boolean findUserByNameAndPwd(User user) throws Exception; public boolean register(User user) throws Exception; }
再新建一个相应的实现类 UserServiceImpl
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import itle.dao.UserMapper; import itle.bean.User; import itle.bean.UserExample; @Service public class UserServiceImpl implements IUserService { @Autowired private UserMapper userMapper; //根据对象查询 public boolean findUserByNameAndPwd(User user) throws Exception { UserExample example = new UserExample(); List<User> list = userMapper.selectByExample(example); for(User u:list) { if(u.getUsername().equals(user.getUsername())&& u.getUserpwd().equals(user.getUserpwd())) { return true; } } return false; } //插入一个对象的数据 public boolean register(User user) throws Exception { int i = userMapper.insertSelective(user); if(i>0) { return true; } return false; } }
6.编写控制层
在controller包中新建一个类 UserCtroller
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import itle.bean.User; import itle.service.IUserService; @Controller public class UserCtroller { @Autowired private IUserService userService; //登录 @RequestMapping("/login") public String loginqw(User user) throws Exception{ if(userService.findUserByNameAndPwd(user)) { return "success"; } return "login"; } @RequestMapping("/indexReg") public String indexreg() { return "register"; } @RequestMapping("/index") public String indexLog() { return "login"; } //注册 @RequestMapping("/reg") public String register(User user) throws Exception{ if(userService.register(user)) { return "success"; } return "register"; } }
7.jsp页面
需要用于登陆注册的页面
在webapp/WEB-INF下新建一个jsp文件夹,用于管理jsp页面,在文件夹下新建login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登录页面</h2> <form action="login.action" method="post"> 用户名:<input type="text" name="username" /><br/> 密码:<input type="password" name="userpwd" /><br/> <input type="submit" value="登录" /> <a href="indexReg.action">去注册</a> </form> </body> </html>
再新建一个register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>注册页面</h2> <form action="reg.action" method="post"> 用户名:<input type="text" name="username" /><br/> 密码:<input type="password" name="userpwd" /><br/> <input type="submit" value="注册" /> <a href="index.action">去登录</a> </form> </body> </html>
还有一个登陆成功后跳转的主页 success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>成功!</h2> </body> </html>
8.测试
运行成功!截图如下: