Spring-boot使用eclipse搭建项目(二)

时间:2022-05-22 17:00:35

       在上篇博客《Spring-boot使用eclipse搭建项目(一)》中,我们已经搭建好一个spring-boot的初始项目结构,本节我们来丰富我们的项目,完成一个注册登录功能(前端页面使用Bootstrap处理样式)。

        由于在pom.xml中我们引入了thymeleaf模板,所以我们的公共资源不用每个页面都写一遍引入,直接引入模板就可以了,类似于jsp中的include

         首先创建一个base.html用来引入公共资源。

base.html代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment = "commonHead(title)">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title th:text="${title}">spring boot</title>
    
    <meta name="viewport" content="width=device-width, initial-scale=1">
	
	<link rel="stylesheet" th:href="@{http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css}">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script type="text/javascript" th:src="@{http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js}"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script type="text/javascript" th:src="@{http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js}"></script>
    
</head>
<body>
</body>
</html>

           这样其他html页面若需使用到bootstrap、jquery可以引入base.html。

注:我把js放在html代码里面写了,如果想单独引其他js,即放在<head></head>标签外,在引入时和base.html中引入的格式风格一致就可以单独引入js。

register.html代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head  th:include="/common/base :: commonHead('注册')">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title th:text="${title}">注册</title>
</head>
<style>
	html, body {
            height: 100%;
            width: 100%
            overflow: auto;
        }
    .alert-warning{
	    height:30px; 
	    margin-bottom:0;
    }
</style>
<body>
	<form class="form-horizontal" role="form" style="padding:30px 25% 10px; min-width: 800px;">
		 <fieldset>
			<legend>注册</legend>
		</fieldset> 
		<div class="panel panel-primary">
			<div class="panel-heading">账号信息</div>
 	 			<div class="panel-body ">
					<div class="form-group ">
						<label for="username" class="col-sm-3 control-label">账号:</label>
						<div class="col-sm-5">
							<input type="text" class="form-control" id="username" onblur="checkuserName()" placeholder="字母开头,6-16位字母和数字组成"/>
						</div>
							<div id="warn1" class="alert alert-warning col-sm-3" style="padding:6px" ></div>
					</div>
				<div class="form-group">
					<label for="password" class="col-sm-3 control-label">密码:</label>
					<div class="col-sm-5">
						<input type="password" class="form-control" id="password" onblur="checkPwd()" placeholder="6-16位字母和数字组成"/>
					</div>
						<div id="warn2" class="alert alert-warning col-sm-3" style="padding:6px" >
					</div>
				</div>
				<div class="form-group">
					<label for="password_cp" class="col-sm-3 control-label">确认密码:</label>
					<div class="col-sm-5">
						<input type="password" class="form-control" id="password_cp" onblur="checkPwdcp()" placeholder="确认密码"/>
					</div>
						<div id="warn3" class="alert alert-warning col-sm-3" style="padding:6px" >
					</div>
				</div>
			</div>
		</div>
		
		<div class="form-group">
			<div style="text-align:center;">
				<button type="button" class="btn btn-warning" style="width:150px" onclick="resets();">重置</button>
				     
				<button type="button" id="registers" class="btn btn-success" style="width:150px" onclick="register();">立即注册</button>
			</div>
		</div>
	</form>
	
</body>
<script type="text/javascript">
/*<![CDATA[*/ 
var basePath = [[@{/}]]; //获取项目根路径
/*]]>*/  
$(function(){
	$('.alert-warning').hide();
});

function checkuserName(){
	$('.alert').hide();
	var userName = $.trim($('#username').val());
	var regCode=/^[a-zA-Z][a-zA-Z0-9]{5,15}$/;
	if(userName == ''){
		$('#warn1').html('登录名不能为空!');
		$('#warn1').show();
		return;
	}
	if(!regCode.test(userName)){
		$('#warn1').html('格式错误!英文字母和数字组成的6-16位字符,以字母开头!');
		$('#warn1').show();
		return;
	}
}


function checkPwd(){
	$('.alert-warning').hide();
	var password = $.trim($('#password').val());
	var regPwd=/^[a-zA-Z0-9]{6,16}$/;
	if(password == ''){
		$('#warn2').html('密码不能为空!');
		$('#warn2').show();
		return;
	}
	if(!regPwd.test(password)){
		$('#warn2').html('格式错误!英文字母和数字组成的6-16位字符!');
		$('#warn2').show();
		return;
	}
}

function checkPwdcp(){
	$('.alert-warning').hide();
	var password = $.trim($('#password').val());
	var password_cp = $.trim($('#password_cp').val());
	if(password_cp == ''){
		$('#warn3').html('确认密码不能为空!');
		$('#warn3').show();
		return;
	}
	if(password != password_cp){
		$('#warn3').html('前后密码不一致!');
		$('#warn3').show();
		return;
	}
}


