1 整合 web 基礎組件
@WebServlet(urlPatterns = "/myservlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("myServlet");
}
}
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("MyFilter");
chain.doFilter(request, response);
}
}
@WebListener
public class MyRequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("requestDestroyed");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println(" requestInitialized");
}
}
- 啓動類
2 路徑映射
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.1 傳統案例
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
2.2 使用配置類
package com.tzb;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/tzb").setViewName("hello");
}
}
3 使用類型轉換器
@RestController
public class UserController {
@GetMapping("/hello")
public void hello(Date birth){
System.out.println(birth);
}
}
- 日期轉換類
package com.tzb;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class DateConverter implements Converter<String,Date> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String s) {
if(s != null && !"".equals(s)){
try {
return sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}