您的位置:首页 > 编程语言 > Java开发

浅谈spring boot与web前后端分离

2017-12-27 13:48 1096 查看

      浅谈spring boot与web前后端分离           

              从J2EE的开发到如今,所有java开发人员没有人不知道Spring这个一站式框架。再入行之前,听提前实习的同学说过,java在开发后台的过中,代码量繁琐,配置文件多,一些其他脚本语言几行就能搞定的东西,java给写几十行。在spring的1.0时代,全部都是XML配置的Bean,到了spring的2.0时代,官方给出了注解方式的声明Bean(@Component,@Service),到了3.0和4.0,也就是我们现在的时代,程序员们普遍达成了一致,与业务逻辑相关的用声明式Bean,与基础配置有关的用XML(数据源等配置)。

         可是随着项目需求的不断变更,业务逻辑的与众不同,越来越多的配置文件,低下的开发效率,这越来越让java开发的缺点体现出来,正当我们都要放弃java的时候,在2014年4月,Spring项目团队提出了“习惯优于配置”的Spring Boot框架,这也让java开发,重获新生。

         本人入行不到3个月,大学前几年也没怎么认真学习,前几年敲过的代码量都没有我现在一个礼拜多,可能以下的理解也较为片面,主要目的为了记录自己的学习经历,和给一些跟我一样,还在Spring Boot初学阶段人的分享。

        个人理解Spring Boot就是把Spring和Spring MVC ,在原有的基础上,重新进行封装,把原有的Tomcat,Jetty也一同封装进去,这样我们无需再以war包的形式进行部署。所谓的注解也都是基于Spring的注解和自己新声明的一些注解。所以说学好Spring和Spring MVC这两个框架尤为重要。Spring Boot推崇习惯优于配置这个理念,但也不能在项目中完全否定配置文件的存在,Spring Boot 更推荐用java的配置文件方式(@Bean
,@Configuration)来配置。所以说应用了Spring Boot后极大了提高了开发效率,减少了开发量。

       Spring Boot也不推荐与jsp文件开发,因为jsp文件当中嵌入了大量的java代码,这让开发人员维护和需求变更的时候很棘手,有一些公司的前端开发人员也不太了解后台的东西,也容易改错,这导致开发效率极低。这还不是最致命的,最关键的是在几年前,大多数的web项目都是拿jsp开发,因为数据流量也不大。但随着互联网大数据时代的来临,前后端耦合的项目已经不能满足我们的需求,传统的方式是把静态资源(css,js,图片)和动态资源一同打成war包部署到服务器,可当大量数据请求服务器的时候,服务器压力也会非常大,本来jsp第一次运行的时候就会被转换成Servlet去运行,当服务器接收到大量请求的时候,卡顿更加严重,用户体验极差,所以说前后端分离,不仅仅是Spring
Boot的推崇,更是时代的要求。

      说到前后端分离,不是说你后台程序员只会java,相反我认为作为后台的我们,更应该懂得前端的知识,如果你是后台中最懂前端的,你的薪资水平又会如何,java这套体系已经成型很多年了,人才市场已经要饱和了,你会java别人也会,公司凭什么给你高薪?可能作为一个刚入行的小白,想法太片面,但我认为这就是现实。

     在最近刚开始学Spring Boot的时候,我经常会有以下疑惑,在告别了传统的jsp后,我们要在前台页面展示给客户,后台有用的数据信息怎么办?后来自己看了一些公司的项目后,才了解到了AJAX这门技术的重要性,话不多说,以下是一个简单的Spring Boot用户登录验证的简单Demo,分享给初学者学习。

         项目结构图如下:

 


    搭建环境:Eclipse4.4.1(提前搭好MAVEN环境)  MYSQL5.5  

    第一步:去http://start.spring.io/,下载好相应的项目依赖。



  第二步把下载好的项目导入eclipse,并根据项目结构图编写文件,进行coding

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.panhai</groupId>
<artifactId>SpringbootMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringbootMybatis</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 这是阿里巴巴的数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</p
4000
lugins>
</build>

