SpringMVC的配置和用法

1、搭建SpringMVC框架步骤:
1)配置部署描述符(web.xml):
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet<!--指定servlet的全名,此是springmvc自带的DispatcherServlet -->
</servlet-class>
<!-- load-on-startup这个参数可选,如果存在则在程序启动时装载servlet并调用init方法,若不存在则第一个请求时加载 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern><!-- /表示将所有URL映射到此servlet -->
</servlet-mapping>
--------------------------------------------------------------------------------------------------------------------------------------------------
2)配置SpringMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!-- SpringMVC的配置文件需在WEB-INF目录下,命名方式必须为servletName-servlet.xml
servletName是部署描述符中(web.xml)<servlet-name>springmvc</servlet-name>的名字 -->
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<bean name="/getMsg" class="org.great.action.GetMsgTestAction">
<!-- name为映射路径,如<form action="getMsg">
class为进入此映射路径后所调用的类-->
</bean>
</beans>
--------------------------------------------------------------------------------------------------------------------------------------------------
3)实现Controller接口:
@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
GetMsgBean gmb = new GetMsgBean();
gmb.setUserName(req.getParameter("userName"));
gmb.setPwd(req.getParameter("pwd"));
//向前台返回一个页面、模型名称及模型,在前台可以通过EL表达式根据模型名称取得实例中的属性${getMsgBean.userName }
return new ModelAndView("MyJsp.jsp", "getMsgBean", gmb);
}
==================================================================================================================================================
2、注解:
1)依赖注入:
@Autowired:可以处理构造器注入和setter注入(构造器注入首选)(按byType进行注入)
@Resource:只能处理setter注入(setter注入首选)(默认按byName注入,可对type进行设置)
--------------------------------------------------------------------------------------------------------------------------------------------------
2)自动扫描标记:(在类上有次标记,可自动扫描进spring容器中进行定义,无需再次在容器中自定义)
@Component 通用注解
@Named 通用注解
@Repository 持久化层组件注解
@Service 业务层组件注解
@Controller 控制层组件注解
@PostConstruct
public void init(){}//初始化回调方法
@PreDestroy
public void destroy(){}//销毁回调方法
--------------------------------------------------------------------------------------------------------------------------------------------------
3)@Value("#{user.userName}") ""中的值可以是基本类型,也可以是从容器中引用来的ID
--------------------------------------------------------------------------------------------------------------------------------------------------
==================================================================================================================================================
3、集合注入:<util:list />、<util:set />、<util:map/>、<util:properties />
1)可使用注解@Value("#{stuList}")将此list的值赋值给bean中的属性(<util:set />、<util:map/>类似)
<util:list id="stuList">
<value>A</value>
<value>B</value>
</util:list>
--------------------------------------------------------------------------------------------------------------------------------------------------
2)使用util:properties读取文件,之后使用#{user.userName}获得文件中属性值
<util:properties id="user" location="classpath:userText.properties"></util:properties>
==================================================================================================================================================
4、访问静态文件,如jsp、js、css
1)方案一:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
--------------------------------------------------------------------------------------------------------------------------------------------------
2)方案二:使用<mvc:resources/>元素
<mvc:resources mapping="/images/**" location="/images/" />//location指定静态资源的位置
==================================================================================================================================================
5、文件上传:(多文件上传:JSP页面<input type="file" name="file" multiple="multiple"/>)
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

