springboot web & 增加不存在的url返回200状态码& vue 打包设置&vue.js 单文件使用

spring boot项目增加 html web页面访问

1. 首先 application.properties 文件中增加配置,指定静态资源目录(包括html的存放)

spring.resources.static-locations=classpath:/webapp/,classpath:/webapp/static/

2. 项目目录

3. 如果有实现 WebMvcConfigurer  类的,增加实现

package yourpack;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * @author wangtong
 */
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {
    @Autowired
    private YourInterceptor yourint;// 拦截器

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(yourint).addPathPatterns("/url").addPathPatterns("/url2");// 不设置拦截器的可以不实现该方法
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController("/").setStatusCode(HttpStatus.OK);
        registry.addViewController("/index.jsp").setViewName("index"); // 配置首页
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/404").setViewName("404"); // 配置404页面
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 设置静态资源目录
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/webapp/static/")
                .addResourceLocations("classpath:/resources/webapp/static/");
    }
}

如果访问不到页面的,可以检查下application配置文件是否有以下配置

#spring.web.resources.add-mappings=false
#spring.resources.add-mappings=false
spring.mvc.view.suffix=.html

如果有的话,需要进行注释。这两个配置都是不进行静态资源的映射。所以会导致html等无法访问。

增加spring boot web不存在的url返回200状态码

1. application配置文件增加以下配置

spring.mvc.throw-exception-if-no-handler-found=true

2. 增加一个error配置类的实现

package ;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;


@Configuration
public class ErrorConfig implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage[] errorPages = new ErrorPage[1];
        errorPages[0] = new ErrorPage(HttpStatus.NOT_FOUND, "/404.do");
        registry.addErrorPages(errorPages);
    }
}

3. 增加一个mapping

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

    @RequestMapping(value = {"/404.do"})
    public ResponseEntity<Map<String, String>> error() {
        Map<String, String> retMap = new HashMap<>();
        retMap.put("message", "请求路径不存在");
        return new ResponseEntity<Map<String, String>> (retMap, HttpStatus.OK);
    }

访问一下

vue 打包配置:

1. main.js 配置 axios相关,这里没有进行增加前缀路由,注释调的api是增加的,但是打包后,访问的页面里面也加上了,不知道为什么,所有就去掉吧

// var baseURL = '/api';
var baseURL = 'http://localhost:8080';
axios.interceptors.request.use(config=>{
  config.baseURL= baseURL;
  config.headers.post["Origin"] = baseURL;
  config.headers.post["Referer"] = baseURL;
  return config;
});
axios.defaults.withCredentials = true;
axios.defaults.headers.post["Origin"] = baseURL;
axios.defaults.headers.post["Referer"] = baseURL;

Vue.prototype.$request=axios;

2. package.json 文件, scripts 中没有build的可以增加一个,如果执行 npm run build 报错的,可以改成build+后缀的其它。 我这里的话 npm run buildt

