GVKun编程网logo

springmvc - 关于Controller中方法参数类型的几点注意(spring mvc controller 参数)

19

如果您想了解springmvc-关于Controller中方法参数类型的几点注意和springmvccontroller参数的知识,那么本篇文章将是您的不二之选。我们将深入剖析springmvc-关于

如果您想了解springmvc - 关于Controller中方法参数类型的几点注意spring mvc controller 参数的知识,那么本篇文章将是您的不二之选。我们将深入剖析springmvc - 关于Controller中方法参数类型的几点注意的各个方面,并为您解答spring mvc controller 参数的疑在这篇文章中,我们将为您介绍springmvc - 关于Controller中方法参数类型的几点注意的相关知识,同时也会详细的解释spring mvc controller 参数的运用方法,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

springmvc - 关于Controller中方法参数类型的几点注意(spring mvc controller 参数)

springmvc - 关于Controller中方法参数类型的几点注意(spring mvc controller 参数)

简单类型

1、当controller方法中的参数类型为基本数据类型时。如果页面提交过来的数据为null或"",会出现数据转换的异常。
IllegalStateException

2、当controller方法中的参数类型为基本数据类型的包装类型时,页面传递过的数据可以为"",null或无该参数提交。当此方法执行时,该包装类型参数自动设为null(包装类可以设为null)。如果被其他方法调用可能抛空指针异常。比如Controller方法中存在一个Long parentId 参数,如果页面没有提交该参数。则parentId自动被设置为null。

注意,如果使用值为null 的包装类型进行拆包时,会抛空指针异常。当将parentId(null)作为参数传递到某方法中时(该方法中的参数为基本数据类型),编译时不会抛异常。但是运行时,此包装类型的参数(null)会进行拆包,此时会抛空指针异常!此异常为运行时异常。当然,如果直接将此parentId与基本数据类型运算,同样也会抛空指针异常。

null的拆包

参考

总结:
1、如果使用基本数据类型,无法接受null值和""值。可能发生数据转换异常;
2、 如果使用包装类型,可以接受null值和""值,但是可能在参数传递时发生空指针异常。解决办法是在此变量在方法间传递时,全部使用包装类型。这样,此参数可以接收页面传递的""或null值。这样,调用此参数发生异常时,会在问题位置抛出。

java – 在SpringMVC中将@Controller中的变量传递给@ControllerAdvice

java – 在SpringMVC中将@Controller中的变量传递给@ControllerAdvice

我创建了@ControllerAdvice,它必须为我设置一些模型属性.

@modelattribute
public void globalAttributes(Model model) {
       model.addAttribute("pageId",PAGE_ID);
}

这是我需要的一般示例,PAGE_ID表示实际控制器必须设置的一些变量.由于@ControllerAdvice在控制器之前运行,我如何声明这个变量并在Advice中使用它?如果这是可能的.

解决方法

我认为更好的解决方案是为控制器使用某种抽象类模式

public abstract class AbstractController {

    @modelattribute
    public void globalAttributes(Model model) {
       model.addAttribute("pageId",getPageId());
    }

    abstract String getPageId();
}

public class MyController extends AbstractController {

    @Override
    public String getPageId() {
       return "MyPageID"
    }

    //..your controller methods
}

Spring MVC Controller中如何使用JUnit返回类型的方法

Spring MVC Controller中如何使用JUnit返回类型的方法

我在Spring MVC控制器上执行junit-

@RequestMapping(value = "index",method = RequestMethod.GET)
    public HashMap<String,String> handleRequest() {
    HashMap<String,String> model = new HashMap<String,String>();
    String name = "Hello World";
    model.put("greeting",name);

    return model;
}

下面是我的上述方法的junit-

