springboot学习笔记三

@RestController

package da.test;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @GetMapping @PostMapping
 *             为spring4.3的新特性,访问请求必须为get或者post,代替了@RequestMapping后面的method中请求
 * @RestController 加了这个就不需要@ResponseBody了
 */
@RestController
public class UserController {
    @RequestMapping("/user/home")
    public String home() {
        return "user home";
    }

    @GetMapping("/user/show")
    public String show(@RequestParam("username") String username, @RequestParam("password") String password) {
        return "user show " + username + ":" + password;
    }

    @PostMapping("/user/create")
    public String create() {
        return "user create";
    }

    @GetMapping("/user/showid/{id}")
    public String showid(@PathVariable("id") Integer id) {
        return "user show id:" + id;
    }
}

springboot使用jsp:

1 在配置文件中加入

#springboot使用jsp
spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp

2 在pom文件中加入相关jar包


<dependency>
    <groupId>org.apache.tomcat.embedgroupId>
    <artifactId>tomcat-embed-jasperartifactId>
dependency>

3 jsp文件放在src/main/webapp文件夹下面

springboot学习笔记三_第1张图片

4 如果要使用jsp则不能使用@RestController

package da.test;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
    @GetMapping("/login")
    public String show(@RequestParam("username") String username, @RequestParam("password") String password) {
        if (username.equals(password))
            return "ok";
        return "fail";
    }

    @GetMapping("/login2")
    public String show(Model model) {
        model.addAttribute("username", "root");
        return "login";
    }
}

springboot使用freemarker:

1 pom文件中加入依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-freemarkerartifactId>
dependency>

2 Freemarker存放在templates中

这里写图片描述

package da.test;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class FreemarkerTest {
    @GetMapping("reg")
    public String reg() {
        return "reg";
    }

    @GetMapping("fmlogin")
    public String fmlogin(Model model) {
        model.addAttribute("username", "root");
        return "login";
    }
}

springboot使用jetty服务器启动:

需要修改pom依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
    
    <exclusions>
        <exclusion>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-tomcatartifactId>
        exclusion>
    exclusions>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-jettyartifactId>
dependency>

拦截器配置:

package da.test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("======preHandle=======" + handler.getClass());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("======postHandle=======");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("======afterCompletion=======");
    }

}
package da.test;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootConfiguration
public class InterceptorConfiguration extends WebMvcConfigurerAdapter {
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor());
    }
}

异常处理:

先要关闭默认错误处理@SpringBootApplication(exclude=ErrorMvcAutoConfiguration.class)

1 错误页面的处理

package da.test;

import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.boot.web.servlet.ErrorPageRegistrar;
import org.springframework.boot.web.servlet.ErrorPageRegistry;
import org.springframework.http.HttpStatus;

//@Component
public class CommonErrorPageRegistrar implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
        ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
        registry.addErrorPages(e404, e500);
    }

}

2 控制器中的异常

package da.test;

import java.io.FileNotFoundException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController02 {

    @RequestMapping("/interceptor/login")
    public String login() {
        System.out.println("============login=========");
        return "login";
    }

    @GetMapping("/user/help")
    public String help() {
        throw new IllegalArgumentException("出异常啦!");
    }

    @ExceptionHandler(value = Exception.class)
    public String error(Exception e) {
        return "exception:" + e.getMessage();
    }

    @GetMapping("/user/error1")
    public String error1() throws FileNotFoundException {
        throw new FileNotFoundException("出异常啦1!");
    }

    @GetMapping("/user/error2")
    public String error2() throws ClassNotFoundException {
        throw new ClassNotFoundException("出异常啦2!");
    }
}

3 全局异常处理

package da.test;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String errorHandler(Exception e) {
        return "globel exception:" + e.getClass().getName();
    }
}

Tomcat的一些配置:

#设置访问地址与访问端口
#server.address=192.168.1.104
#server.port=8888
#开启tomcat的日志功能
#server.tomcat.accesslog.enabled=true
#server.tomcat.accesslog.directory=e:/tmp/logs
#server.tomcat...开启其他tomcat的功能

其他内容:

#指定启动端口,默认8080
server.port=8888

springboot默认静态资源的路径:
classpath:[/WEB-INF/resources/,/resources/,/static/,/public/]可以通过spring.resources.staticLocations配置项修改默认静态资源的路径

你可能感兴趣的:(学习笔记)