{
  "name": "vue-admin-template",
  "version": "4.4.0",
  "description": "A vue admin template with Element UI & axios & iconfont & permission control & lint",
  "author": "",
  "scripts": {
    "dev": "vue-cli-service serve",
    "build:prod": "vue-cli-service build",
    "buildt": "npm install && vue-cli-service build",
    "preview": "node build/index.js --preview",
    "svgo": "svgo -f src/icons/svg --config=src/icons/svgo.yml",
    "lint": "eslint --ext .js,.vue src",
    "test:unit": "jest --clearCache && vue-cli-service test:unit",
    "test:ci": "npm run lint && npm run test:unit"
  },

3. vue.config.js文件

module.exports = {
  publicPath: '/',
  outputDir: '../your-web/src/main/resources/webapp',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: 2234,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // proxy: { 
    //   '/api': { 
    //     target: 'http://localhost:8080',
    //     ws: true,
    //     changeOrigin: true ,
    //     pathRewrite:{
    //       '^/api':''
    //     }
    //   } 
    // }
  },

这里的话,axios没有设置前缀,所以这里的路由也就不需要了。注释掉。

outputDir  要输出的目录路径,这里的话,我这里打包的不在当前这个目录下面。

生成到和当前node父目录同层的指定目录下。

elementUi 单vue.js 文件使用

页面效果:

由于简单点,就直接都引入到一个html了

index.html



<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/qs/6.5.1/qs.min.js"></script>
</head>
<script type="module">

</script>
<body>
<div id="app">
<!--    <el-button @click="visible = true">Button</el-button>-->
<!--    <el-dialog :visible.sync="visible" title="Hello world">-->
<!--        <p>Try Element</p>-->
<!--    </el-dialog>-->

    <el-form ref="form" :model="form" label-width="120px">

        <el-form-item label="select url">
            <el-select v-model="form.region" @change="changeName" placeholder="please select your zone">
                <el-option
                        v-for="item in serviceUrl"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="url">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="select url">
            <el-select v-model="form.encryptionType" placeholder="please select encryptionType">
                <el-option
                        v-for="item in encryType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="type">
            <el-radio-group v-model="form.resource">
                <el-radio label="post" key="post" />
                <el-radio label="get" key="get" disabled />
            </el-radio-group>
        </el-form-item>
        <el-form-item label="privateKey">
            <el-input v-model="form.privateKey" />
        </el-form-item>
        <el-form-item label="service">
            <el-input v-model="form.service" />
        </el-form-item>
        <el-form-item label="merchantName">
            <el-input v-model="form.merchantName" />
        </el-form-item>
        <el-form-item label="dataContent">
            <el-input v-model="form.dataContent" type="textarea" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" :disabled="loading" @click="onSubmit">提交</el-button>
            <el-button @click="onCancel">Cancel</el-button>
        </el-form-item>
    </el-form>

    <div description="描述文字">
        <span>调用结果</span>

        <p v-html="result" ></p>

    </div>
</div>

</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>

    new Vue({
        el: '#app',
        data: function() {
            return {
                form: {
                    name: 'openapi/fsddg/v1',
                    region: 'openApi',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    privateKey: 'gawegsfew',
                    resource: 'post',
                    encryptionType: 'md5',
                    service: 'gawdewae',
                    merchantName: 'fewageawwe',
                    requestSeq: "fawegeaw",
                    dataContent: JSON.stringify({
                        "backTrackingDate": "",
                        "bizNo": "20220329000002",
                        "reqParams": {
                            "saasChannelInfo": {
                                "secondLevel": "XW",
                                "thirdLevel": "",
                                "custType": "",
                                "firstLevel": "JC"
                            }
                        },
                        "idNo": "fafwfawefawew",
                        "encryptType": "md5"
                    })
                },
                serviceUrl:[{
                    value: 'openapi/dataservice/v1',
                    label: 'openApi'
                },{
                    value: "sfs/dataservice/v1",
                    label: "dataserviceV1"
                },{
                    value: "sfs/dataservice/v2",
                    label: "dataserviceV2"
                }],
                encryType:[{
                    label:"rsa",
                    value:"rsa"
                },{
                    label: "md5",
                    value: "md5"
                }],
                result: '',
                loading : false,
                visible: false
            }
        },
        methods:{
            onSubmit() {
                this.loading = false;
                this.$message('submit!')
                const form = this.form;

                var params = {
                    "dataContent": form.dataContent,
                    "service": form.service,
                    "productCode": form.service,
                    "signature": '',
                    "requestSeq": form.requestSeq,
                    "encryptionType": form.encryptionType,
                    "privateKey": form.privateKey,
                    "merchantSecret": "123456",
                    "merchantName": form.merchantName
                };

                var paramsStr = Qs.stringify(params);
                var th = this;
                axios.post('sfs/getSe', paramsStr).then((response) =>{
                    console.log('获取sign成功', response);
                    if(response.status == 200){
                        params["signature"] = response.data;
                        paramsStr = Qs.stringify(params);
                        console.log("入参", params)
                        axios.post(form.name, paramsStr).then((response) => {
                            console.log(response.data);
                            th.result = response.data;
                        }).catch(function (error) { // 请求失败处理
                            console.log(error);
                        });;
                    }

                }).catch(function (error) { // 请求失败处理
                    console.log(error);
                });;

            },
            changeName(){
                this.form.name = this.form.region;
            },
            onCancel() {
                this.$message({
                    message: 'cancel!',
                    type: 'warning'
                })
            }
        }
    });

    // service.post('fsagsad', {}).then(response=>{
    //     console.log(response)
    // });
</script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用中的代码中,首先使用module.exports将配置对象导出,然后设置了assetsDir、publicPath、productionSourceMap等选项,以及引入了一些CDN链接来加速优化。这些配置可以根据具体需求进行修改和定制。引用也提供了一些常见的配置选项,如publicPath、assetsDir、outputDir等。这些配置选项可以根据具体需求进行调整。 根据你提供的代码,可以看出你的vue项目中未包含vue.config.js文件。可能的原因有两种: 1. 你的项目中没有创建vue.config.js文件。你可以在项目根目录下手动创建一个vue.config.js文件,并在其中编写你需要的打包配置。 2. 你的vue.config.js文件存在,但是文件路径不正确。请确保vue.config.js文件位于你的Vue项目的根目录下,并确保文件名拼写正确。 请确认以上两点,如仍然无法解决问题,请提供更多细节,以便进一步协助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue项目打包优化及配置vue.config.js文件(实测有用)](https://blog.csdn.net/weixin_46824709/article/details/126034991)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [vue打包文件配置说明vue.config.js](https://blog.csdn.net/weixin_47970316/article/details/126095427)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值