function register(){
	$('.alert-warning').hide();
	var userName = $.trim($('#username').val());
	var password = $.trim($('#password').val());
	var password_cp = $.trim($('#password_cp').val());
	
	var regCode=/^[a-zA-Z][a-zA-Z0-9]{5,15}$/;
	var regPwd=/^[a-zA-Z0-9]{6,16}$/;
	
	if(userName == ''){
		alert('登录名不能为空!');
		return;
	}
	if(!regCode.test(userName)){
		alert('格式错误!英文字母和数字组成的6-16位字符,以字母开头!');
		return;
	}
	if(password == ''){
		alert('密码不能为空!');
		return;
	}
	if(!regPwd.test(password)){
		alert('格式错误!英文字母和数字组成的6-16位字符!');
		return;
	}
	if(password_cp == ''){
		alert('确认密码不能为空!');
		return;
	}
	if(!regPwd.test(password_cp)){
		alert('格式错误!英文字母和数字组成的6-16位字符!');
		return;
	}
	if(password != password_cp){
		alert('前后密码不一致!');
		return;
	}
	$.ajax({
		type:'POST',
		contentType: 'application/x-www-form-urlencoded',
		url: basePath + '/login/register',
		data:{
			user_name:userName,
			pass_word:password
		},
		dataType:'json',
		success:function(returnData){
			 if(returnData){
				 $('#message').html('');
				 if(returnData == "400"){
					 alert('登录名重复!'); 
				 }else if(returnData == "500"){
					 alert('注册异常!'); 
				 }else if(returnData == "200"){
					 resets();
					 alert('注册成功!'); 
					 window.setTimeout('toLoginPage()', 800);
				 }
			 }
		},
		error:function(request){
			return false;
		}
	}); 
	
}
function toLoginPage(){
	location.href=basePath+'login/loginPage';
}

function resets(){
	$('.alert-warning').hide();
	$('#username').val('');
	$('#password').val('');
	$('#password_cp').val('');
}
  
</script>
</html>

login.html代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head  th:include="/common/base :: commonHead('登录')">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title th:text="${title}">登录</title>
</head>
<style>
.lanren {
	position: fixed;
	left: 50%;
	top: 50%;
	margin-top: -200px;
	margin-left: -530px;
}
</style>
<body>
	<div class="top-content lanren">
		<div class="inner-bg">
			<div class="container">
				<div class="row">
					<div class="col-sm-5 col-sm-offset-3 form-box">
						<div class="form-top">
							<fieldset>
								<legend>登录</legend>
							</fieldset>
						</div>
						<div class="panel panel-primary">
							<div class="panel-heading">请输入</div>
							<div class="panel-body">
								<div class="form-bottom">
									<form role="form" method="post" class="login-form">
										<div class="form-group">
											<label class="control-label" style="width: 15%;"
												for="user_name">账号:</label> <input type="text"
												class="form-control pull-right"
												style="display: inline-block; width: 80%;" name="user_name"
												placeholder="账号...(字母开头,6-16位字母和数字组成)" id="user_name">
										</div>
										<div class="form-group">
											<label class="control-label" style="width: 15%;"
												for="password">密码:</label> <input type="password"
												class="form-control pull-right"
												style="display: inline-block; width: 80%;" name="password"
												placeholder="密码...(6-16位字母和数字组成)" id="password">
										</div>
									</form>
									<div>
										<button type="submit" class="btn btn-info"
											style="width: 150px;" onclick="toRegisterPage();">注册</button>
										<button type="submit" id="login" class="btn btn-success"
											style="width: 150px; float: right;" onclick="login();">登录</button>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
<script type="text/javascript">

/*<![CDATA[*/ 
var basePath = [[@{/}]]; 
/*]]>*/ 
$(function(){
	$(document).keyup(function(event){  
		  if(event.keyCode ==13){  
		    $("#login").trigger("click");  
		  }  
		});  
});

function toRegisterPage(){
	var url = basePath+'login/registerPage';
	location.href=url;
}

function login(){
	var user_name = $('#user_name').val();
	var password = $('#password').val();
	var regCode=/^[a-zA-Z][a-zA-Z0-9]{5,15}$/;
	var regPwd=/^[a-zA-Z0-9]{6,16}$/;
	if(user_name == ''){
		alert('登录名不能为空!'); 
		return;
	}
	if(password == ''){
		alert('密码不能为空!'); 
		return;
	}
	if(!regCode.test(user_name)){
		alert('登录名格式错误!英文字母和数字组成的6-16位字符,以字母开头!'); 
		return;
	}
	if(!regPwd.test(password)){
		alert('密码格式错误!英文字母和数字组成的6-16位字符!'); 
		return;
	}
	$.ajax({
		type:'POST',
		contentType: 'application/x-www-form-urlencoded',
		url: basePath + '/login/userLogin',
		data:{
			user_name:user_name,
			pass_word:password
		},
		dataType:'json',
		success:function(returnData){
			 if(returnData){
				 if(returnData == "500"){
					 alert('账号或密码错误!请检查账号和密码是否正确!'); 
				 }else if(returnData == "200"){
					 alert('登录成功!'); 
					 window.setTimeout('toSuccess()', 800); 
				 }
			 }
		},
		error:function(request){
			return false;
		}
	}); 
}