@RequestMapping("/upLoad")
public String upLoad(@RequestParam("file") MultipartFile file[]){
for(MultipartFile mf : file){
String fileName = mf.getName();
String fileContentType = mf.getContentType();
String fileAllName = mf.getOriginalFilename();
if (!mf.isEmpty()){
try {
//使用StreamsAPI方式拷贝文件
Streams.copy(mf.getInputStream(),new FileOutputStream("E:/"+mf.getOriginalFilename()),true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
PS:
<!-- 文件上传中文乱码,在spring的配置文件中定义以下bean -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>
</beans>
--------------------------------------------------------------------------------------------------------------------------------------------------
***一个关于上传的工具类:
public class FileUploadUtil {
public static final String FILE_PATH = "upload";//要保存的路径
//文件上传
public static String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
String fileName = file.getOriginalFilename();
//获得服务器的绝对路径
String path = request.getSession().getServletContext().getRealPath(FILE_PATH);
File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName));
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdir();
}
if (!tempFile.exists()) {
tempFile.createNewFile();
}
//保存(MultipartFile类的方法)
file.transferTo(tempFile);
return tempFile.getName();
}
public static File getFile(HttpServletRequest request, String fileName) {
String path = request.getSession().getServletContext().getRealPath(FILE_PATH);
return new File(path, fileName);
}
}
==================================================================================================================================================
6、文件下载:
@RequestMapping("/downLoad")
public ResponseEntity<byte[]> down() {
// 指定文件,必须是绝对路径
File file = new File("D:/新2015培训手册.doc");
// 下载浏览器响应的那个文件名
String dfileName = file.getName();
// 下面开始设置HttpHeaders,使得浏览器响应下载
HttpHeaders headers = new HttpHeaders();
// 设置响应方式
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
byte a[] = null;
try {
// 设置响应文件
headers.setContentDispositionFormData("attachment", new String(dfileName.getBytes("gbk"),"iso-8859-1"));
a = FileUtils.readFileToByteArray(file);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 把文件以二进制形式写回
return new ResponseEntity<byte[]>(a, headers, HttpStatus.CREATED);
}
==================================================================================================================================================
7、
<context:component-scan/> 扫描指定的包中的类上的注解,常用的注解有:
@Controller 声明Action组件
@Service 声明Service组件 @Service("myMovieLister")
@Repository 声明Dao组件
@Component 泛指组件, 当不好归类时.
@RequestMapping("/menu") 请求映射
@Resource 用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name="beanName") (可以直接省略get\set方法)
@Autowired 用于注入,(srping提供的) 默认按类型装配
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody(使用ajax必须在action方法上加的注解)
@Scope("prototype") 设定bean的作用域
==================================================================================================================================================
8、
@Controller 控制器(注入服务)
@Service 服务(注入dao)
@Repository dao(实现dao访问)
@Component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
==================================================================================================================================================
9、controller层使用@controller注解
@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法。通俗来说,被Controller标记的类就是一个控制器,这个类中的方法,就是相应的动作。
@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。比如下面,跳转到登录页面的路径就是localhost:8080/xxx/hello1/hello

@RequestMapping
@RequestMapping(value="/hello1") 等同 @RequestMapping("/hello1")等同于/hello1

/hello1/hello
@RequestMapping(value="/hello1")
public class HelloController {
@RequestMapping(value="/hello",method=RequestMethod.GET)
public String sayHello(Model model){
model.addAttribute(key, value)//前台使用${key}可以去得到model中的value
==================================================================================================================================================
10、service采用@service注解
@Service("userService")注解是告诉spring,当Spring要创建UserService的实例时,bean的名字必须叫做"userService",这样当Action需要使用UserService的实例时,就可以由Spring创建好的"userService",然后注入给Action。
==================================================================================================================================================
11、dao层使用@repository注解
@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。
当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl实例时,就可以使用@Resource(name = "userDao")注解告诉Spring,Spring把创建好的userDao注入给Service即可。

@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作,我们也要清楚,@Autowired是根据类型进行自动装配的。
==================================================================================================================================================
12、mapper层使用@Component注解
==================================================================================================================================================
13、转发与重定向
可以通过redirect/forward:url方式转到另一个Action进行连续的处理。
可以通过redirect:url 防止表单重复提交。
写法如下:
return "forward:/order/add";
return "redirect:/index.jsp";
==================================================================================================================================================
14、AJAX的用法:@ResponseBody//使用此注解可以返回JSON数据
可以在action中实例一个Map对象,然后将前台要的数据存储在这个对象中
直接return map这个对象,前台ajax的回调函数自然可以得到JSON数据
==================================================================================================================================================
15、@RequestParam("role_no"):等同于request.getParameter("role_no")
可以取得前台input中name="role_no"的value值
==================================================================================================================================================
16、在JSP页面中使用SpringMVC标签:
在web.xml中配置:
<jsp-config>
<taglib>
<span style="white-space:pre"></span>
<taglib-uri>/spring</taglib-uri>
<span style="white-space:pre"></span>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</jsp-config>
在WEB-INF目录中导入:spring-form.tld、spring.tld
==================================================================================================================================================

posted on 2017-07-09 09:46  猴子敲代码  阅读(384)  评论(0编辑  收藏  举报