</project>
2.User.java
package com.panhai.SpringbootMybatis.Domain;

import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class User {
private String username;

private Date birthday;

private Integer id;

private String sex;

private String address;

private String password;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
}
3.UserMapper.java
package com.panhai.SpringbootMybatis.Dao;

import com.panhai.SpringbootMybatis.Domain.User;

public interface UserMapper {
int insert(User record);

int insertSelective(User record);
User checkLogin(User user);
}
4.UserService.java
package com.panhai.SpringbootMybatis.Service;

import com.panhai.SpringbootMybatis.Domain.User;

public interface UserService {
public User checkLogin(User user);
}
5.UserServiceImpl.java

package com.panhai.SpringbootMybatis.Service.ServiceImpl;

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

import com.panhai.SpringbootMybatis.Dao.UserMapper;
import com.panhai.SpringbootMybatis.Domain.User;
import com.panhai.SpringbootMybatis.Service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;

public User checkLogin(User user) {
// TODO Auto-generated method stub
return userMapper.checkLogin(user);
}

}
6. 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.panhai.SpringbootMybatis.Dao.UserMapper" >

<resultMap id="BaseResultMap" type="com.panhai.SpringbootMybatis.Domain.User" >
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="birthday" property="birthday" jdbcType="DATE" />
<result column="id" property="id" jdbcType="INTEGER" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="address" property="address" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>

