SpringBoot通过@RequestParam接收前端表单传来的数据

就像这样的界面在前台向控制器中传输数据,
SpringBoot通过@RequestParam接收前端表单传来的数据_第1张图片
使用功能form表单进行传值,使用@RequestParam注解在控制器中接收传过来的值,注意,name属性一定要和控制器中的@RequestParam相同 要不然接收不到还报错

HTML中页面代码:

<div class="panel admin-panel margin-top" id="add">
    <div class="panel-head"><strong><span class="icon-pencil-square-o">span> 增加内容strong>div>
    <div class="body-content">
        <form method="post" class="form-x" th:action="@{/targetAdd}">
            <div class="form-group">
                <div class="label">
                    <label>创建库类型:label>
                div>
                <div class="field">
                    <select name="lib_type" id="lib_type" class="input w50" data-validate="required:请选择创建库的类型" >
                        <option th:value="1">黑名单库option>
                        <option th:value="2">白名单库option>
                    select>
                    
                    <div class="tips">div>
                div>
            div>
            <div class="form-group">
                <div class="label">
                    <label>填写库名称:label>
                div>
                <div class="field">
                    <input type="text" class="input w50" name="lib_name" value=""  />
                    <div class="tips">div>
                div>
            div>
            <div class="form-group">
                <div class="label">
                    <label>label>
                div>
                <div class="field">
                    <button class="button bg-main icon-check-square-o" type="submit"><input class="button bg-main icon-check-square-o" type="submit" name="sub" value="提交" />button>
                div>
            div>
        form>
    div>
div>

控制器接收代码:

 @RequestMapping("/targetAdd")
    public String targetAdd(@RequestParam(value = "lib_name",required = false) String lib_name,
                            @RequestParam(value = "lib_type",required = false) String lib_type) throws IOException{
        if(null!=lib_name){
            String msg_id = "1025";
            String postUrl = "http://192.168.4.10:80/api/json";
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("msg_id", msg_id);
            map.put("lib_name", lib_name);
            map.put("lib_type", Integer.parseInt(lib_type));
            JSONObject jsonMap = JSONObject.fromObject(map);
            String jsn = PostDemo.sendPost(postUrl, jsonMap, "utf-8");
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(jsn);
        return "targetAdd";
    }

里面的required=false表示非必须存在的,忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错,如果不写默认的是true,在运行注入的时候,该bean必须存在,否则就会注入失败,没有的的话就直接报错的哦!!!

你可能感兴趣的:(Spring,Boot)