之前一直用struts2/spring/hibernate,部门被吞并了,得学着用人家mybatis/spring/springMVC。
原先的领导让我整理一份springMVC学习文档出来,给同事们快速上手一下,我也就顺便粘过来吧。懂得struts2的人再学springMVC很容易,接下来这篇文章也是对于有一定基础的人准备的。
web.xml中加入:
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
classpath:spring-mvc.xml是springMVC配置文件的地址。
*.do是springMVC拦截的地址。不是.do结尾就不拦截。
spring-mvc.xml:
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 使用注解的包,包括子集,spring要扫描的包-->
<context:component-scan base-package="com.xxxx"/>
<!-- 视图解析器,匹配传回来的字符串,到解析器的地址找jsp -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
HelloWorld:
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model){
model.addAttribute("message", "HelloWorld");
return "helloWorld";
}
}
在这个类加入spring的@controller注解。
方法上@RequestMapping(地址),springMVC就会根据拦截的地址,找到这个方法,并执行。
类的上方也可以加入@RequestMapping(地址),就相当于struts2的nameSpace。
方法的参数Model,可以直接调用.addAttribute()方法,以键值对的形式,像前台JSP传数据。直接使用el表达式就可以取到了。
return "helloWorld"就会去视图解析器查找对应的JSP,即/WEB-INF/jsp/helloWorld.jsp,若return "hello/helloWorld"则返回/WEB-INF/jsp/hello/helloWorld.jsp
ModelAndView
@RequestMapping("/list")
public ModelAndView list(@RequestParam(value="id",required=false) String id){
List<Student> studentList=new ArrayList<Student>();
ModelAndView mav=new ModelAndView();
mav.addObject("studentList", studentList);
mav.setViewName("student/list");
return mav;
}
ModelAndView. addObject()和上面的model是一样的,都是通过键值对的方式向前台传参数,ModelAndView. setViewName()就相当于上面return的地址。
@RequestParam(value="id",required=false),前台传过来的值,value就是name,赋给后面声明的参数,required=false代表非必须,若没有的话,id为空时会报错。
内部转发、重定向和自动封装
后台:
@RequestMapping("/save")
public String save(Student student){
studentList.add(student);
// return "redirect:/student/list.do";
return "forward:/student/list.do";
}
前端:
<form action="${pageContext.request.contextPath}/student/save.do" method="post">
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"/></td>
</tr>
</table>
</form>
name和age都是student的属性,在提交的时候,将他这样命名,就会自动封装到方法的参数student中。
return "redirect:xxx";是重定向,return "forward:xxx";是转发。
乱码解决:
Web.xml中加入,spring自带的编码转换器,过滤所有.do的
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Servlet API和JSON
spring-mvc.xml中加入:
<!-- 支持对象与json的转换。 -->
<mvc:annotation-driven/>
public String login(HttpServletRequest request,HttpServletResponse response){
XXXXXXXXXXXXXXX;
}
参数中,加入HttpServletRequest request, HttpServletResponse response, HttpSession session则可以通过servlet API自动获得servlet中的request\response\session对象。
public @ResponseBody User ajax(){
User user=new User("zhangsan","123");
return user;
}
在方法返回值的类前面加上@ResponseBody 注解,return 一个对象后,通过上面spring-mvc.xml中加入的<mvc:annotation-driven/>标签,则可以自动把user中的各个属性,转化成json对象。
Restful风格
@RequestMapping("/details/{id}")
public ModelAndView details(@PathVariable("id") int id){
ModelAndView mav=new ModelAndView();
if(id==1){
mav.addObject("article", new Article("文章一","文章一的内容"));
}else if(id==2){
mav.addObject("article", new Article("文章二","文章二的内容"));
}
mav.setViewName("article/details");
return mav;
}
修改web.xml中springmvc拦截路径为/。
方法上加入@RequestMapping("/details/{id}"),{id}为占位符。参数中加入@PathVariable("id"),id则为占位符所占的字符。这样即可将地址URL变为这种类型。但是因为拦截了所有的请求,所有CSS,JS,图片的请求就会失败。还要单独配置映射,
<mvc:resources mapping="/resources/**" location="/images/"/>
<mvc:resources mapping="/resources2/**" location="/css/"/>
将CSS,用resources标签,images映射成resources,springMVC就不会拦截了。
文件上传
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10000000"/>
</bean>
defaultEncoding设置文件编码格式。
maxUploadSize设置文件上传大小(字节)。
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
return "redirect:success.html";
}
@RequestMapping("/upload2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
for(MultipartFile file:files){
file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
}
return "redirect:success.html";
}
@RequestParam("file")页面传来的file注入到 MultipartFile参数中。
多文件上传就是MultipartFile数组。
文件下载
和servlet文件下载一样。
简略的整理了一下,会了这些至少能够应负简单的开发工作了。至于剩下的问题,以后工作中遇到再说。
以上代码和思路均来自www.java1234.com。我做了一点小修改。
浙公网安备 33010602011771号