function toRegisterPage(){
	location.href=basePath+'login/registerPage';
}

function toSuccess(){
	location.href=basePath+'login/success';
}
</script>
</html>

success.html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>登录成功!!</h1>
</body>
</html>

        后台代码:

LoginController.java:

package com.springboottest.web;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springboottest.service.ILoginService;

@Controller
@RequestMapping("/login")
public class LoginController {
  
  @Autowired
  private ILoginService loginService;
  
  /**
   * 跳转到注册页面
   * @return
   */
  @RequestMapping("/registerPage")
  public String registerPage(){
    
    return "register";
  }
  
  /**
   * 注册
   * @param requestMap
   * @return
   */
  @RequestMapping("/register")
  @ResponseBody
  public String register(@RequestParam Map<String,String> requestMap){
    
    return loginService.register(requestMap);
  }
  
  /**
   * 跳转到登录页面
   * @return
   */
  @RequestMapping("/loginPage")
  public String loginPage(){
    
    return "login";
  }
  
  /**
   * 登录
   * @param requestMap
   * @return
   */
  @RequestMapping("/userLogin")
  @ResponseBody
  public String userLogin(@RequestParam Map<String,String> requestMap){
    
    return loginService.login(requestMap);
  }
  
  /**
   * 跳转到成功页面
   * @return
   */
  @RequestMapping("/success")
  public String toSuccess(){
    
    return "success";
  }
  
}

ILoginService.java:

package com.springboottest.service;

import java.util.Map;

public interface ILoginService {

	/**
	 * 注册
	 * @param requestMap
	 * @return
	 */
	public String register(Map<String,String> requestMap);
	
	/**
	 * 登录
	 * @param requestMap
	 * @return
	 */
	public String login(Map<String,String> requestMap);
}

LoginServiceImpl.java:

package com.springboottest.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.springboottest.dao.ILoginDao;
import com.springboottest.model.User;
import com.springboottest.service.ILoginService;

@Service("loginService")
@Transactional
public class LoginServiceImpl implements ILoginService {

  @Autowired
  private ILoginDao loginDao;
  
  @Override
  public String register(Map<String, String> requestMap) {
    String user_name = requestMap.get("user_name");
    String pass_word = requestMap.get("pass_word");
    User user = new User();
    user.setUser_name(user_name);
    user.setPass_word(pass_word);
    try {
      //先校验用户名是否重复
      List<Map<String, Object>> checkResult = loginDao.checkUserName(user);
      if(checkResult!=null && checkResult.size()>0){
        return "400";//用户名重复
      }
      int result = loginDao.register(user);
      if(result>0){
        return "200";//成功
      }
    } catch (Exception e) {
      e.printStackTrace();
      return "500";//异常
    }
    return "500";//异常
  }

  @Override
  public String login(Map<String, String> requestMap) {
    String user_name = requestMap.get("user_name");
    String pass_word = requestMap.get("pass_word");
    User user = new User();
    user.setUser_name(user_name);
    user.setPass_word(pass_word);
    List<User> result = loginDao.login(user);
    if(result != null && result.size() > 0){
      return "200";//登陆成功
    }
    return "500";//登录失败
  }

}

ILoginDao.java:

package com.springboottest.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.springboottest.model.User;

@Mapper
public interface ILoginDao {

	
	/**
	 * 校验用户名是否重复
	 * @param user
	 * @return
	 */
	@Select("SELECT USER_NAME FROM USER WHERE USER_NAME = #{user.user_name}")
	public List<Map<String,Object>> checkUserName(@Param("user") User user);
	
	/**
	 * 注册
	 * @param user
	 * @return
	 */
	@Insert("INSERT INTO USER(user_name,pass_word) VALUES(#{user.user_name},#{user.pass_word})")
	public int register(@Param("user") User user);
	
	
	/**
	 * 登录
	 * @param user
	 * @return
	 */
	@Select("SELECT USER_NAME,PASS_WORD FROM USER WHERE USER_NAME = #{user.user_name} AND PASS_WORD = #{user.pass_word}")
	public List<User> login(@Param("user") User user);
	
}

User.java:

package com.springboottest.model;

public class User {

	private String user_name;
	private String pass_word;
	
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public String getPass_word() {
		return pass_word;
	}
	public void setPass_word(String pass_word) {
		this.pass_word = pass_word;
	}
	@Override
	public String toString() {
		return "User [user_name=" + user_name + ", pass_word=" + pass_word + "]";
	}
	
	
}


       代码里面已实现登录注册的基本功能,页面样式使用bootstrap响应式布局实现,有很多瑕疵,并且在于非chorme浏览器下可能会出现样式问题。有很多改进空间,如果拿去使用需谨慎。


        至此一个基于Spring-boot,应用Bootstrap实现登录注册的项目完毕。