public class ControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
    this.mockMvc = standaloneSetup(new Controller()).build();
    }

    @Test
    public void test01_Index() {

    try {
        mockMvc.perform(get("/index")).andExpect(status().isOk());

    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

以上junit工作正常..

但是我的问题是我该如何将返回类型handleRequest返回HashMap带有键和值对的junit 。如何验证它是否正在返回Hello World?是否有任何方法可以做到这一点?

spring mvc 关于 jsp 页面传递到 controller 层参数类型转换(格式化)的学习记录 --2018 年 1 月

spring mvc 关于 jsp 页面传递到 controller 层参数类型转换(格式化)的学习记录 --2018 年 1 月


spring mvc jsp 传递参数到 controller 涉及到日期类型数据,需要使用到类型转换器:
目前笔者找到两种类型转换器可以使用:
  类型一:实现 Convert<Source,Target> 接口的方式(Source 源数据,Target 目标数据类型),实现功能是一种数据类型到另一种数据类型:
数据转换类如下:在不添加 DateTimeFormatter.ofPattern ("yyyy/MM/dd") 时 (MM 必须大写,小写表示时间分),默认需要输入的 String 样式 “yyyy-MM-dd”
  public class StringToLocalDate implements Converter<String,LocalDate>  //String 转换为 LocalDate
  {
    @Override
    public LocalDate convert(String s)
    {
      return LocalDate.parse(s,DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    }
  }
spring-servlet.xml 配置如下:在 mvc:annoation-driven 内部 conversion-service 默认装配的 bean 为 FormattingConversionServiceFactoryBean,所以在使用 convert 时需要显示的设置该 conversion-service 对应的 bean 为 ConversionServiceFactoryBean

  <mvc:annotation-driven conversion-service="conversionService" />
<!-- 注册自定义数据类型转换器工厂,并添加自定义的转换器 bean-->
  <beanid="conversionService">
    <property name="converters">
      <set>
        <bean/>   //StringToLocalDate 是自定义的类型转换器
      </set>
    </property>
  </bean>
到此借用 convert 实现自定义转换器,需要实现的接口以及需要配置的地方全部完成,可以将 Source 类型转换成 Target 类型了。此处笔者使用的是 String 转换成 LocalDate 作为示例;


  类型二:使用 FormattingConversionServiceFactoryBean 格式化转换,此处可以使用注解简单的转换,也可以使用自定义类方法转换
  注解转换:
需要在 Pojo 实体的属性上使用注解,笔者使用 LocalDate 做示例,故需要在数据类型为 LocalDate 的变量上添加注解如下:
  import org.springframework.format.annotation.DateTimeFormat;  // 导入该注解对应的包
  @DateTimeFormat(pattern="yyyy-MM-dd")  //pattern 是设置传入 String 的样式类型,非此样式类型的 String 不能转换成目标类型 LocalDate
  private LocalDate releaseDate;    // 发布日期
由于 mvc:annoation-driven 内部默认就是 FormattingConversionServiceFactoryBean 该工厂,所以无需显示的设置 conversion-service,
  <mvc:annotation-driven />
建议还是显示的设置一下
  <mvc:annotation-driven conversion-service="conversionService2" />
  <beanid="conversionService2"/>
至此注解转换需要完成的配置等已完成;

  自定义类转换:
需要创建一个自定义转换类并实现 Formatter<T> 接口,如下:
  public class LocalDateFormatterForDash implements Formatter<LocalDate>
  {
    /* 声明一个日期时间格式化的属性 */
    private DateTimeFormatter dateTimeFormatter;
    /* 声明一个字符串作为格式化的样式 */
    private String datePattern;
    /* 创建构造器用以初始化时获取需要转换的 String 样式 datePattern,并根据该 datePattern 样式生成一个 DateTimeFormatter 对象 */
    public LocalDateFormatterForDash(String datePattern)
    {
      this.datePattern=datePattern;
      dateTimeFormatter=DateTimeFormatter.ofPattern(datePattern);
    }
    /* 重写接口提供的方法,将源字符串数据 source 转换成目标数据类型 LocalDate,local 是本地化 */
    @Override
    public LocalDate parse(String source, Locale locale) throws ParseException
    {
      /* 将符合 datePattern 样式的 String 转化为 LocalDate 并返回 */
      LocalDate localDate=LocalDate.parse(source,dateTimeFormatter);
      return localDate;
    }
    /* 将 LocalDate 转换成字符串 */
    @Override
    public String print(LocalDate localDate, Locale locale)
    {
      return localDate.format(dateTimeFormatter);
    }
  }

自定义转换器类以及声明并编辑完成,接下来需要让 spring 来让其发挥作用:
有两种方法:
一是将该类直接添加到 FormattingConversionServiceFactoryBean如下:
  <mvc:annotation-driven conversion-service="conversionService" />
  <beanid="conversionService">
    <!-- 添加自定义 formatter 到 formatter 仓库中 -->
    <property name="formatters">
      <set>
        <bean>
          <!-- 构造器注入 String 样式 yyyy/MM/dd-->
          <constructor-arg name="datePattern" value="yyyy/MM/dd"/>
        </bean>
      </set>

    </property>

  </bean>
到此直接添加方式已完成相关配置;
二是将该类添加到 MyFormatterRegistrar 注册类中,在该类中完成注册
MyFormatterRegistrar 注册类实现 FormatterRegistrar 该接口
  public class MyFormatterRegistrar implements FormatterRegistrar
  {
    /* 声明需要转换 String 的样式 */
    private String dataPatternForDash;
    /* 构造器 */
    public MyFormatterRegistrar(String dataPatternForDash)
    {
      this.dataPatternForDash=dataPatternForDash;
    }

    @Override
    public void registerFormatters(FormatterRegistry formatterRegistry)
    {
      /* 将创建的自定义类转换器注册(添加)到注册类中,完成注册(以注册类中的样式)*/
      formatterRegistry.addFormatter(new LocalDateFormatterForDash(dataPatternForDash));
    }
  }
xml 配置:
  <mvc:annotation-driven conversion-service="conversionService" />
  <beanid="conversionService">
    <!-- 将注册类添加到 FormattingConversionServiceFactoryBean-->
    <property name="formatterRegistrars">
      <set>
        <!-- 初始化自定义注册类时,并传入 String 样式 -->
        <bean>
          <constructor-arg name="dataPatternForDash" value="yyyy-MM-dd"/>
        </bean>
      </set>
    </property>
  </bean>
到此借助注册类的方式已经完成相关配置;想分享的数据类型转换的几种方式已经分享完毕,如有纰漏望指正;
ps:自定义转换器针对同一种目标数据类型(如:针对 LocalDate 自定义了多个转换器)spring 默认会使用 xml 配置中的最后一个转换器执行转换操作。

Spring MVC 关于controller的字符编码问题

Spring MVC 关于controller的字符编码问题

<div id="cnblogs_post_body"><div id="content"> <p>在使用springMVC框架构建web应用,客户端常会请求字符串、整型、json等格式的数据,通常使用@ResponseBody注解使 controller回应相应的数据而不是去渲染某个页面。如果请求的是非英文格式的字符串,往往在客户端显示的是乱码。原因是spring的 StringHttpMessageConverter默认的字符类型是iso8895-1 ‘西欧语言'',中文等字符需要单独指定。</p> <p><strong>这里总结几种解决方案:</strong><br> </p> <p>1.不使用@ResponseBody注解,使用HttpServeletResponse设置contentType属性</p> <div> <div><div id="highlighter_80537"><div><span><a href="#">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div></td><td><div><div><code>@RequestMapping</code><code>(value =</code><code>"/rest/create/document"</code><code>) </code></div><div><code>public</code> <code>void</code> <code>create(Document document, HttpServletRespone respone) { </code></div><div><code>repoonse.setContentType(</code><code>"text/plain;charset=''utf-8''"</code><code>); </code></div><div><code>response.write(</code><code>"中文string"</code><code>); </code></div><div><code>}</code></div></div></td></tr></tbody></table></div></div> </div> <p>2.返回Response Entity object,设置contentType,例:</p> <div> <div><div id="highlighter_112060"><div><span><a href="#">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div></td><td><div><div><code>@RequestMapping</code><code>(value = </code><code>"/rest/create/document"</code><code>) </code><code>public</code> <code>ResponseEntity&lt;String&gt; create(Document document, HttpServletRespone respone) { </code></div><div><code>HttpHeaders responseHeaders = </code><code>new</code> <code>HttpHeaders(); responseHeaders.add(</code><code>"Content-Type"</code><code>, </code><code>"text/html; charset=utf-8"</code><code>); </code></div><div><code>Document newDocument = DocumentService.create(Document); </code></div><div><code>String json = jsonSerializer.serialize(newDocument); </code></div><div><code>return</code> <code>new</code> <code>ResponseEntity&lt;String&gt;(json, responseHeaders, HttpStatus.OK); </code></div><div><code>}</code></div></div></td></tr></tbody></table></div></div> </div> <p>3.使用produces属性:</p> <div> <div><div id="highlighter_996625"><div><span><a href="#">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div></td><td><div><div><code>@RequestMapping</code><code>(value = </code><code>"/rest/create/document"</code><code>,produces= </code><code>"text/plain;charset=UTF-8"</code><code>) </code><code>//返回的内容类型</code></div><div><code>@ResponseBody</code></div><div><code>public</code> <code>String create(Document document, HttpServletRespone respone) </code><code>throws</code> <code>UnsupportedEncodingException { </code></div><div><code>Document newDocument = DocumentService.create(Document); </code></div><div><code>return</code> <code>jsonSerializer.serialize(newDocument); </code></div><div><code>}</code></div></div></td></tr></tbody></table></div></div> </div> <p><strong>@RequestMapping</strong></p> <p>参数绑定(@RequestParam、 @RequestBody、 @RequestHeader 、 @PathVariable)</p> <div> <div><div id="highlighter_580602"><div><span><a href="#">?</a></span></div><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div><div>10</div><div>11</div><div>12</div><div>13</div><div>14</div><div>15</div><div>16</div><div>17</div><div>18</div><div>19</div><div>20</div><div>21</div><div>22</div><div>23</div><div>24</div><div>25</div><div>26</div><div>27</div><div>28</div><div>29</div></td><td><div><div><code>package</code> <code>org.springframework.web.bind.annotation;</code></div><div>&nbsp;</div><div><code>import</code> <code>java.lang.annotation.Documented;</code></div><div><code>import</code> <code>java.lang.annotation.ElementType;</code></div><div><code>import</code> <code>java.lang.annotation.Retention;</code></div><div><code>import</code> <code>java.lang.annotation.RetentionPolicy;</code></div><div><code>import</code> <code>java.lang.annotation.Target;</code></div><div><code>import</code> <code>org.springframework.web.bind.annotation.Mapping;</code></div><div><code>import</code> <code>org.springframework.web.bind.annotation.RequestMethod;</code></div><div>&nbsp;</div><div><code>@Target</code><code>({ElementType.METHOD, ElementType.TYPE})</code></div><div><code>@Retention</code><code>(RetentionPolicy.RUNTIME)</code></div><div><code>@Documented</code></div><div><code>@Mapping</code></div><div><code>public</code> <code>@interface</code> <code>RequestMapping {</code></div><div><code>&nbsp;&nbsp;</code><code>String name() </code><code>default</code> <code>""</code><code>;</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>String[] value() </code><code>default</code> <code>{};</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>RequestMethod[] method() </code><code>default</code> <code>{};</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>String[] params() </code><code>default</code> <code>{};</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>String[] headers() </code><code>default</code> <code>{};</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>String[] consumes() </code><code>default</code> <code>{};</code></div><div>&nbsp;</div><div><code>&nbsp;&nbsp;</code><code>String[] produces() </code><code>default</code> <code>{};</code></div><div><code>}</code></div></div></td></tr></tbody></table></div></div> </div> <p>RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。</p> <p><strong>RequestMapping注解有六个属性。</strong></p> <p>1、value, method;<br> </p> <p>value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);<br> </p> <p>method: 指定请求的method类型, GET、POST、PUT、DELETE等;</p> <p>2、consumes,produces;<br> </p> <p>consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;<br> </p> <p>produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;</p> <p>3、params,headers;<br> </p> <p>params: 指定request中必须包含某些参数值是,才让该方法处理。<br> </p> <p>headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。<br> </p> <p>以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。</p>

<div> <span id="art_bot"></span> </div> </div> </div>

今天关于springmvc - 关于Controller中方法参数类型的几点注意spring mvc controller 参数的介绍到此结束,谢谢您的阅读,有关java – 在SpringMVC中将@Controller中的变量传递给@ControllerAdvice、Spring MVC Controller中如何使用JUnit返回类型的方法、spring mvc 关于 jsp 页面传递到 controller 层参数类型转换(格式化)的学习记录 --2018 年 1 月、Spring MVC 关于controller的字符编码问题等更多相关知识的信息可以在本站进行查询。

本文标签: