使用ideal编写代码实现使用拦截器强制未登录用户进行登录以及登录用户可进行文件的上传和下载
时间: 2024-05-07 11:19:48 浏览: 79
以下是使用IDEA编写的Java代码实现拦截器强制未登录用户进行登录以及登录用户可进行文件的上传和下载:
InterceptorConfig.java
```java
@Configuration
@EnableWebMvc
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/upload")
.addPathPatterns("/download")
.excludePathPatterns("/login")
.excludePathPatterns("/logout");
}
}
```
LoginInterceptor.java
```java
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
// 未登录用户,跳转到登录页面
if (user == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
}
```
UserController.java
```java
@Controller
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String doLogin(@RequestParam String username, @RequestParam String password,
HttpSession session) {
// 验证用户名和密码是否正确
if (username.equals("admin") && password.equals("123456")) {
session.setAttribute("user", username);
return "redirect:/upload";
} else {
// 登录失败,返回登录页面
return "login";
}
}
@GetMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "redirect:/login";
}
@GetMapping("/upload")
public String upload() {
return "upload";
}
@PostMapping("/upload")
public String doUpload(@RequestParam MultipartFile file) throws IOException {
// 文件上传的具体操作
return "redirect:/download";
}
@GetMapping("/download")
public String download() {
return "download";
}
@PostMapping("/download")
public void doDownload(HttpServletResponse response) throws IOException {
// 文件下载的具体操作
}
}
```
在上面的代码中,LoginInterceptor类实现了HandlerInterceptor接口,用于拦截未登录用户访问需要登录才能访问的资源,如上传和下载文件。在InterceptorConfig类中,将LoginInterceptor注册为拦截器,并设置需要拦截的路径和不需要拦截的路径。在UserController类中,实现了登录、注销、上传和下载文件的功能,当用户访问需要登录才能访问的资源时,拦截器会先进行判断,如果用户未登录,则跳转到登录页面,否则允许用户访问资源。