超实用的14个 Spring MVC “隐藏”技巧,用了都说好!
优质文章,及时送达
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 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";
}
}
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";
}
@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);
}
}
@Controller
public class UserController {
}
@Controller
public class ProductController {
}
@Controller
public class OrderController {
}
@Controller
public class PaymentController {
}
-End-
喜欢文章,点个在看