这篇文章主要介绍了基于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.propertiesjdbc.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.javapackage 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.javapackage 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.javapackage 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="注册" > </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>
三、运行结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家 。
原文链接:http://www.cnblogs.com/ktao/p/8387033.html