<insert id="insert" parameterType="com.panhai.SpringbootMybatis.Domain.User" >
insert into user (username, birthday, id,
sex, address, password
)
values (#{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{id,jdbcType=INTEGER},
#{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
</insert>

<insert id="insertSelective" parameterType="com.panhai.SpringbootMybatis.Domain.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="username != null" >
username,
</if>
<if test="birthday != null" >
birthday,
</if>
<if test="id != null" >
id,
</if>
<if test="sex != null" >
sex,
</if>
<if test="address != null" >
address,
</if>
<if test="password != null" >
password,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="birthday != null" >
#{birthday,jdbcType=DATE},
</if>
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="sex != null" >
#{sex,jdbcType=VARCHAR},
</if>
<if test="address != null" >
#{address,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="checkLogin"    parameterType="com.panhai.SpringbootMybatis.Domain.User"   resultType="com.panhai.SpringbootMybatis.Domain.User"  >
select * from user where username=#{username}  and password=#{password}

</select>

</mapper>
7.application.properties
## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
## Mybatis 配置
mybatis.typeAliasesPackage=com.panhai.SpringbootMybatis.Domain
mybatis.mapperLocations=classpath:mapper/*.xml
8.## 数据源配置

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=1234

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

## Mybatis 配置

mybatis.typeAliasesPackage=com.panhai.SpringbootMybatis.Domain

mybatis.mapperLocations=classpath:mapper/*.xml

9.SpringbootMybatisApplication.java
package com.panhai.SpringbootMybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.panhai.SpringbootMybatis.Dao")
public class SpringbootMybatisApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
10.login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script
src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset="utf-8" />
<title>用户登录系统</title><base target="_blank" />
<style>
*{
padding:0px;
margin:0px;
}
a{color:White}
body{
font-family:Arial, Helvetica, sans-serif;
background:url(http://keleyi.com/keleyi/phtml/divcss/21/images/grass.jpg) no-repeat center;
font-size:13px;
}
img{
border:0;
}
.lg{width:468px; height:468px; margin:100px auto; background:url(http://keleyi.com/keleyi/phtml/divcss/21/images/login_bg.png) no-repeat;}
.lg_top{ height:200px; width:468px;}
.lg_main{width:400px; height:180px; margin:0 25px;}
.lg_m_1{
width:290px;
height:100px;
padding:60px 55px 20px 55px;
}
.ur{
height:37px;
border:0;
color:#666;
width:236px;
margin:4px 28px;
background:url(http://keleyi.com/keleyi/phtml/divcss/21/images/user.png) no-repeat;
padding-left:10px;
font-size:16pt;
font-family:Arial, Helvetica, sans-serif;
}
.pw{
height:37px;
border:0;
color:#666;
width:236px;
margin:4px 28px;
background:url(http://keleyi.com/keleyi/phtml/divcss/21/images/password.png) no-repeat;
padding-left:10px;
font-size:16pt;
font-family:Arial, Helvetica, sans-serif;
}
.bn{width:330px; height:72px; background:url(http://keleyi.com/keleyi/phtml/divcss/21/images/enter.png) no-repeat; border:0; display:block; font-size:18px; color:#FFF; font-family:Arial, Helvetica, sans-serif; font-weight:bolder;}
.lg_foot{
height:80px;
width:330px;
padding: 6px 68px 0 68px;
}
</style>
</head>

<body class="b">
<div class="lg">
<form action="#" method="POST">
<div class="lg_top"></div>
<div class="lg_main">
<div class="lg_m_1">

<input name="username"  id="username"  class="ur" />
<input name="password"   id="password"   type="password"  class="pw" />

</div>
</div>
<div class="lg_foot">
<input type="button" value="点这里登录" class="bn"  id="bn"  /></div>
</form>
</div>
<div style="text-align:center;">
<p><a href="http://keleyi.com/">首页</a> <a href="http://keleyi.com/keleyi/phtml/">特效库</a> <a href="http://keleyi.com/a/bjae/6asac24d.htm">原文</a></p>
</div>
</body>
<script type="text/javascript">

$("#bn").click(function(){
var username=$("#username").val();
var password=$("#password").val();
console.log(username);
console.log(password);
var error="";
if (username.length=="") {
error+="用户名不能为空";
error+="\n";

}
if (password.length=="") {
error+="密码不能为空";
error+="\n";
}
if (error!="") {
alert(error);
}
else{
/* debugger */
$.ajax({
type:'POST',
/* dataType:'json', */
dataType:'json',
url:'http://localhost:8080/panhai/login',
contentType:'application/json;charset=UTF-8',

data:JSON.stringify({"username":username,"password":password}),

success:function(data){//返回json结果

//username==data.username&&password==data.password
if(username==data.username&&password==data.password){
//alert("用户名密码错误");//JSON.stringify(data)
window.location.href="success.html?username="+data.username;
//data.username
}

else {
//debugger;
alert("用户名密码,错误");
}

}

});

/* console.log({"username":username,"password":password}); */

}

});

</script>

</html>
11.success.html
<!DOCTYPE html>
<html>
<head>
<script
src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
成功登陆

<marquee direction="left" behavior="alternate"><span id="name"></span> ,磐海数据欢迎您!
</marquee>
</body>
<script type="text/javascript">

$(function(){

var url=window.location.href;
var records=url.split("=");

//var obj=eval('(' + records[1] + ')');
document.getElementById("name").innerHTML= records[1];;
//          $("#name").html(obj.username) ;

// console.log(records);
// alert( records[1]);
}

)

</script>
<!-- <script type="text/javascript">
$(function(){
$.ajax({
type:'GET',
/* dataType:'json', */
dataType:'text',
url:'http://localhost:8080/panhai/d',
contentType:'application/json;charset=UTF-8',

/* data:JSON.stringify({"username":username,"password":password}), */

success:function(data){//返回json结果

alert(data);

}

});
})
</script> -->
</html>
第三步

3.1 登录页面展示:



3.2 成功页面展示:



3.3 错误信息提示:


      以上就是一个简单的Spring  Boot结合AJAX用户验证的简单实例,适合初学者学习,也是对于自己学习经历的记录,也是对于自己年轻时候的一个念象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: