springmvc

SpringMVC环境搭建:

1、加入jar包

由于找不到HttpServlet类,可通过导入Tomcat到工作目录或者通过Maven添加HttpServlet类所在的servlet-api.jar
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.2.RELEASE</version>
<scope>compile</scope>
 </dependency>


2、在web.xml中配置dispatcherservlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <servlet>
        <servlet-name>controller</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>controller</servlet-name>
        <url-pattern>*.shtml</url-pattern>
    </servlet-mapping>
</web-app>

3、加入SpringMvc配置文件

<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- 自动扫瞄 -->
<context:component-scan base-package="com.yz" />

<!-- 扫描properties文件,用于占位符 -->
<context:property-placeholder location="classpath:prop/*.properties" />

<!-- 导入所有spring配置文件 -->
<import resource="classpath:xml/spring-*.xml"/>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
<mvc:annotation-driven />

<!-- 访问静态资源 -->
<mvc:default-servlet-handler />

         <!-- 事务注解,一般放在spring配置文件中 -->
<aop:aspectj-autoproxy />

</beans>

占位符: 
@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id){
System.out.println("this is id ="+ id);
return "success";
}

RESTful风格:
web.xml配置过滤器

<!-- 通过SpringMVC中的HiddenHttpMethodFilter 将post请求转换为delete 或 put 请求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Controller:
@RequestMapping(value = "/order/{id}",method = RequestMethod.POST)
public String add(@PathVariable("id") Integer id){
System.out.println("添加操作:id="+ id );
return "success";
}

@RequestMapping(value = "/order/{id}",method = RequestMethod.GET)
public String get(@PathVariable("id") Integer id){
System.out.println("获取资源操作:id="+ id );
return "success";
}

@RequestMapping(value = "/order/{id}",method = RequestMethod.PUT)
public String update(@PathVariable("id") Integer id){
System.out.println("更新资源操作:id="+ id );
return "success";
}

@RequestMapping( value = "/order/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable("id") Integer id){
System.out.println("删除操作:id="+ id );
return "success";
}


※ 加上@ResponseBody 表示返回"success"字符串,否则返回结果被解析为跳转路径
jsp:
<form action="/order/1.shtml" method="get">
<input type="submit" value="get">
</form>
<form action="/order/1.shtml" method="post">
<input type="submit" value="post">
</form>
<form action="/order/1.shtml" method="post">
<input type="hidden" name="_method" value="put">
<input type="submit" value="put">
</form>
<form action="/order/1.shtml" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="delete">
</form>


绑定请求参数:

@PathVariable    主要属于restful:

@RequestMapping(" /testPathVariable/{id}")
@ResponseBody
public String testPathVariable( @PathVariable("id") Integer id){
System.out.println("this is id ="+ id);
return "success";
}

@RequestParam :

@RequestMapping("/testRequestParam")
@ResponseBody
public String testRequestParam( @RequestParam("userName") String userName, @RequestParam(value = "age",required = false,defaultValue = "18") Integer age){
System.out.println("this is testRequestParam userName ="+ userName+",age="+age);
return "success";
}

※ required = false    设置该参数是否必须要传入,默认为true,false为可以不必须传入(设为false时也可以传该参数,defaultValue取值就取传入的值)

※ defaultValue = "18" 如果不传age参数,则默认值是18


@RequestHeader : 用于从Http请求头中提取指定的某个请求头信息

@RequestMapping(value = "/testRequestHeader")
@ResponseBody
public String accept(@RequestHeader(value = "Accept", required = true, defaultValue = "MyAccept") String accept) {
System.out.println("this is testRequestHeader accept ="+ accept);
return accept;
}

使用pojo 绑定请求参数:

springmvc会按请求参数名和pojo属性名进行自动匹配,并填充属性。支持级联属性

@RequestMapping("/testPojo")
@ResponseBody
public String testPojo(User user){
System.out.println("id ="+ user.getId()+",name:"+user.getName()+",address:"+user.getAddress().getCity());
return "success";
}

User:
private int id;
private String name;

private City address;

City:

private String city;

jsp:
<form action="/testPojo.shtml" method="post">
<input type="text" name="id" >
<input type="text" name="name">
<input type="text" name=" address.city">
<input type="submit" value="testPojo">

</form>


ModelAndView :

/**
 * 可以通过ModelAndView,设置视图转发页面、转发参数
 */
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("time",new Date());
modelAndView.setViewName("/test");
return modelAndView;
}

jsp取值:${time}


springmvc如何重定向?
字符串带redirect则重定向

实例 "redirect:/index.jsp" 则重定向到index.jsp页面


如何通过springMVC返回json?
1、在请求方法上加上 @ResponseBody 通过返回值自动转换为json
2、添加json包
<dependency>
<groupId>net.sf.json-lib</groupId>
<classifier>jdk15</classifier>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>

3、需要在springmvc配置文件中配置如下信息:

<!-- 开启注解 -->
<mvc:annotation-driven />

<!-- 避免IE执行Ajax时,返回json出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/> <!-- json转换器 -->
</list>
</property>

</bean>


通过springmvc上传文件

1、在springmvc配置文件中配置上传文件信息

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="${file.maxUploadSize}"/>
<property name="maxInMemorySize" value="512"/>

</bean>

※※※<!-- spring配置文件-扫描properties文件,用于占位符 -->
<context:property-placeholder location="classpath:prop/*.properties" />
# File
file.maxInMemorySize=512
# Max file size: 50MB
file.maxUploadSize=512000000


2、前端页面实例
<form action="/testUpload.shtml" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>

3、Controller
@RequestMapping("/testUpload")
@ResponseBody
public String upload(@RequestParam(value = "file",required = false) MultipartFile file){
// 文件的原名
String originalFilename = file.getOriginalFilename();
// 文件的大小
long size = file.getSize();
System.out.println("originalFilename:"+originalFilename);
System.out.println("size:"+size);
String path="C:\\Users\\yz\\Desktop";
File targetFile = new File(path,originalFilename);
if(!targetFile.exists()){
targetFile.mkdir();
}
// 保存文件
try {
file.transferTo(targetFile);
} catch (IOException e) {
System.out.println("error"+e.getMessage());
}
return "success";
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值