赞
踩
@RestController
public class Hello {
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
server.port = 8080
spring.mvc.static-path-pattern=/static/**
spring.web.resources.static-locations=classpath:/static/
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
@PostMapping("/up") public String upload(MultipartFile f) throws IOException { System.out.println(f.getSize()); System.out.println(f.getContentType()); System.out.println(f.getOriginalFilename()); saveFile(f); return "上传成功"; } public void saveFile(MultipartFile f) throws IOException { File upDir = new File("E:\\2.Study\\SpringBoot2\\photos\\"); if (!upDir.exists()){ upDir.mkdir(); } File file = new File("E:\\2.Study\\SpringBoot2\\photos\\" + f.getOriginalFilename()); f.transferTo(file); }
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("登录拦截器");
return true;
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 仅拦截user路径下的所有资源
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**");
}
}
@GetMapping("/user/{id}") public String getUserById(@PathVariable String id){ return "查询用户"; } @PostMapping("/user") public String save(User user){ return "保存用户"; } @PutMapping("/user") public String update(User user){ return "更新用户"; } @DeleteMapping("/user/{id}") public String DeleteUserById(@PathVariable String id){ return "删除用户"; }
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration//告诉Spring容器,这个类是一个配置类 @EnableSwagger2//启Swagger2功能 public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com")) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("演示项目API") .description("学习xxx的项目") .build(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
配置解决springboot和swagger的冲突
# 解决springboot与Swagger的冲突
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.31</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.17</version> </dependency>
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=mzk
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 开启驼峰命名
mybatis-plus.configuration.map-underscore-to-camel-case=true
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Override
public String getAllUser() {
return userMapper.selectList(null).toString();
}
@GetMapping("/findAll")
public IPage findAll(){
Page page = new Page(1,2);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Page IPage = userService.page(page, queryWrapper);
return IPage;
}
npm install element-ui
import ElementUI from 'element-ui';
Vue.use(ElementUI)
npm install font-awesome
import 'font-awesome/css/font-awesome.min.css'
使用webStorm新建项目后,把 .lock文件删除后项目运行才不报错,配置文件 vue.config.js 中加入 lintOnSave: false 关闭eslint语法检测
npm install axios
created() {
axios.get('/user').then(response => {
this.movies = response.data;
console.log(this.movies)
})
},
在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求。此时会遇到如下两个问题:
//配置请求根路径
axios.defaults.baseURL = 'http://api.com'
//将ax1os作为全局的自定义属性,每个组件可以在内部直接访问(Vue3)
app.config.globalProperties.$http = axios
//将axios作为全局的自定义属性,每个组件可以在内部直接访问(Vue2)
Vue.prototype.$http = axios
跨域问题,多种解决方法,需要时可百度
其中一种解决CORS 的方法, 在springboot项目中跨域的方法或类加上@CrossOrigin注解
npm install vue-router@3
<template> <div id="app"> <!-- 声明路由链接--> <router-link to="/discover">发现音乐</router-link> <br> <router-link to="/my">我的</router-link> <br> <router-link to="/friends">朋友</router-link> <br> <button @click="toDiscover">跳转发现音乐</button> <!-- 声明路由占位标签--> <router-view></router-view> </div> </template> <script> export default { name: 'App', components: {}, methods: { toDiscover: function () { // 编程式导航 上面的为声明式,跳转同一页面会报错,所以catch this.$router.push('/discover').catch(error => error) } } } </script>
route.js
Vue.use(VueRouter) const router = new VueRouter({ // 指定hash属于与组件的对应关系 routes: [ {path: '/', redirect: '/my'}, {path: '/discover', component: Discover}, { path: '/friends', component: Friends, children: [ {path: ":id", component: f, props:true}// props:true 表面以参数形式传参 ], }, { path: '/my', component: My, children: [ {path: 'son1', component: my_son1}, {path: 'son2', component: my_son2} ] } ] }) export default router
main.js
import router from "@/router";
new Vue({
render: h => h(App),
router : router
}).$mount('#app')
导航守卫
router.beforeEach((to, from, next) => {
if(to.path === '/main' && !isAuthenticated){
next('/login')
}
else{
next()
}
})
对于组件化开发来说,大型应用的状态往往跨越多个组件。在多层嵌套的父子组件之间传递状态已经十分麻烦,而Vue更是没有为兄弟组件提供直接共享数据的办法。
基于这个问题,许多框架提供了解决方案——使用全局的状态管理器,将所有分散的共享数据交由状态管理器保管,Vue也不例外。
npm install vuex@ + 版本号
store.js
import Vuex from "vuex"; import Vue from "vue"; Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0, todos: [ {id: 1, text: '吃饭', done: true}, {id: 2, text: '睡觉', done: false} ] }, mutations: { increment(state, n) { state.count += n; } }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } }) export default store
main.js
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store: store
}).$mount('#app')
hello.vue
<template> <div class="hello"> <!-- <h1>{{this.$store.state.count}}</h1>--> {{ count }} <button @click="addOne">+1</button> <span v-for="todo in doneTodos" :key="todo.id">{{ todo.text }}</span> </div> </template> <script> import {mapState, mapGetters} from 'vuex' export default { name: 'HelloWorld', computed: { ...mapState([ 'count', 'todos' ]), ...mapGetters([ 'doneTodos' ]) }, // computed:{ // count(){ // return this.$store.state.count // } // }, methods: { addOne() { this.$store.commit('increment', 2); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Session认证
互联网服务离不开用户认证。一般流程是下面这样。
Token认证
Token 是在服务端产生的一串字符串,是客户端访问资源接口(API)时所需要的资源凭证,流程如下:
JWT
JWT 的由三个部分组成,依次如下:
三部分最终组合为完整的字符串,中间使用 . 分隔,如下:
加入依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
生成token
//7天过期 private static Long expire 604800; //32位秘钥 private static String secret "abcdfghiabcdfghiabcdfghiabcdfghi"; //生成token public static String generateToken(String username){ Date now new Date(); Date expiration new Date(now.getTime() + 1000 * expire); return Jwts.builder() .setHeaderParam("type","JWT") .setSubject(username) .setIssuedAt(now) .setExpiration(expiration) .signwith(SignatureAlgorithm.HS512,secret) .compact(); }
解析Token
//解析token
public static Claims getclaimsByToken(String token){
return Jwts.parser()
.setsigningKey(secret)
.parseclaimsJws(token)
.getBody();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。