ConfigRegistCenter.java
package com.example.config;
import com.example.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration //将当前类注入到Spring容器中
@EnableWebMvc
public class ConfigRegistCenter implements WebMvcConfigurer {
//注册拦截器
public void addInterceptors(InterceptorRegistry registry){
// "/" 项目根目录(http://localhost:80/app)
registry.addInterceptor(new JwtInterceptor()).addPathPatterns("/**") //所有资源,包括静态资源
.excludePathPatterns("/login.jsp","/regist.jsp","/customer/login","/customer/regist")
.excludePathPatterns("/product/**")
.excludePathPatterns("/index.jsp","ajax_jquery_demo1.jsp")
.excludePathPatterns("/js/**","/css/**","/images/**");
}
// 静态资源配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/","classpath:webapp/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
MybatisplusConfig.java
package com.example.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //当前是类配置类 @Component
public class MybatisplusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
}
CustomerController.java
package com.example.controller;
import com.example.entity.Customer;
import com.example.entity.LoginCustomer;
import com.example.service.ICustomerService;
import com.example.util.JwtUtil;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* <p>
* 前端控制器
* </p>
*
* @author dd
* @since 2024-04-16
*/
@Controller
@RequestMapping("customer")
public class CustomerController {
@Autowired
private ICustomerService customerService;
@PostMapping("login")
@ResponseBody
public ServerResult login(String custName,String custPassword){
return customerService.login(custName, custPassword);
}
//获得当前登录用户信息
// @GetMapping("info")
// public ServerResult getCustomerInfo(HttpServletRequest request ){
// String token = request.getHeader("token");
// return customerService.getLoginInfoById(token);
// }
@GetMapping("getInfoByToken")
@ResponseBody
public ServerResult getInfoByToken(HttpServletRequest request){
//1. 获得token
String token = request.getHeader("token");
//2. 解析token LoginCustomer
LoginCustomer loginCustomer = JwtUtil.parseToken(token);
//3. 绑定数据
if(loginCustomer !=null)
return ServerResult.getSuccess(loginCustomer);
return ServerResult.getFail("无效的token,没有获得到登录用户的信息 ");
}
// @GetMapping("getInfoByToken")
// @ResponseBody
// public ServerResult getInfoByToken(HttpServletRequest request){
// //1.获得token
// String token = request.getHeader("token");
// //2.解析token LoginCustomer
// LoginCustomer loginCustomer = JwtUtil.parseToken(token);
// //3绑定数据
//
//
//
// }
}
ReceiveAddressJsonController.java
package com.example.controller;
import com.example.entity.LoginCustomer;
import com.example.entity.ReceiveAddress;
import com.example.service.IReceiveAddressService;
import com.example.util.JwtUtil;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
/**
* <p>
* 前端控制器
* </p>
*
* @author dd
* @since 2024-04-10
*/
@RestController //@Controller + @ResponseBody 所有方法都返回json数据
@RequestMapping("/receiveAddressJSon")
public class ReceiveAddressJsonController {
@Autowired
private IReceiveAddressService addressService;
/**
* 根据主键查询
* @param arrId
* @return
*/
@GetMapping("{addrId}") //URL:http://localhost:8080/app/receiveAddress/103
public ServerResult getById(@PathVariable("addrId") Integer arrId){//URL : http://localhost:8080/app/receive-address/103
return addressService.getById(arrId);
}
/**
* 查询所有 //URL : http://localhost:8080/app/receive-address/
* @return
*/
@GetMapping("")
public ServerResult getAll(){
int custId = 1;// 模拟的登录用户id
return addressService.getAll(custId);
}
//@GetMapping("page/{pageNum}")
//public List<ReceiveAddress> getByPage(@PathVariable("pageNum") Integer pageNum){
// return null;
//}
/**
* 新增收件地址
* @param receiveAddress
* @return
*/
@PostMapping
public ServerResult save(ReceiveAddress receiveAddress,HttpServletRequest request){
String token = request.getHeader("token");
LoginCustomer loginCustomer = JwtUtil.parseToken(token);
Integer customerId = loginCustomer.getCustId();
System.out.println("ReceiveAddressJsonController中 save address 解析出来的用户id是:" + customerId);
receiveAddress.setCustId(customerId);
receiveAddress.setStatus(1);
receiveAddress.setVersion(1);
receiveAddress.setCreateTime(LocalDateTime.now());
return addressService.save(receiveAddress);
}
/**
* 删除(修改status=0)
* @param addressId 根据主键删除(根据主键修改)
* @return
*/
@DeleteMapping("/{addrId}")
public ServerResult remove(@PathVariable("addrId") Integer addressId){
System.out.println("删除方法");
return addressService.removeById(addressId);
}
/**
* 修改我的某一个收件地址信息
* @param receiveAddress 页面中接受到的最新的收件地址信息
* @return 返回是否修改成功
*/
@PutMapping
public ServerResult update(@RequestBody ReceiveAddress receiveAddress){
System.out.println(receiveAddress);
System.out.println("put controller");
return addressService.updateById(receiveAddress);
}
@GetMapping("page/{pageNum}")
public ServerResult getByPage(@PathVariable("pageNum") Integer pageNum,HttpServletRequest request){
String token = request.getHeader("token");
LoginCustomer loginCustomer = JwtUtil.parseToken(token);
if(loginCustomer != null){
Integer customerId = loginCustomer.getCustId();
return addressService.getByPage(pageNum,customerId);
}else{
return ServerResult.getFail("登录用户无效");
}
}
// @GetMapping("/all")
// public ServerResult getByCustId(HttpServletRequest request){
// String token = request.getHeader("token");
// LoginCustomer loginCustomer = JwtUtil.parseToken(token);
// if(loginCustomer !=null){
// Integer custId = loginCustomer.getCustId();
// ServerResult addressResult = addressService.getByCustId(custId);
// return addressResult;
// }else{
// return ServerResult.getFail(null);
// }
// }
}
Customer.java
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author dd
* @since 2024-04-16
*/
@TableName("customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "cust_id", type = IdType.AUTO)
private Integer custId;
private String custName;
private Long custTelno;
private String custGender;
private LocalDate custBirth;
/**
* 状态
*/
private Integer status;
/**
* 版本号用于做乐观锁
*/
private Integer version;
/**
* 数据添加的时间
*/
private LocalDateTime createTime;
/**
* 数据修改时间
*/
private LocalDateTime updateTime;
private String custPassword;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public Long getCustTelno() {
return custTelno;
}
public void setCustTelno(Long custTelno) {
this.custTelno = custTelno;
}
public String getCustGender() {
return custGender;
}
public void setCustGender(String custGender) {
this.custGender = custGender;
}
public LocalDate getCustBirth() {
return custBirth;
}
public void setCustBirth(LocalDate custBirth) {
this.custBirth = custBirth;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
public String getCustPassword() {
return custPassword;
}
public void setCustPassword(String custPassword) {
this.custPassword = custPassword;
}
@Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName=" + custName +
", custTelno=" + custTelno +
", custGender=" + custGender +
", custBirth=" + custBirth +
", status=" + status +
", version=" + version +
", createTime=" + createTime +
", updateTime=" + updateTime +
", custPassword=" + custPassword +
"}";
}
}
LoginCustomer.java
package com.example.entity;
/**
* 该类封装了登录用户的信息
*/
public class LoginCustomer {
private Integer custId;
private String custName;
public LoginCustomer(){}
public LoginCustomer(Integer custId, String custName) {
this.custId = custId;
this.custName = custName;
}
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
}
ReceiveAddress.java
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author dd
* @since 2024-04-10
*/
@TableName("receive_address")
public class ReceiveAddress implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "addr_id", type = IdType.AUTO)
private Integer addrId;
private Long receiveUserTelno;
private String receiveUsername;
private Integer custId;
/**
* 地址的省份
*/
private String addrProvince;
/**
* 地址的城市
*/
private String addrCity;
/**
* 地址的区域
*/
private String addrArea;
/**
* 地址的街道
*/
private String addrStreet;
/**
* 详细地址
*/
private String addrDetail;
/**
* 状态
*/
private Integer status;
/**
* 版本号,用于做乐观锁
*/
private Integer version;
/**
* 数据添加的时间
*/
private LocalDateTime createTime;
/**
* 数据修改时间
*/
private LocalDateTime updateTime;
public Integer getAddrId() {
return addrId;
}
public void setAddrId(Integer addrId) {
this.addrId = addrId;
}
public Long getReceiveUserTelno() {
return receiveUserTelno;
}
public void setReceiveUserTelno(Long receiveUserTelno) {
this.receiveUserTelno = receiveUserTelno;
}
public String getReceiveUsername() {
return receiveUsername;
}
public void setReceiveUsername(String receiveUsername) {
this.receiveUsername = receiveUsername;
}
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getAddrProvince() {
return addrProvince;
}
public void setAddrProvince(String addrProvince) {
this.addrProvince = addrProvince;
}
public String getAddrCity() {
return addrCity;
}
public void setAddrCity(String addrCity) {
this.addrCity = addrCity;
}
public String getAddrArea() {
return addrArea;
}
public void setAddrArea(String addrArea) {
this.addrArea = addrArea;
}
public String getAddrStreet() {
return addrStreet;
}
public void setAddrStreet(String addrStreet) {
this.addrStreet = addrStreet;
}
public String getAddrDetail() {
return addrDetail;
}
public void setAddrDetail(String addrDetail) {
this.addrDetail = addrDetail;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "ReceiveAddress{" +
"addrId=" + addrId +
", receiveUserTelno=" + receiveUserTelno +
", receiveUsername=" + receiveUsername +
", custId=" + custId +
", addrProvince=" + addrProvince +
", addrCity=" + addrCity +
", addrArea=" + addrArea +
", addrStreet=" + addrStreet +
", addrDetail=" + addrDetail +
", status=" + status +
", version=" + version +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
}
}
JwtInterceptor.java
package com.example.interceptor;
import com.example.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 登录检查拦截器
* 被拦截下来的URL:
* 1.获得token
* 2.check token
*/
public class JwtInterceptor implements HandlerInterceptor {
//在访问前拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("登录检查拦截器正在拦截URL>>>"+request.getRequestURI());
//跨域请求会首先发一个option请求,直接返回正常状态并放行
//if(request.getMethod().equals("OPTION"))
//return true;
//1.获得token
String token = request.getHeader("token");
if(token == null || token.equals("")){
System.out.println("登录检查拦截器正在拦截,没有获得到token");
//跳转到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}else {//2.check token
System.out.println("登录检查拦截器正在拦截,获得到的token:"+token);
if (JwtUtil.checkToken(token)){//有效token
return true;
}else {
System.out.println("被拦截了,无效token");
return false;
}
}
// if(token != null){
// if(JwtUtil.checkToken(token))
// return true;//token有效
// }
// return false;
}
}
CustomerMapper.java
package com.example.mapper;
import com.example.entity.Customer;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author dd
* @since 2024-04-16
*/
public interface CustomerMapper extends BaseMapper<Customer> {
}
ReceiveAddressMapper.java
package com.example.mapper;
import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author dd
* @since 2024-04-10
*/
public interface ReceiveAddressMapper extends BaseMapper<ReceiveAddress> {
}
CustomerServiceImpl.java
package com.example.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Customer;
import com.example.entity.LoginCustomer;
import com.example.entity.ReceiveAddress;
import com.example.mapper.CustomerMapper;
import com.example.service.ICustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.JwtUtil;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author dd
* @since 2024-04-16
*/
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {
@Autowired
private CustomerMapper customerMapper;
@Override
public ServerResult login(String custName, String custPwd){
QueryWrapper<Customer> wrapper = new QueryWrapper<>();
wrapper.eq("cust_name",custName).eq("cust_password",custPwd);
Customer customer = customerMapper.selectOne(wrapper);
System.out.println(customer.getCustId());
System.out.println(customer.getCustName());
System.out.println(customer.getCustPassword());
if(customer != null) { // 登录成功
String token = JwtUtil.createToken(customer.getCustId(),customer.getCustName());
return ServerResult.loginSuccess(token);
}
return ServerResult.loginFail(null);
}
// @Override
// public ServerResult getLoginInfoById(String token) {
// if(JwtUtil.checkToken(token)) { // 有效的token
// LoginCustomer loginCustomer = JwtUtil.parseToken(token);
// if(loginCustomer !=null)
// return ServerResult.getSuccess(loginCustomer);
// else
// return ServerResult.getFail(null);
// }else
//
// return ServerResult.getFail(null);
// }
}
ReceiveAddressServiceImpl.java
package com.example.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.ReceiveAddress;
import com.example.mapper.ReceiveAddressMapper;
import com.example.service.IReceiveAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author dd
* @since 2024-04-10
*/
@Service
public class ReceiveAddressServiceImpl implements IReceiveAddressService {
@Autowired
private ReceiveAddressMapper addressMapper;
@Override
public ServerResult getById(Integer addressId) {
ReceiveAddress address = addressMapper.selectById(addressId);
if(address != null){
return ServerResult.getSuccess(address);
}
return ServerResult.getFail(null);
}
//当前登录用户的有效地址
@Override
public ServerResult getAll(Integer customerId){
//select * from
QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
wrapper.eq("cust_id",customerId).eq("status",1);
List<ReceiveAddress> addressList = addressMapper.selectList(wrapper);//select * from table_name where cust_id= and
if(addressList == null || addressList.size()==0)
return ServerResult.getFail("暂无收件地址");
return ServerResult.getSuccess(addressList);
}
//添加
public ServerResult save(ReceiveAddress receiveAddress){//receiveAddress: 没有addr_id
receiveAddress.setStatus(1);
receiveAddress.setVersion(1);
receiveAddress.setCreateTime(LocalDateTime.now());
System.out.println("尚未添加,从页面拿到的收件地址是:" + receiveAddress);
int rows = addressMapper.insert(receiveAddress);
if(rows > 0){
System.out.println("添加成功后:" + receiveAddress);
return ServerResult.updateSuccess(receiveAddress);//若添加成功,会把数据库中自增的主键addr_id赋值到对象上
}
return ServerResult.updateFail(receiveAddress);
}
//删除收件地址(实际修改status为0)
@Override
public ServerResult removeById(Integer addressId) {
ReceiveAddress address = addressMapper.selectById(addressId);
address.setStatus(0);
address.setVersion(address.getVersion() + 1);
int rows = addressMapper.updateById(address);//删除成功row =1,删除失败row=0
if(rows > 0)
return ServerResult.updateSuccess(address);
return ServerResult.updateFail(address);
}
@Override
public ServerResult updateById(ReceiveAddress address) {
System.out.println("put service");
int oldVersion = addressMapper.selectById(address.getAddrId()).getVersion();//旧的version值来自db
address.setUpdateTime(LocalDateTime.now());
address.setVersion(oldVersion+1);
int rows = addressMapper.updateById(address);
if(rows > 0){
return ServerResult.updateSuccess(address);
}
return ServerResult.updateFail(address);
}
@Override
public ServerResult getByPage(Integer pageNum,Integer customerId) {
//select * from address where cust_id = 1 and status = 1 limit 0,3
//select * from address where cust_id = 1 and status = 1 limit 3,3
//select * from address where cust_id = 1 and status = 1 limit 6,3
QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
wrapper.eq("cust_id",customerId).eq("status",1);
//page:只有页面的信息(当前页码、每页显示记录数)
Page<ReceiveAddress> page = new Page<>(pageNum,3);
//page:页码的信息+数据
page = addressMapper.selectPage(page,wrapper);
if (page.getRecords().size() > 0){
return ServerResult.getSuccess(page);
}
return ServerResult.getFail(page);
}
@Override
public ServerResult getByCustId(Integer custId) {
QueryWrapper<ReceiveAddress> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("cust_id",custId);
List<ReceiveAddress> receiveAddressList = addressMapper.selectList(queryWrapper);
if(receiveAddressList.size() >0)
return ServerResult.getSuccess(receiveAddressList);
return ServerResult.getFail(null);
}
}
ICustomerService.java
package com.example.service;
import com.example.entity.Customer;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.util.ServerResult;
/**
* <p>
* 服务类
* </p>
*
* @author dd
* @since 2024-04-16
*/
public interface ICustomerService extends IService<Customer> {
public ServerResult login(String custName,String custPwd);
// public ServerResult getLoginInfoById(String token);
}
IReceiveAddressService.java
package com.example.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.util.ServerResult;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author dd
* @since 2024-04-10
*/
public interface IReceiveAddressService {
public ServerResult getById(Integer addressId);
//查询所有的收件地址(当前用户有效的地址数据)
public ServerResult getAll(Integer customerId);
public ServerResult save(ReceiveAddress receiveAddress);
public ServerResult removeById(Integer addressId);
public ServerResult updateById(ReceiveAddress address);
//分页查询
public ServerResult getByPage(Integer pageNum,Integer customerId);
/**
* 根据用户Id查询他的所有收件地址
* @param custId
* @return
*/
public ServerResult getByCustId(Integer custId);
}
JwtUtil.java
package com.example.util;
import io.jsonwebtoken.*;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.example.entity.LoginCustomer;
public class JwtUtil {
private static final String jwtToken = "dahkgag7*$";
private static long expireTime = 1000*60*60*24;
/**
* 创建新token
* @param customerId 用户id
* @param customerName
* @return
*/
public static String createToken(Integer customerId,String customerName){
Map<String,Object> claims = new HashMap<>();
claims.put("customerId",customerId);
claims.put("customerName",customerName);
JwtBuilder jwtBuilder = Jwts.builder().signWith(SignatureAlgorithm.HS256,jwtToken)//签发算法(head部分),秘钥为jwtToken
.setClaims(claims)//body数据,要唯一,自行设。payload部分数据 //1.(customerId,customerName)--token
.setIssuedAt(new Date())//设置签发时间:保证每次生成的token不同
.setExpiration(new Date(System.currentTimeMillis()+expireTime));//一天的有效时间
String token = jwtBuilder.compact();
return token;
}
//验证token是否有效
/**
* 验证token是否有效
* @param token 客户端携带的token
* @return 返回是否有效
*/
//2.验证token是否过期
public static boolean checkToken(String token){
if(token != null && !token.equals("")){
try {
Jwt parse = Jwts.parser().setSigningKey(jwtToken).parseClaimsJws(token);
return true;
}catch (ExpiredJwtException e){
System.out.println("token已经过期了");
return false;
} catch (Exception e) {
System.out.println("无效的token");
return false;
}
}else
return false;
}
/**
* 解析token中的用户数据
* @param token 客户端携带的token
* @return 返回登录用户信息(customerIs)
*/
public static LoginCustomer parseToken(String token){
if(token != null && !token.equals("")) {
try {
Jwt parse = Jwts.parser().setSigningKey(jwtToken).parseClaimsJws(token);
Map<String,Object> map = (Map<String, Object>)parse.getBody();
if(map != null){
Integer custId = (Integer)map.get("customerId");//注意,此处的key 要与当初绑定进去的key一致
String custName = (String)map.get("customerName");//注意,此处的key 要与当初绑定进去的key一致
LoginCustomer loginCustomer = new LoginCustomer(custId,custName);
System.out.println("获得到的登录用户的信息是:" + loginCustomer);
return loginCustomer;
}else{
System.out.println("获得到的登录用户的信息失败");
return null;
}
} catch (Exception e){
e.printStackTrace();
return null;
}
}else
return null;
}
}
ServerResult.java
package com.example.util;
public class ServerResult {
private int code;
private String msg;
private Object data;
public static ServerResult getSuccess(Object data){
return new ServerResult(200,"查询成功",data);
}
public static ServerResult getFail(Object data){
return new ServerResult(201,"查询失败",data);
}
/**
* 添加、删除、修改的成功
* @param data
* @return
*/
public static ServerResult updateSuccess(Object data){
return new ServerResult(200,"处理成功",data);
}
/**
* 添加、删除、修改的失败
* @param data
* @return
*/
public static ServerResult updateFail(Object data){
return new ServerResult(201,"处理失败",data);
}
public static ServerResult loginSuccess(Object data){
return new ServerResult(200,"登录成功",data);
}
public static ServerResult loginFail(Object data){
return new ServerResult(201,"登失败",data);
}
public ServerResult() {
}
public ServerResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "ServerResult{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
ServletInitializer.java
package com.example;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootDemoApplication.class);
}
}
SpringbootDemoApplication.java
package com.example;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
customer.sql
/*
Navicat Premium Data Transfer
Source Server : mysql8_3306
Source Server Type : MySQL
Source Server Version : 80029
Source Host : localhost:3306
Source Schema : empdb
Target Server Type : MySQL
Target Server Version : 80029
File Encoding : 65001
Date: 11/04/2024 09:38:17
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for customer
-- ----------------------------
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
`cust_id` int(0) NOT NULL AUTO_INCREMENT,
`cust_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`cust_telno` bigint(0) NOT NULL,
`cust_gender` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`cust_birth` date NULL DEFAULT NULL,
`status` int(0) NULL DEFAULT NULL COMMENT '状态',
`version` int(0) NULL DEFAULT NULL COMMENT '版本号用于做乐观锁',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '数据添加的时间',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '数据修改时间',
`cust_password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`cust_id`) USING BTREE,
UNIQUE INDEX `cust_telno`(`cust_telno`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES (1, 'smith', 1849430033, 'M', '2000-01-01', 1, 1, '2023-08-11 13:39:30', NULL, '123456');
INSERT INTO `customer` VALUES (2, 'allen', 13771940583, 'F', '2001-05-01', 1, 1, '2023-07-31 13:40:09', NULL, '123456');
SET FOREIGN_KEY_CHECKS = 1;
receive_address.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for receive_address
-- ----------------------------
DROP TABLE IF EXISTS `receive_address`;
CREATE TABLE `receive_address` (
`addr_id` int(0) NOT NULL AUTO_INCREMENT,
`receive_user_telno` bigint(0) NULL DEFAULT NULL,
`receive_username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`cust_id` int(0) NULL DEFAULT NULL,
`addr_province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的省份',
`addr_city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的城市',
`addr_area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的区域',
`addr_street` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的街道',
`addr_detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '详细地址',
`status` int(0) NULL DEFAULT NULL COMMENT '状态',
`version` int(0) NULL DEFAULT NULL COMMENT '版本号,用于做乐观锁',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '数据添加的时间',
`update_time` datetime(0) NULL DEFAULT NULL COMMENT '数据修改时间',
PRIMARY KEY (`addr_id`) USING BTREE,
INDEX `fk_address_customer`(`cust_id`) USING BTREE,
CONSTRAINT `fk_address_customer` FOREIGN KEY (`cust_id`) REFERENCES `customer` (`cust_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of receive_address
-- ----------------------------
INSERT INTO `receive_address` VALUES (1, NULL, NULL, 1, '江苏省', '苏州市', '园区', '若水路', '若水路', 1, 1, '2023-08-11 13:47:02', NULL);
INSERT INTO `receive_address` VALUES (2, NULL, NULL, 1, '黑龙江', '大庆市', '市区', '育才路', '育才路', 1, 1, '2023-07-31 13:47:52', NULL);
SET FOREIGN_KEY_CHECKS = 1;
CustomerMapper.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.example.mapper.CustomerMapper">
</mapper>
ReceiveAddressMapper.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.example.mapper.ReceiveAddressMapper">
</mapper>
application.yaml
server:
servlet:
context-path: /app
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/dict?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mvc:
view:
prefix: / #前缀
suffix: .jsp #后缀
hiddenmethod:
filter:
enabled: true # 支持表单 method 转换
logging:
file:
path: d://logger #日志记录
level:
com.example: debug
ajax_demo1.js(忽略)
/****1.ajax 异步请求:根据主键查询 ****/
document.querySelector(".getByIdBtn").onclick = function (){
//1.创建异步请求对象
var xhr = new XMLHttpRequest();
//2连接服务器
var url = "http://localhost:80/app/receiveAddressJSon/1"
xhr.open("GET",url,true);
//3.发送请求
xhr.send(null);
//4.获得相应数据
xhr.onreadystatechange = function (){
if(xhr.readyState == 4 && xhr.status == 200){//http请求响应成功
var result = JSON.parse(xhr.responseText);//json-->js对象
if(result.code == 200){//自己封装的结果状态码
document.querySelector(".address_detail").style.display = "block";
var username = result.data.receiveUsername;
var userTelno = result.data.receiveUserTelno
var detailAddress = result.data.addrProvince + result.data.addrCity + result.data.addrArea + result.data.addrStreet + result.data.addrDetail;
document.querySelector(".receive_username").innerText = username;
document.querySelector(".receive_telno").innerText = userTelno;
document.querySelector(".receive_detail_address").innerText = detailAddress;
}else{
document.querySelector(".address_no_data_info span").innerText = "暂无数据";
}
}else{
console.log("请求响应失败");
//json数据不完整可能
}
}
}
/**********************2. ajax 异步请求:添加收件地址 *****/
document.querySelector(".saveAddressBtn").onclick= function (){
var xhr = new XMLHttpRequest();
var url = "http://localhost:80/app/receiveAddressJson"
xhr.open("POST",url,true);
//表单的数据
var receiveUsername = document.querySelector("#recipientName").value;
var receiveUserTelno = document.querySelector("#phoneNumber").value;
var province = document.querySelector("#province").value;
var city = document.querySelector("#city").value;
var district = document.querySelector("#district").value;
var street = document.querySelector("#street").value;
var address = document.querySelector("#address").value;
// k1=v1&k2=v2&k3=v3
var formData = "receiveUserTelno="+receiveUserTelno + "&receiveUsername="+receiveUsername +"&addrProvince="+province+"&addrCity="+city
+"&addrArea="+district + "&addrStreet="+street+"&addrDetail="+address;
console.log(formData)
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(formData); // xhr.send(表单数据)
xhr.onreadystatechange = function (){
if(xhr.status ==200 && xhr.readyState ==4) {
console.log(xhr.responseText);
let result = JSON.parse(xhr.responseText);
if (result.code = 200) {
document.querySelector(".saveMsg").innerText = "添加成功";
} else {
document.querySelector(".saveMsg").innerText = "添加失败";
}
}
}
}
ajax_jquery_demo1.js
// //打开ajax_jquery_demo.jsp页面(只有用户登录成功后),就需要加载登录用户的信息
// LoadLoginCustomerInfo();
// function LoadLoginCustomerInfo(){
// let token = localStorage.getItem("token");
//
// $.ajax({
// type: "get",
// url: url,
// headers: {'token':token},
// success:function (result){
// if (result.code == 200){
// $(".log")
// }
// }
// })
//
//
// }
//根据主键查询
$(".getByIdBtn").click(function (){
let addressId = 1;
let url = "http://localhost:80/app/receiveAddressJSon/"+addressId;
var token = localStorage.getItem("token");
$.ajax({
type: "get",
url: url,
headers: {'token': token},
success: function (result) {
console.log(result)
console.log(result.code == 200)
if (result.code == 200){
//数据渲染到页面
$(".address_detail").show();
$(".receive_username").text(result.data.receiveUsername);
$(".receive_telno").text(result.data.receiveUserTelno);
var detailAddress = result.data.addrProvince + result.data.addrCity + result.data.addrArea + result.data.addrStreet + result.data.addrDetail;
$(".receive_detail_address").text(detailAddress);
}else{
$(".address_no_data_info").text("暂无数据");
}
}
});
});
//添加
$(".saveAddressBtn").click(function (){
let url = "http://localhost:80/app/receiveAddressJSon/";
let formData = $("#addressForm").serialize(); // name1=v1&name2=v2
let token = localStorage.getItem("token");
console.log(formData)
console.log(token)
$.ajax({
type:"post",
url:url,
data:formData,
headers:{'token': token},
success:function (){
$(".saveMsg").text("添加成功");
},
error:function (){
$(".saveMsg").text("添加失败");
}
})
})
//3.查询我的所有收件地址(分页)
$(".getMyAllAddressBtn").click(function (){
getAddressByPage(1);
})
function getAddressByPage(pageNum) {
let url = "http://localhost:80/app/receiveAddressJSon/page/"+pageNum;
let token = localStorage.getItem("token");
$.ajax({
type:"get",
url:url,
headers:{'token': token},
success:function (result){
//1.数据渲染
let addressArray = result.data.records;
var ulEle = $("#addressList");
ulEle.html("");
$(".page-information").html("");
for (var i = 0; i < addressArray.length; i++) {
var addrId = addressArray[i].addrId;
var username = addressArray[i].receiveUsername;
var telno = addressArray[i].receiveUserTelno;
var detailAddress = addressArray[i].addrProvince + addressArray[i].addrCity + addressArray[i].addrArea + addressArray[i].addrStreet + addressArray[i].addrDetail;
let liElement = '<li>\n' +
' <div class="btn-container">\n' +
' <form class="deleteForm" method="post" action="">\n' +
' <input type="hidden" name="_method" value="DELETE">\n' +
' <input type="hidden" name="addressId" value="' + addrId + '">' +
' <input type="button" value="删除" class="delete-btn">\n' +
' <input type="button" value="修改" class="update-btn">'+
' </form>\n' +
' </div>\n' +
' <h3>' + username + '</h3>\n' +
' <p>手机号: ' + telno + '</p>\n' +
' <p>收件地址: ' + detailAddress + '</p>\n' +
' </li>';
ulEle.append(liElement);
}
//2页码渲染
var pageNum = result.data.current;
var pages = result.data.pages;
var total = result.data.total;
var prePage = result.data.current-1;
var nextPage = result.data.current+1;
if(pageNum != 1) //有上一页
var prePageEle = '<a href="javascript:getAddressByPage('+prePage+')">上一页</a>';
var pageEle = ' 当前是'+pageNum+' 页,共有 '+total+' 条记录,共有 '+pages+'页';
if(pageNum != pages)//有下一页
var nextPageEle = '<a href="javascript:getAddressByPage('+nextPage+')">下一页</a>';
$(".page-information").append(prePageEle).append(pageEle).append(nextPageEle);
},
error:function (){
}
})
// $.get(url, function (result) {
// console.log(result);
// //1.数据渲染
// let addressArray = result.data.records;
// var ulEle = $("#addressList");
// ulEle.html("");
// $(".page-information").html("");
// for (var i = 0; i < addressArray.length; i++) {
//
// var addrId = addressArray[i].addrId;
// var username = addressArray[i].receiveUsername;
// var telno = addressArray[i].receiveUserTelno;
// var detailAddress = addressArray[i].addrProvince + addressArray[i].addrCity + addressArray[i].addrArea + addressArray[i].addrStreet + addressArray[i].addrDetail;
//
//
// let liElement = '<li>\n' +
// ' <div class="btn-container">\n' +
// ' <form class="deleteForm" method="post" action="">\n' +
// ' <input type="hidden" name="_method" value="DELETE">\n' +
// ' <input type="hidden" name="addressId" value="' + addrId + '">' +
// ' <input type="button" value="删除" class="delete-btn">\n' +
// ' <input type="button" value="修改" class="update-btn">'+
// ' </form>\n' +
// ' </div>\n' +
// ' <h3>' + username + '</h3>\n' +
// ' <p>手机号: ' + telno + '</p>\n' +
// ' <p>收件地址: ' + detailAddress + '</p>\n' +
// ' </li>';
//
// ulEle.append(liElement);
//
// }
//
//
// //2页码渲染
// var pageNum = result.data.current;
// var pages = result.data.pages;
// var total = result.data.total;
// var prePage = result.data.current-1;
// var nextPage = result.data.current+1;
//
//
// if(pageNum != 1) //有上一页
// var prePageEle = '<a href="javascript:getAddressByPage('+prePage+')">上一页</a>';
// var pageEle = ' 当前是'+pageNum+' 页,共有 '+total+' 条记录,共有 '+pages+'页';
// if(pageNum != pages)//有下一页
// var nextPageEle = '<a href="javascript:getAddressByPage('+nextPage+')">下一页</a>';
//
// $(".page-information").append(prePageEle).append(pageEle).append(nextPageEle);
//
//
//
//
// });
}
//4删除收件地址(业务实际是修改status=0)
// //事件冒泡,获得删除按钮
// $("#addressList").click(function (event){
// event.preventDefault();
// var ele = event.target;
// if(ele.nodeName == 'INPUT' && ele.className=='delete-btn'){
// if(window.confirm('你确定要删除这条收件地址记录?')){
// var addressId = ele.previousElementSibling.value;//删除按钮的前一个元素的值
// removeAddress(addressId);
// }
// }
// })
// //事件冒泡。获得修改按钮
// $("#addressList").click(function (event){
// event.preventDefault();
// var ele = event.target;
// if(ele.nodeName == 'INPUT' && ele.className=='update-btn'){
// if(window.confirm('你确定要修改这条收件地址记录?')){
// var addressId = ele.previousElementSibling.previousElementSibling.value;//删除按钮的前一个元素的值
// console.log(addressId);
// getUpdatePage(addressId);
// }
// }
// })
$("#addressList").click(function (event) {
event.preventDefault();
var ele = event.target;
if (ele.nodeName == 'INPUT') {
if (ele.className == 'delete-btn') {
if (window.confirm('你确定要删除这条收件地址记录?')) {
var addressId = ele.previousElementSibling.value;
removeAddress(addressId);
}
} else if (ele.className == 'update-btn') {
if (window.confirm('你确定要修改这条收件地址记录?')) {
var addressId = ele.previousElementSibling.previousElementSibling.value;
console.log(addressId);
getUpdatePage(addressId);
}
}
}
});
function removeAddress(addressId){
$("deleteMsg").text("");
let url = "http://localhost:80/app/receiveAddressJSon/"+addressId;
let token = localStorage.getItem("token");
$.ajax({
type: "DELETE",
url: url,
headers: {'token': token},
// data: {_method:'DELETE'},
success: function () {
$("deleteMsg").text("删除成功");
getAddressByPage(1);//重新查询列表数据
},
error:function (){
$("deleteMsg").text("删除失败");
}
})
}
//渲染修改页面
function getUpdatePage(addressId) {
var url = "http://localhost:80/app/receiveAddressJSon/"+addressId;
let token = localStorage.getItem("token");
$.ajax({
type:"get",
url:url,
headers:{'token': token},
success:function (result) {
$('#addrId2').val(result.data.addrId);
$('#recipientName2').val(result.data.receiveUsername);
$('#phoneNumber2').val(result.data.receiveUserTelno);
//$('#province2').val(result.data.addrProvince);
//$('#city2').val(result.data.addrCity);
$('#district2').val(result.data.addrArea);
$('#street2').val(result.data.addrStreet);
$('#address2').val(result.data.addrDetail);
var value = result.data.addrProvince;
var $option = $('<option></option>').attr('value', value).text(value);
// 将新的<option>插入到<select>的第一个位置
$('#province2').prepend($option);
var value2 = result.data.addrCity;
var $option2 = $('<option></option>').attr('value', value2).text(value2);
// 将新的<option>插入到<select>的第一个位置
$('#city2').prepend($option2);
//var addressId = $("input[name='addressId']").val();
//document.getElementsByName("addressId")[0].value;
//console.log(result);
// var rd = result.data;
// var addrId = rd.addrId;
// var username = rd.receiveUsername;
// var telno = rd.receiveUserTelno;
//var detailAddress = rd.addrProvince + rd.addrCity + rd.addrArea + rd.addrStreet + rd.addrDetail;
// let liElement = '<li>\n' +
// ' <div class="btn-container">\n' +
// '<form id="updateForm" method="post" >\n' +
// ' <input type="hidden" name="_method" value="PUT">\n' +
// ' <input type="hidden" name="addrId" value="' + addrId + '">\n' +
// '\n' +
// ' <label for="recipientName">收件人姓名:</label>\n' +
// ' <input type="text" id="recipientName" name="receiveUsername" value="' + username + '" required>\n' +
// '\n' +
// ' <label for="phoneNumber">收件人手机号:</label>\n' +
// ' <input type="tel" id="phoneNumber" name="receiveUserTelno" value="' + telno + '" required>\n' +
// '\n' +
// ' <label for="province">省份:</label>\n' +
// ' <select id="province" name="addrProvince" required>\n' +
// ' <option value="' + result.data.addrProvince + '">' + result.data.addrProvince + '</option>\n' +
// ' <option value="北京">北京</option>\n' +
// ' <option value="上海">上海</option>\n' +
// ' <option value="天津">天津</option>\n' +
// ' <option value="重庆">重庆</option>\n' +
// ' <option value="河北">河北</option>\n' +
// ' <option value="河南">河南</option>\n' +
// ' <option value="湖南">湖南</option>\n' +
// ' <option value="湖北">湖北</option>\n' +
// ' <option value="四川">四川</option>\n' +
// ' <option value="广东">广东</option>\n' +
// ' </select>\n' +
// '\n' +
// ' <label for="city">城市:</label>\n' +
// ' <select id="city" name="addrCity" required>\n' +
// ' <option value="' + result.data.addrCity + '">' + result.data.addrCity + '</option>\n' +
// ' </select>\n' +
// '\n' +
// ' <label for="district">区域:</label>\n' +
// ' <input type="text" id="district" name="addrArea" value="' + result.data.addrArea + '" required>\n' +
// '\n' +
// ' <label for="street">街道:</label>\n' +
// ' <input type="text" id="street" name="addrStreet" value="' + result.data.addrStreet + '" required>\n' +
// '\n' +
// ' <label for="address">详细地址:</label>\n' +
// ' <input type="text" id="address" name="addrDetail" value="' + result.data.addrDetail + '" required>\n' +
// '\n' +
// ' <input type="button" value="修改" class="upbtn" />\n' +
// ' </form>' +
// ' </div>\n' +
// ' </li>';
},error:function (){
}
})
}
$(".updateBtn").click(function (){
let url = "http://localhost:80/app/receiveAddressJSon";
let token = localStorage.getItem("token");
//let formData = $("#updateForm");
let form = $("#updateForm");
let formData = {
addrId: form.find("input[name='addrId']").val(),
receiveUsername: form.find("input[name='receiveUsername']").val(),
receiveUserTelno: form.find("input[name='receiveUserTelno']").val(),
addrProvince: form.find("select[name='addrProvince']").val(),
addrCity: form.find("select[name='addrCity']").val(),
addrArea: form.find("input[name='addrArea']").val(),
addrStreet: form.find("input[name='addrStreet']").val(),
addrDetail: form.find("input[name='addrDetail']").val()
};
// 将JavaScript对象转换为JSON字符串
let jsonData = JSON.stringify(formData);
$.ajax({
type: "PUT",
url: url,
headers: {
'Content-Type': 'application/json', // 设置请求头的内容类型为application/json
'token': token
},
//data: formData,
data: jsonData, // 发送JSON字符串
success: function () {
getAddressByPage(1);
},
error:function (){
}
})
})
getCustomerInfo_logout.js
// 打开ajax_jquery_demo.jsp 页面(只有用户登录成功后),就需要加载登录用户的信息
loadLoginCustomerInfo();
function loadLoginCustomerInfo(){
$(".login_customer_name").text("")
$(".loginMsg").text("")
let token = localStorage.getItem("token");
console.log(token)
let url = "http://localhost:80/app/customer/getInfoByToken"
$.ajax({
type: "get",
url: url,
headers: {'token': token},
success:function (result){
if(result.code == 200){
$(".login_area").show();
$(".login_customer_name").text(result.data.custName);
}else{
$(".login_area").hide();
$(".loginMsg").text(result.data)
}
}
})
}
//退出
$(".logoutBtn").click(function (){
console.log("退出操作...")
localStorage.removeItem("token");
window.location.href="index.jsp"
});
// 返回首页
$(".backToIndexBtn").click(function (){
window.open("index.jsp")
});
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
ajax_demo1.jsp(忽略)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>1.ajax 异步请求:根据主键查询</h1>
<a href="javascript:void(0)" class="getByIdBtn">查询id=1的收件地址</a>
<div class="address_detail">
收件人姓名:<span class="receive_username"></span><br>
收件人手机号:<span class="receive_telno"></span><br>
收件地址:<span class="receive_detail_address"></span><br>
</div>
<div class="address_no_data_info">
<span></span>
</div>
<%--============================2. ajax 异步请求:添加收件地址=======================================================--%>
<h1>2. ajax 异步请求:添加收件地址</h1>
<form id="addressForm" method="post" action="${pageContext.request.contextPath}/receiveAddress">
<label for="recipientName">收件人姓名:</label>
<input type="text" id="recipientName" name="receiveUsername" required> <br>
<label for="phoneNumber">收件人手机号:</label>
<input type="tel" id="phoneNumber" name="receiveUserTelno" required> <br>
<label for="province">省份:</label>
<select id="province" name="addrProvince" required>
<option value="">请选择省份</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="天津">天津</option>
<option value="重庆">重庆</option>
<option value="河北">河北</option>
<option value="河南">河南</option>
<option value="湖南">湖南</option>
<option value="湖北">湖北</option>
<option value="四川">四川</option>
<option value="广东">广东</option>
</select> <br>
<label for="city">城市:</label>
<select id="city" name="addrCity" required>
<option value="">请选择城市</option>
</select> <br>
<label for="district">区域:</label>
<input type="text" id="district" name="addrArea" required> <br>
<label for="street">街道:</label>
<input type="text" id="street" name="addrStreet" required> <br>
<label for="address">详细地址:</label>
<input type="text" id="address" name="addrDetail" required> <br>
<input type="button" value="添加 " class="saveAddressBtn"/>
</form>
<span class="saveMsg"></span>
<script>
// Cities data for each province
var citiesData = {
"北京": ["北京"],
"上海": ["上海"],
"天津": ["天津"],
"重庆": ["重庆"],
"河北": ["石家庄", "唐山", "保定"],
"河南": ["郑州", "洛阳", "开封"],
"湖南": ["长沙", "株洲", "湘潭"],
"湖北": ["武汉", "黄石", "十堰"],
"四川": ["成都", "绵阳", "乐山"],
"广东": ["广州", "深圳", "东莞"]
};
// Function to populate cities based on selected province
function populateCities() {
var provinceSelect = document.getElementById("province");
var citySelect = document.getElementById("city");
var selectedProvince = provinceSelect.value;
// Clear existing city options
citySelect.innerHTML = "<option value=''>Select City</option>";
// Populate city options based on selected province
if (selectedProvince in citiesData) {
citiesData[selectedProvince].forEach(function(city) {
var option = document.createElement("option");
option.value = city;
option.text = city;
citySelect.appendChild(option);
});
}
}
// Event listener for province select change
document.getElementById("province").addEventListener("change", populateCities);
</script>
<script src="${pageContext.request.contextPath}/js/ajax_demo1.js"></script>
</body>
</html>
ajax_jquery_demo1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax-jquery-收件地址</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
<style>
.address_detail{
display: none;
}
.login_area{
display: none;
}
</style>
</head>
<body>
<div class="login_area">
欢迎<span class="login_customer_name"></span>登录
<a href="javascript:void(0)" class="logoutBtn">退出</a>
</div>
<span class="loginMsg"></span>
<a href="javascript:void(0)" class="backToIndexBtn">返回首页</a>
<%--============================1. ajax 异步请求:根据主键查询收件地址=======================================================--%>
<h1>1. ajax-jquery 异步请求:根据主键查询收件地址</h1>
<a href="javascript:void(0)" class="getByIdBtn">查询id=1的收件地址</a>
<div class="address_detail">
收件人姓名:<span class="receive_username"></span> <br>
收件人手机号:<span class="receive_telno"></span> <br>
收件地址:<span class="receive_detail_address"></span> <br>
</div>
<div class="address_no_data_info">
<span ></span>
</div>
<%--============================2. ajax 异步请求:添加收件地址=======================================================--%>
<h1>2. ajax-jquery 异步请求:添加收件地址</h1>
<form id="addressForm" method="post" >
<label for="recipientName">收件人姓名:</label>
<input type="text" id="recipientName" name="receiveUsername" required> <br>
<label for="phoneNumber">收件人手机号:</label>
<input type="tel" id="phoneNumber" name="receiveUserTelno" required> <br>
<label for="province">省份:</label>
<select id="province" name="addrProvince" required>
<option value="">请选择省份</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="天津">天津</option>
<option value="重庆">重庆</option>
<option value="河北">河北</option>
<option value="河南">河南</option>
<option value="湖南">湖南</option>
<option value="湖北">湖北</option>
<option value="四川">四川</option>
<option value="广东">广东</option>
</select> <br>
<label for="city">城市:</label>
<select id="city" name="addrCity" required>
<option value="">请选择城市</option>
</select> <br>
<label for="district">区域:</label>
<input type="text" id="district" name="addrArea" required> <br>
<label for="street">街道:</label>
<input type="text" id="street" name="addrStreet" required> <br>
<label for="address">详细地址:</label>
<input type="text" id="address" name="addrDetail" required> <br>
<input type="button" value="添加 " class="saveAddressBtn"/>
</form>
<span class="saveMsg"></span>
<%-- updateform表单 --%>
<form id="updateForm" method="post" >
<input type="hidden" name="_method" value="PUT">
<input type="hidden" id="addrId2" name="addrId" >
<label for="recipientName2">收件人姓名:</label>
<input type="text" id="recipientName2" name="receiveUsername" required> <br>
<label for="phoneNumber2">收件人手机号:</label>
<input type="tel" id="phoneNumber2" name="receiveUserTelno" required> <br>
<label for="province2">省份:</label>
<select id="province2" name="addrProvince" required>
<option value=""></option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="天津">天津</option>
<option value="重庆">重庆</option>
<option value="河北">河北</option>
<option value="河南">河南</option>
<option value="湖南">湖南</option>
<option value="湖北">湖北</option>
<option value="四川">四川</option>
<option value="广东">广东</option>
</select> <br>
<label for="city2">城市:</label>
<select id="city2" name="addrCity" required>
<option value="">请选择城市</option>
</select> <br>
<label for="district2">区域:</label>
<input type="text" id="district2" name="addrArea" required> <br>
<label for="street2">街道:</label>
<input type="text" id="street2" name="addrStreet" required> <br>
<label for="address2">详细地址:</label>
<input type="text" id="address2" name="addrDetail" required> <br>
<input type="button" value="修改 " class="updateBtn"/>
</form>
<span class="updateMsg"></span>
<%-- 3.ajax异步请求,查询所有收件地址 --%>
<a href="javascript:void(0)" class="getMyAllAddressBtn">查询所有收件地址(分页)</a>
<%-- 数据信息 --%>
<ul class="address-list" id="addressList">
</ul>
<ul class="update-list" id="updateList">
</ul>
<%-- 页码信息--%>
<div class="page-information">
</div>
<span class="deleteMsg"></span>
<%--省份城市下拉列表--%>
<script>
// Cities data for each province
var citiesData = {
"北京": ["北京"],
"上海": ["上海"],
"天津": ["天津"],
"重庆": ["重庆"],
"河北": ["石家庄", "唐山", "保定"],
"河南": ["郑州", "洛阳", "开封"],
"湖南": ["长沙", "株洲", "湘潭"],
"湖北": ["武汉", "黄石", "十堰"],
"四川": ["成都", "绵阳", "乐山"],
"广东": ["广州", "深圳", "东莞"]
};
// Function to populate cities based on selected province
function populateCities() {
var provinceSelect = document.getElementById("province");
var citySelect = document.getElementById("city");
var selectedProvince = provinceSelect.value;
// Clear existing city options
citySelect.innerHTML = "<option value=''>Select City</option>";
// Populate city options based on selected province
if (selectedProvince in citiesData) {
citiesData[selectedProvince].forEach(function(city) {
var option = document.createElement("option");
option.value = city;
option.text = city;
citySelect.appendChild(option);
});
}
}
// Event listener for province select change
document.getElementById("province").addEventListener("change", populateCities);
</script>
<script src="${pageContext.request.contextPath}/js/ajax_jquery_demo1.js"></script>
<script src="${pageContext.request.contextPath}/js/getCustomerInfo_logout.js"></script>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
.login_area{
display: none;
}
</style>
<script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js"></script>
</head>
<body>
<h2>首页</h2>
<%--<a href="javascript:void(0)" class="getCustInfoBtn">获得当前用户的信息</a>--%>
<div class="login_area">
欢迎<span class="login_customer_name"></span>登录
<a href="javascript:void(0)" class="logoutBtn">退出</a>
</div>
<span class="loginMsg"></span>
<a href="javascript:void(0)" class="getMyAddressBtn">查看我的所有收件地址</a>
<%--<script>--%>
<%-- getCustInfo();--%>
<%-- /**--%>
<%-- * 获得用户信息--%>
<%-- */--%>
<%-- function getCustInfo(){--%>
<%-- var tokenStr = localStorage.getItem("token");--%>
<%-- var token = JSON.parse(tokenStr);--%>
<%-- console.log("从localStorage 中获得的token是:" + token);--%>
<%-- $.ajax({--%>
<%-- type: "get",--%>
<%-- url:"http://localhost:80/app/customer/info",--%>
<%-- headers: {'token': token},--%>
<%-- success: function (result) {--%>
<%-- console.log("获得当前用户的信息:" +result);--%>
<%-- if(result.code ==200) {--%>
<%-- var custId = result.data.custId;--%>
<%-- var custName = result.data.custName;--%>
<%-- console.log("custId:" + custId);--%>
<%-- console.log("custName:" + custName);--%>
<%-- // 显示用户登录信息--%>
<%-- $(".loginInfo").css("display","block");--%>
<%-- $(".custName").text(custName)--%>
<%-- }else if(result.code ==202){--%>
<%-- console.log("用户登录超时,请重新登录");--%>
<%-- window.location ="http://localhost:80/app/customer/login.jsp"--%>
<%-- }--%>
<%-- }--%>
<%-- })--%>
<%-- }--%>
<%-- $(".getCustInfoBtn").click(getCustInfo);--%>
<%-- // 用户退出--%>
<%-- $(".logoutBtn").click(logout);--%>
<%-- /**--%>
<%-- * 用户退出--%>
<%-- */--%>
<%-- function logout(){--%>
<%-- var tokenStr = localStorage.getItem("token");--%>
<%-- if(tokenStr!=null || tokenStr !=""){--%>
<%-- localStorage.removeItem("token");--%>
<%-- // 显示用户登录信息--%>
<%-- $(".loginInfo").css("display","none");--%>
<%-- $(".custName").text("")--%>
<%-- }--%>
<%-- }--%>
<%-- /***********************查看我的所有收件地址**********************************/--%>
<%-- $(".getMyAddressBtn").click(function (){--%>
<%-- var token = localStorage.getItem("token");--%>
<%-- $.ajax({--%>
<%-- type:"get",--%>
<%-- url:"http://localhost:80/app/receiveAddressJSon/all",--%>
<%-- headers: {'token': token},--%>
<%-- success:function (data){--%>
<%-- console.log(data)--%>
<%-- }--%>
<%-- })--%>
<%-- })--%>
<%--</script>--%>
${result.data}
<script src="${pageContext.request.contextPath}/js/getCustomerInfo_logout.js"></script>
</body>
</html>
login.jsp
<%--isELIgnored="false"--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script src="./js/jquery-3.7.0.min.js" ></script>
<html>
<head>
<title>登录</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js" ></script>
</head>
<body>
<h2>用户登录</h2>
<form class="loginForm" method="post" >
用户名:<input name="custName" class="custName" type="text" /><br>
密码:<input name="custPassword" class="custPassword" type="password" /><br>
<input type="button" class="loginBtn" value="登录">
</form>
<span class="loginMsg"></span>
<script>
$(".loginBtn").click(function (){
var url = "http://localhost:80/app/customer/login";
var formData = $(".loginForm").serialize();
$.post(url,formData,function (result){
console.log(result)
if (result.code == 200){
localStorage.setItem("token",result.data);//1保存token
window.location.href = "http://localhost:80/app/ajax_jquery_demo1.jsp";//2跳转
}else {
$(".loginMsg").text(result.data);
}
})
})
// $(".loginBtn").click(function (){
// $.ajax({
// type:"post",
// url:"http://localhost:80/app/customer/login",
// data:{
// custName:$(".custName").val(),
// custPassword:$(".custPassword").val()
// },
// success:function (result){
// console.log("result:" + result);
// console.log("json result:" + JSON.stringify(result));
//
// if(result.code ==200) {
// //保存信息到本地,里面都 token
// var token = JSON.stringify(result.data);
// console.log("登录后,得到的token:" + token);
//
// localStorage.setItem("token", token);
// window.location.href = "./index.jsp";
// }
// }
// })
// })
</script>
</body>
</html>
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot_demo</name>
<description>springboot_demo</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--====================JWT===============================-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>