基于SSM框架实现简单的登录注册的示例代码
一、环境配置工程目录
在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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.imooc</groupId> <artifactId>userLogin</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <!-- 使用junit4 用注解方式 --> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 补全项目依赖 --> <!-- 1:日志 java日志:slf4j,log4j,logback,common-logging slf4j 是规范/接口 日志实现:log4j,logback,common-logging 使用:slf4j + logback --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.1</version> </dependency> <!-- 实现slf4j接口并整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!-- 2:数据库相关依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- DAO框架:MyBatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!-- mybatis自身实现的spring整合依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--:3:servlet web相关依赖 --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 4:spring依赖 --> <!-- 1)spring核心依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- 2)spring dao层依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- 3)spring web相关依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <!-- 4)spring test相关依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.0.RELEASE</version> </dependency> </dependencies> <build> <finalName>userLogin</finalName> <plugins> <!-- define the project compile level --> <!-- maven编译用的版本控制,控制jdk的版本不会回跳 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
数据库驱动配置
jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mysystem?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=kongtao
spring-web.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <!-- 配置springMVC --> <!-- 1:开启springMVC注解模式 --> <!-- 简化配置: (1)自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter (2)提供一系列:数据绑定,数字和日期的format @NumberFormat,@DataTimeFormat xml,json默认读写支持 --> <mvc:annotation-driven/> <!-- 2:配置jsp显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 3:扫描web相关的bean --> <context:component-scan base-package="com.sy.controller" /> </beans>
二、具体逻辑实现数据访问对象(DAO接口)
UserDao.java
package com.sy.dao; import org.apache.ibatis.annotations.Param; import com.sy.entity.User; public interface UserDao { /** * 查找用户名和密码 * @param username 登录用户名 * @return */ User findByUsername(String username); /** * 注册用户和密码 */ void registerByUsernameAndPassword(@Param("username")String username, @Param("password")String password); }
UserDao.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.sy.dao.UserDao"> <!-- 目的:为DAO接口方法提供sql语句配置 --> <!-- 查询用户和密码进行登录 --> <select id="findByUsername" resultType="User" parameterType="String"> select * from user where username = #{username} </select> <!--增加用户名和密码进行注册 --> <insert id="registerByUsernameAndPassword"> insert into user (username,password) values (#{username},#{password}) </insert> </mapper>
控制器
UserController.java
package com.sy.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import com.sy.entity.User; import com.sy.service.UserService; @Controller @RequestMapping("/user") //这里用了@SessionAttributes,可以直接把model中的user(也就key)放入其中 //这样保证了session中存在user这个对象 @SessionAttributes("user") public class UserController { @Autowired private UserService userServivce; //正常访问login页面 @RequestMapping("/login") public String login(){ return "login"; } //表单提交过来的路径 @RequestMapping("/checkLogin") public String checkLogin(User user,Model model){ //调用service方法 user = userServivce.checkLogin(user.getUsername(), user.getPassword()); //若有user则添加到model里并且跳转到成功页面 if(user != null){ model.addAttribute("user",user); return "success"; } return "fail"; } //测试超链接跳转到另一个页面是否可以取到session值 @RequestMapping("/anotherpage") public String hrefpage(){ return "anotherpage"; } //注销方法 @RequestMapping("/outLogin") public String outLogin(HttpSession session){ //通过session.invalidata()方法来注销当前的session session.invalidate(); return "login"; } @RequestMapping("/regist") public String regist(){ return "regist"; } @RequestMapping("/doRegist") public String doRegist(User user,Model model){ System.out.println(user.getUsername()); userServivce.Regist(user); return "success"; } }
实体类
package com.sy.entity; public class User { private String id; private String username; private String password; public String getId() { return id; } public void setId(String 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; } }
相关服务
UserService.java (接口)
package com.sy.service; import com.sy.entity.User; //Service层接口 public interface UserService { //检验用户登录 User checkLogin(String username,String password); void Regist(User user); }
UserServiceImpl.java
package com.sy.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sy.dao.UserDao; import com.sy.entity.User; import com.sy.service.UserService; @Service public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; /* * 检验用户登录业务 * */ public User checkLogin(String username, String password) { User user = userDao.findByUsername(username); if(user != null && user.getPassword().equals(password)){ return user; } return null; } @Override public void Regist(User user) { userDao.registerByUsernameAndPassword(user.getUsername(),user.getPassword()); } }
其他配置文件
持久层相关配置文件 sprintg-dao.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置整合mybatis过程 --> <!-- 1:配置数据库相关参数 properties的属性:${url}--> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 2:数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性 --> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false"/> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="1000"/> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- 约定大于配置 --> <!-- 3:配置sqlsessionfactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置mybatis全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 扫描entity包 使用别名 com.sy.entity.User ->User --> <property name="typeAliasesPackage" value="com.sy.entity"/> <!-- 扫描sql配置文件:mapping需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 4:配置扫描Dao接口的包,动态实现Dao接口,注入到Spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlsessionfactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描的Dao接口包 --> <property name="basePackage" value="com.sy.dao"/> </bean> </beans>
spring-service.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.sy.service"/> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库的连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的声明式事务 默认使用注解来管理事务行为 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder --> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="STDOUT" /> </root> </configuration>
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> <!-- 配置全局属性 --> <settings> <!--使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <setting name="useGeneratedKeys" value="true"/> <!-- 使用列别名替换列名 默认:true select name as title from table --> <setting name="useColumnLabel" value="true"/> <!-- 开启驼峰命名转换:Table(create_time) -> Entity(createTime) --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
JSP视图文件
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body background="images/bg1.jpg"> <form action="${pageContext.request.contextPath}/user/checkLogin" method="post"> <table> <tr> <td>用户名:</td> <td><input id="username" name="username" type="text"></td> </tr> <tr> <td>密码:</td> <td><input id="password" name="password" type="password"></td> </tr> <tr > <td><input type="submit" value="登录" ></td> <td><input type="button" value="注册" onclick="window.location.href='/user/regist'"> </td> </tr> </table> </form> </body> </html>
regist.jsp
<%-- Created by IntelliJ IDEA. User: 86265 Date: 2018/1/30 Time: 10:32 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>用户注册页面</title> </head> <body> <h3>注册页面</h3> <hr/> <form action="${pageContext.request.contextPath}/user/doRegist" method="post"> <table border="1px"> <tr height="35px"> <td width="150px">用户名</td> <td width="300px"> <input type="text" name="username" id="username"> </td> </tr> <tr height="35px"> <td>密码</td> <td> <input type="text" name="password" id="password"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" id="regist" value="注册"/> </td> </tr> </table> </form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div> <strong> welcome,${sessionScope.user.username}! </strong> </div> this is success page! <a href="${pageContext.request.contextPath}/user/anotherpage" rel="external nofollow" >点我跳到另一个页面</a> <form action="${pageContext.request.contextPath}/user/login"> <table> <tr> <td><input type="submit" value="退出登录"></td> </tr> </table> </form> </body> </html>
fail.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> u are loser,this is a fail page! </body> </html>
anotherpage.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div> <strong> ${sessionScope.user.username}!!!!! </strong> </div> <form action="user/outLogin"> <table> <tr> <td><input type="submit" value="退出登录" ></td> </tr> </table> </form> </body> </html>
三、运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)