SpringMVC

2021-11-19  本文已影响0人  抬头挺胸才算活着
@Controller
public class MyController {
    @RequestMapping(value = "/my-handler-path", method = RequestMethod.GET)
    public String myHandlerMethod(...) {
       .....
    }
}
@Controller
public class MyMvcController {
    @RequestMapping(value = "/my-uri-path")
    public String prepareView(Model model) {
       model.addAttribute("msg", "msg-value");
        .....
    }
}
@Configuration
public class MyWebConfig {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver =
                      new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}
@EnableWebMvc
@Configuration
public class MyWebConfig {
 .....
}

@EnableWebMvc的类引入了DelegatingWebMvcConfiguration,是WebMvcConfigurationSupport的子类。

package org.springframework.web.servlet.config.annotation;
 ...
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

DelegatingWebMvcConfiguration在setConfigurers方法中注入了WebMvcConfigurer,因此我们如果有在配置类中定义这类实例,也会注入到在里面

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
   .....
  @Autowired(required = false)
  public void setConfigurers(List<WebMvcConfigurer> configurers) {
    if (!CollectionUtils.isEmpty(configurers)) {
        this.configurers.addWebMvcConfigurers(configurers);
    }
  }
}
@EnableWebMvc
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
  .....
   @Override
    public void addViewControllers (ViewControllerRegistry registry) {
        //our customization
    }
  ...
 }

上面的配置类会被注入到DelegatingWebMvcConfiguration的configurers。

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
   .....
  @Autowired(required = false)
  public void setConfigurers(List<WebMvcConfigurer> configurers) {
    if (!CollectionUtils.isEmpty(configurers)) {
        this.configurers.addWebMvcConfigurers(configurers);
    }
  }
}

在配置阶段DelegatingWebMvcConfiguration会调用addViewControllers进行配置类配置。

 @Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    ...
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
       this.configurers.addViewControllers(registry);
    }
    ...
}
 @RequestMapping("/users")
 @Controller
 public class UserController{
   @RequestMapping("/{userId}")
    public String handle(....){
     ....
    }
 }

路径参数可以被捕获到方法的输入参数

    @RequestMapping("/{userId}")
    public void handle(@PathVariable("userId") String userId) {
            // ...
    }

下面的用法中方法也要加上RequestMapping,不然会报404,@RequestMapping("")和@RequestMapping都会映射“/”路径。

 @Controller
 @RequestMapping("/users")
 public class UserController {

  @RequestMapping
  public String handleAllUsersRequest(){
        .....
  }
 }

元素method可以是RequestMethod.GET、RequestMethod.DELETE
元素params是链接问号后面的内容是否包含该元素
元素headers是HTTP协议的头元素
元素consumes是多媒体类型

 public class Trade {

    private String buySell;
    private String buyCurrency;
    private String sellCurrency;

    public String getBuySell () {
        return buySell;
    }

    public void setBuySell (String buySell) {
        this.buySell = buySell;
    }

   .................
}

@Controller
@RequestMapping("trades")
public class TradeController {
    @RequestMapping
    public String handleTradeRequest (Trade trade,
                                      Model map) {
        String msg = String.format(
                          "trade request. buySell: %s, buyCurrency: %s, sellCurrency: %s",
                           trade.getBuySell(), trade.getBuyCurrency(),
                           trade.getSellCurrency());
        map.addAttribute("msg", msg);
        return "my-page";
    }

将路径变量/trades/buy/EUR/USD映射到Trade trade变量

@Controller
@RequestMapping("trades")
public class TradeController {

    @RequestMapping("{buySell}/{buyCurrency}/{sellCurrency}")
    public String handleTradeRequest (Trade trade, Model map) {
        String msg = String.format(
                           "trade request. buySell: %s, buyCurrency: %s, sellCurrency: %s",
                           trade.getBuySell(), trade.getBuyCurrency(),
                           trade.getSellCurrency());

        map.addAttribute("msg", msg);
        return "my-page";
    }
}
public class TradeIdToTradeConverter implements Converter<String, Trade> {

    private TradeService tradeService;

    public TradeIdToTradeConverter (TradeService tradeService) {
        this.tradeService = tradeService;
    }

    @Override
    public Trade convert (String id) {
        try {
            Long tradeId = Long.valueOf(id);
            return tradeService.getTradeById(tradeId);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}
@Controller
public class EmployeeController {
    .............
  @RequestMapping("/employee3")
  @ResponseBody
  public String getEmployeeByDept3 (@RequestParam("dept") Optional<String> deptName) {
      return "test response for dept: " + (deptName.isPresent() ? deptName.get() :
                "using default dept");
  }
}
  @Scope(WebApplicationContext.SCOPE_SESSION)
  public Visitor visitor(HttpServletRequest request){
       return new Visitor(request.getRemoteAddr());
  }

Controller中获取

@Controller
@RequestMapping("/trades")
public class TradeController {

  @Autowired
  private Provider<Visitor> visitorProvider;

  @RequestMapping("/**")
  public String handleRequestById (Model model, HttpServletRequest request) {
      model.addAttribute("msg", "trades request, serving page " + request.getRequestURI());
      visitorProvider.get()
                     .addPageVisited(request.getRequestURI());
      return "traders-page";
  }
}

2、在Controller方法中写HttpSession httpSession
3、通过@Autowired

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class VisitorInfo implements Serializable {
  private String name;
  private int visitCounter;
  private LocalDateTime firstVisitTime;
  //getters/setters
    .............
}
    @ModelAttribute("time")
    public LocalDateTime getRequestTime () {
        return LocalDateTime.now();
    }
上一篇下一篇

猜你喜欢

热点阅读