苍穹外卖day06
HttpClient
入门案例Get
@SpringBootTest
public class HttpClientTest {
//通过httpClient发送Get方式的请求
@Test
public void testGET() throws IOException {
//创建http对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
//发送请求,接收响应结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取服务器返回的状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("服务端返回的状态码为:"+statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity);
System.out.println("服务器返回的数据为:"+string);
//关闭资源
response.close();
httpClient.close();
}
}
结果
服务端返回的状态码为:200
服务器返回的数据为:{“code”:1,“msg”:null,“data”:1}
@Test
public void testPOST() throws JSONException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding("utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
CloseableHttpResponse execute = httpClient.execute(httpPost);
int statusCode = execute.getStatusLine().getStatusCode();
System.out.println("响应码为"+statusCode);
HttpEntity entity = execute.getEntity();
System.out.println(entity);
execute.close();
httpClient.close();
}
响应码为200
ResponseEntityProxy{[Content-Type: application/json,Chunked: true]}
微信小程序开发
准备工作
选上不然不能请求了
入门案例
导入vx小程序的前端代码
微信登录
需求分析
/user是用户端发送的请求
第二个user是用户模块
login是登录
controller (jwt登录wx,将获取的openid变成jwt)
@Slf4j
@RestController
@Api(tags = "C端用户相关接口")
@RequestMapping("/user/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private JwtProperties jwtProperties;
@PostMapping("/login")
@ApiOperation("微信登陆")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
log.info("微信用户登录:{}",userLoginDTO.getCode());
User user = userService.wxlogin(userLoginDTO);
//生成jwt令牌
Map<String,Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.USER_ID,user.getId());
String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
UserLoginVO userLoginVO = UserLoginVO.builder()
.id(user.getId())
.openid(user.getOpenid())
.token(jwt)
.build();
return Result.success(userLoginVO);
}
}
Service(通过code在weixin的接口获取用户的openid)
@Service
@Slf4j
public class UserServiceImpl implements UserService {
public static final String WX_LOGIN = "http://api.weixin.qq.com/sns/jscode2session";
@Autowired
private WeChatProperties weChatProperties;
@Autowired
private UserMapper userMapper;
public User wxlogin(UserLoginDTO userLoginDTO) {
//openid每个用户在某个微信公众号或小程序的唯一标识
//要理解 getCode 的 code 是什么,我们需要理解微信用户登录流程。
//微信的 code 是一个临时凭证,用于交换用户的 openid 和 session_key。这个 code 是通过微信客户端发起的登录请求获得的。
String openid = getOpenid(userLoginDTO.getCode());
if(openid == null){
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
//是否已经存在
User user = userMapper.getByOpenid(openid);
//新用户自动注册
if(user == null){
user = User.builder()
.openid(openid)
.createTime(LocalDateTime.now())
.build();
userMapper.insert(user);
}
return user;
}
private String getOpenid(String code){
HashMap<String, String> map = new HashMap<>();
map.put("appid", weChatProperties.getAppid());
map.put("secret",weChatProperties.getSecret());
map.put("js_code",code);
map.put("grant_type","authorization_code");
String json = HttpClientUtil.doGet(WX_LOGIN, map);
JSONObject jsonObject = JSON.parseObject(json);
//用户是否为空
String openid = jsonObject.getString("openid");
return openid;
}
}
openid每个用户在某个微信公众号或小程序的唯一标识
要理解 getCode 的 code 是什么,我们需要理解微信用户登录流程。
微信的 code 是一个临时凭证,用于交换用户的 openid 和 session_key。这个 code 是通过微信客户端发起的登录请求获得的。
后端发送HTTPClients请求POST传输code获取openid
导入商品浏览功能代码
查询分类
<select id="list" resultType="Category">
select * from category
where status = 1
<if test="type != null">
and type = #{type}
</if>
order by sort asc,create_time desc
</select>
将分类的全部查出来
根据分类id查询菜品
@GetMapping("/list")
@ApiOperation("根据分类id查询菜品")
public Result<List<DishVO>> list(Long categoryId) {
Dish dish = new Dish();
dish.setCategoryId(categoryId);
dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
List<DishVO> list = dishService.listWithFlavor(dish);
return Result.success(list);
}
根据分类的id查询菜品有口味要包括口味
public class DishVO implements Serializable {
private Long id;
//菜品名称
private String name;
//菜品分类id
private Long categoryId;
//菜品价格
private BigDecimal price;
//图片
private String image;
//描述信息
private String description;
//0 停售 1 起售
private Integer status;
//更新时间
private LocalDateTime updateTime;
//分类名称
private String categoryName;
//菜品关联的口味
private List<DishFlavor> flavors = new ArrayList<>();
//private Integer copies;
}
public List<DishVO> listWithFlavor(Dish dish) {
List<Dish> dishList = dishMapper.getByCateGroyId(dish);
List<DishVO> dishVOList = new ArrayList<>();
for (Dish d : dishList) {
DishVO dishVO = new DishVO();
BeanUtils.copyProperties(d,dishVO);
//根据菜品id查询对应的口味
List<DishFlavor> flavors = dishFlavorMapper.getById(d.getId());
dishVO.setFlavors(flavors);
dishVOList.add(dishVO);
}
return dishVOList;
}
传dish取查所有categoryid的所有dish吗?为什么不传categoryid取查?。。。
获得所有的dish之后再分别差flavor然后再set进去
根据id查询套餐
@GetMapping("/list")
@ApiOperation("根据分类id查询套餐")
public Result<List<Setmeal>> list(Long categoryId) {
Setmeal setmeal = new Setmeal();
setmeal.setCategoryId(categoryId);
setmeal.setStatus(StatusConstant.ENABLE);
List<Setmeal> list = setmealService.list(setmeal);
return Result.success(list);
}
传setmeal取查所有的list返回
<select id="list" parameterType="Setmeal" resultType="Setmeal">
select * from setmeal
<where>
<if test="name != null"> and name like concat('%',#{name},'%') </if>
<if test="categoryId != null"> and category_id = #{categoryId} </if>
<if test="status != null"> and status = #{status} </if>
</where>
</select>
根据套餐id 查询包含菜品
@GetMapping("/dish/{id}")
@ApiOperation("根据套餐id查询包含的菜品列表")
public Result<List<DishItemVO>> dishList(@PathVariable("id") Long id) {
List<DishItemVO> list = setmealService.getDishItemById(id);
return Result.success(list);
}
根据套餐id查询所有的Dish返回,套餐中的dish是返回的dishitemVO
@Select("select sd.name, sd.copies, d.image, d.description " +
"from setmeal_dish sd left join dish d on sd.dish_id = d.id " +
"where sd.setmeal_id = #{setmealId}")
List<DishItemVO> getDishItemBySetmealId(Long setmealId);
setmeal_dish左外连接dish(需要返回的那个VO)on 左外连接二者的关联键
然后where等于查询条件
bug
真的服了
registry.addInterceptor(jwtTokenUserInterceptor)
.addPathPatterns("user/**")
.excludePathPatterns("/user/user/login")
.excludePathPatterns("/user/shop/status");
注册WebMvc的时候拦截器要user/* * 而不是、user/ **