springboot(17)- 整合web开发(9)- 整合web基础组件
程序员文章站
2022-07-10 20:00:48
...
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;
}
}
上一篇: OSS细粒度的权限控制
下一篇: 说说Web开发之远程与本地文件下载的细节