Spring MVC 基础
Spring MVC 项目案件见附件
导包
配置web.xml启动Spring MVC
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
创建一个以web.xml配置的springMVC servlet名称的文件如:spring-servlet.xml文件名
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="com.springmvc.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
rest风格传参,注入@RequestParam的参数,参数就是地址的一部分,是必需的,如果没有就找404
@RequestMapping({"/hi","/"})
public String hello(@RequestParam("userName") String userName){
System.out.println(userName);
return "hi";
}
1.使用Map
把数据带回view
@RequestMapping({ "/hi", "/" })
public String hello(@RequestParam("userName") String userName,
Map<String, Object> context) {
System.out.println(userName);
context.put("userName", userName);
return "hi";
}
2.使用Model
@RequestMapping({ "/hi", "/" })
public String hello(String userName,
Model model) {
System.out.println(userName);
model.addAttribute("userName", userName);
return "hi";
}
<body>
hello ${userName}
</body>
实例一个user到创建页面
方式1
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute(new User());
return "user/add";
}
方式2
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(@ModelAttribute("user") User user) {
return "user/add";
}
//服务器端验证,可以使用JSR 303 - Bean Validation
1.在bean类里需要验证的字段,使用相应的注解
public class User {
private String userName;
private String password;
private String nikeName;
private String email;
public User(){}
public User(String userName, String password, String nikeName, String email) {
this.userName = userName;
this.password = password;
this.nikeName = nikeName;
this.email = email;
}
@NotBlank(message="用户不能为空")
public String getUserName() {
return userName;
}
}
2.controller难度的参数加@Validated注解,后面一定要跟着BindingResult
@RequestMapping(value = "/{userName}/update", method = RequestMethod.POST)
public String update(@PathVariable String userName, @Validated User user,
BindingResult br) {
if (br.hasErrors()) {
return "user/update";
}
users.put(userName, user);
return "redirect:/user/users";
}
3.spring-servlet.xml
启用MVC注解<mvc:annotation-driven />
异常处理,可以使用局部处理,还有全局处理异常
public class UserException extends RuntimeException {
...
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String userName, String password, HttpSession session) {
if (!users.containsKey(userName)) {
throw new UserException("用户名不存在!");
}
User u = users.get(userName);
if (!u.getPassword().equals(password)) {
throw new UserException("用户密码不正确!");
}
session.setAttribute("loginUser", u);
return "redirect:/user/users";
}
1.局部异常处理
/**
* 局部异常处理
*/
// @ExceptionHandler(value={UserException.class})
// public String handlerException(UserException e,HttpServletRequest req){
// req.setAttribute("e", e);
// return "error";
// }
2.全局异常处理
<!-- 全局异常处理 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.springmvc.model.UserException">error</prop>
</props>
</property>
</bean>
单文件上传
<body>
<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
userName:<sf:input path="userName"/><sf:errors path="userName"/><br />
password:<sf:input path="password"/><sf:errors path="password"/><br />
nikeName:<sf:input path="nikeName"/><br />
email:<sf:input path="email"/><br />
attach:<input type="file" name="attach" />
<input type="submit" value="提交" />
</sf:form>
</body>
spring-servlet.xml
<!-- 设置MultipartResolver才能完成上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"></property>
</bean>
controller
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@Validated User user, BindingResult br,
MultipartFile attach, HttpServletRequest req) throws IOException {
if (br.hasErrors()) {
return "user/add";
}
String path = req.getSession().getServletContext()
.getRealPath("/resources/upload");
File file = new File(path + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
System.out.println(path);
//
// System.out.println(attach.getName() + ","
// + attach.getOriginalFilename() + "," + attach.getContentType());
users.put(user.getUserName(), user);
return "redirect:/user/users";
}
多文件上传
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
attach:<input type="file" name="attachs" />
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@Validated User user, BindingResult br,
@RequestParam("attachs") MultipartFile[] attachs,
HttpServletRequest req) throws IOException {
if (br.hasErrors()) {
return "user/add";
}
String path = req.getSession().getServletContext()
.getRealPath("/resources/upload");
for (MultipartFile attach : attachs) {
if(attach.isEmpty()) continue;
File file = new File(path + "/" + attach.getOriginalFilename());
FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
}
System.out.println(path);
//
// System.out.println(attach.getName() + ","
// + attach.getOriginalFilename() + "," + attach.getContentType());
users.put(user.getUserName(), user);
return "redirect:/user/users";
}
返回json数据 :http://localhost:8080/SpringMVC/user/sdy?json
@RequestMapping(value = "/{userName}", method = RequestMethod.GET,params="json")
@ResponseBody
public User show(@PathVariable String userName) {
return users.get(userName);
}