本文介绍了SpringBoot 中使用JSP的方法示例,分享给大家,具体如下:

依赖:

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

示例代码:

  @RequestMapping(value = "/register", method = RequestMethod.GET)
  @ResponseBody
  public String register(){

    return "user register";
  }

  /** @GetMapping 是Spring 4.3 的新特性 */
  @GetMapping("getUser")
  @ResponseBody
  public String getUser(){

    return "user get";
  }

  /** @PostMapping 也是Spring 4.3 的新特性 */
  @PostMapping("createUser")
  @ResponseBody
  public String createUser(){

    return "user create";
  }


  /**
   * @RequestParam 接收提交的参数,参数默认是必填的
   * @RequestParam(value = "password", required = false) required = false,可以不是必填的参数
   *
   */
  @PostMapping("buildUser")
  @ResponseBody
  public String buildUser(@RequestParam("username") String username,
                      @RequestParam(value = "password", required = false) String password){

    return "提交的参数:username" + username + " password:" + password;
  }

在SpringBoot中使用JSP

SpringBoot默认不支持JSP,需要在项目中添加相关的依赖

 <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jdt.core.compiler</groupId>
      <artifactId>ecj</artifactId>
      <version>4.6.1</version>
      <scope>provided</scope>
 </dependency>

配置文件增加配置项:

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

Login.java

@Controller
public class LoginController {

  @PostMapping("login")
  public String login(String username, String password){

    if (username.equals(password)){
      return "list";
    }
    return "login";
  }

  @GetMapping("form")
  public String from(Model model){

    model.addAttribute("username", "tomcat");
    return "form";
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

02-05 23:33