编写Spring MVC控制器的14个技巧
java1234
共 17048字,需浏览 35分钟
·
2021-08-06 06:09
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
1.使用@Controller构造型
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String visitHome() {
return "home";
}
}
<annotation-driven />
<context:component-scan base-package="net.codejava.spring" />
@Controller
public class MultiActionController {
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
}
@RequestMapping("/saveUser")
public ModelAndView saveUser(User user) {
}
@RequestMapping("/deleteUser")
public ModelAndView deleteUser(User user) {
}
}
2.实现控制器接口
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class MainController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("Welcome main");
return new ModelAndView("main");
}
}
<bean name="/main" class="net.codejava.spring.MainController" />
3.扩展AbstractController类
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class BigController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("You're big!");
return new ModelAndView("big");
}
}
这将创建具有有关受支持的方法,会话和缓存的配置的单动作控制器,然后可以在控制器的bean声明中指定这些配置。例如:
<bean name="/big" class="net.codejava.spring.BigController">
<property name="supportedMethods" value="POST"/>
</bean>
AbstractUrlViewController
MultiActionController
ParameterizableViewController
ServletForwardingController
ServletWrappingController
UrlFilenameViewController
4.为处理程序方法指定URL映射
@RequestMapping("/login")
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/hello")
public class SingleActionController {
@RequestMapping(method = RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
当@RequestMapping
注解在方法级别使用的,你可以有一个多动作控制器。例如:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("/listUsers")
public String listUsers() {
return "ListUsers";
}
@RequestMapping("/saveUser")
public String saveUser() {
return "EditUser";
}
@RequestMapping("/deleteUser")
public String deleteUser() {
return "DeleteUser";
}
}
@RequestMapping({"/hello", "/hi", "/greetings"})
5.为处理程序方法指定HTTP请求方法
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewLogin() {
return "LoginForm";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin() {
return "Home";
}
}
6.将请求参数映射到处理程序方法
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(@RequestParam String username,
@RequestParam String password) {
}
http:// localhost:8080 / spring / login?username = scott&password = tiger
@RequestParam int securityNumber
@RequestParam("SSN") int securityNumber
@RequestParam(required = false) String country
@RequestParam(defaultValue = "18") int age
doLogin(@RequestParam Map<String, String> params)
7.返回模型和视图
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewLogin() {
return "LoginForm";
}
这是返回视图名称的最简单方法。但是,如果要将其他数据发送到视图,则必须返回一个 ModelAndView
对象。考虑以下处理程序方法:
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
List<User> listUser = new ArrayList<>();
// 从DAO获取用户列表…
ModelAndView modelView = new ModelAndView("UserList");
modelView.addObject("listUser", listUser);
return modelView;
}
@RequestMapping("/listUsers")
public ModelAndView listUsers(ModelAndView modelView) {
List<User> listUser = new ArrayList<>();
//从DAO获取用户列表…
modelView.setViewName("UserList");
modelView.addObject("listUser", listUser);
return modelView;
}
8.将对象放入模型
modelView.addObject("listUser", listUser);
modelView.addObject("siteName", new String("CodeJava.net"));
modelView.addObject("users", 1200000);
@RequestMapping(method = RequestMethod.GET)
public String viewStats(Map<String, Object> model) {
model.put("siteName", "CodeJava.net");
model.put("pageviews", 320000);
return "Stats";
}
9.处理程序方法中的重定向
// 检查登录状态....
if (!isLogin) {
return new ModelAndView("redirect:/login");
}
// 返回用户列表
10.处理表格提交和表格验证
@Controller
public class RegistrationController {
@RequestMapping(value = "/doRegister", method = RequestMethod.POST)
public String doRegister(
@ModelAttribute("userForm") User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// 表单验证错误
} else {
// 表单输入没问题
}
// 注册过程……
return "Success";
}
}
在方法参数上使用@ModelAttribute
在方法上使用@ModelAttribute
接口绑定结果
11.处理文件上传
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public String handleFileUpload(
@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
for (CommonsMultipartFile aFile : fileUpload){
// 存储上传的文件
aFile.transferTo(new File(aFile.getOriginalFilename()));
}
return "Success";
}
12.在控制器中自动装配业务类
@Controller
public class UserController {
@Autowired
private UserDAO userDAO;
public String listUser() {
// 列出所有用户的处理方法
userDAO.list();
}
public String saveUser(User user) {
// 保存/更新用户的处理方法
userDAO.save(user);
}
public String deleteUser(User user) {
// 删除用户的处理方法
userDAO.delete(user);
}
public String getUser(int userId) {
// 获取用户的处理方法
userDAO.get(userId);
}
}
interface UserDAO {
List<User> list();
void save(User user);
void checkLogin(User user);
}
13.访问HttpServletRequest和HttpServletResponse
@RequestMapping("/download")
public String doDownloadFile(
HttpServletRequest request, HttpServletResponse response) {
// 访问请求
// 访问响应
return "DownloadPage";
}
14.遵循单一责任原则
控制器类不应执行业务逻辑。相反,它应该将业务处理委托给相关的业务类别。这使控制器始终专注于其设计职责是控制应用程序的工作流程。例如:
@Controller
public class UserController {
@Autowired
private UserDAO userDAO;
public String listUser() {
userDAO.list();
}
public String saveUser(User user) {
userDAO.save(user);
}
public String deleteUser(User user) {
userDAO.delete(user);
}
public String getUser(int userId) {
userDAO.get(userId);
}
}
为每个业务域创建每个单独的控制器。例如,
UserController
用于控制用户管理的OrderController
工作流程, 用于控制订单处理的工作流程等。例如:
@Controller
public class UserController {
}
@Controller
public class ProductController {
}
@Controller
public class OrderController {
}
@Controller
public class PaymentController {
}
作者 | 不坠青云~
来源 | csdn.net/Summer_Lyf/article/details/102911215
评论