Spring MVC 4
Spring MVC 4
项目文件结构
pom.xml依赖
<properties><endorsed.dir>${project.build.directory}/endorsed</endorsed.dir><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies> <dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.2.5.RELEASE</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.4</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.2.5.RELEASE</version></dependency><!-- JSTL --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version><scope>runtime</scope></dependency><dependency><groupId>javax</groupId><artifactId>javaee-web-api</artifactId><version>7.0</version><scope>provided</scope></dependency></dependencies>
applicationContext.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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
</beans>
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:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- springmvc 注解驱动 --><!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven/><!-- 扫描器 --><!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <context:component-scan base-package="com"/><!-- 配置视图解析器 --><!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 前缀 --><property name="prefix" value="/view/"></property><!-- 后缀 --><property name="suffix" value=".jsp"></property></bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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"><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- POST中文乱码过滤器 Servlet 3.0 新特性@WebFilter,@WebFilter是过滤器的注解,不需要在web.xml进行配置,不过话说还是配置好用<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>/*</url-pattern></filter-mapping>--><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><session-config><session-timeout>30</session-timeout></session-config><welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>
</web-app>
hello.java
/** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/
package com.me.www;import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;/*
@Scope("##") : spring默认的Scope是单列模式(singleton),顾名思义,肯定是线程不安全的. 而@Scope("prototype")
可以保证每个请求都会创建一个新的实例, 还有几个参数: session request@Scope("session")的意思就是,只要用户不退出,实例就一直存在,
request : 就是作用域换成了request
@Controller : 不多做解释 , 标注它为Controller
@RequestMapping :是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是 以该地址作为父路径。 比如现在访问getProducts方法的地址就是 :
http://localhost:8080/项目名/上面web.xml配置(api)/products/list*/
@Scope("prototype")
@Controller
@RequestMapping("/hello")
public class Hello {//使用HttpServletRequest获取@RequestMapping(value = "/listRequest")public String listRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {request.setAttribute("message", "helloWord>>>HttpServletRequest方式 by http://blog.csdn.net/unix21/");return "hello";}//http://localhost:8080/www/hello/testRequestParameter?name=admin&pass=123@RequestMapping(value = "/listRequestParameter")public String listRequestParameter(HttpServletRequest request, HttpServletResponse response) throws Exception {String name = request.getParameter("name");String pass = request.getParameter("pass");request.setAttribute("message", "helloWord>>>HttpServletRequestParameter方式 参数是name=" + name + " pass=" + pass + " by http://blog.csdn.net/unix21/");return "hello";}@RequestMapping(value = "/listModel")public String listModel(Model model) {model.addAttribute("message", "Hello World>>>Model方式 by http://blog.csdn.net/unix21/");return "hello";}@RequestMapping(value = "/list/{id}", method = RequestMethod.GET)public String listId(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {request.setAttribute("message", "helloWord>>>HttpServletRequest方式 id=" + id + " by http://blog.csdn.net/unix21/");return "hello";}//需要注意参数名要和bean对应@RequestMapping(value = "/list/{id}/{name}", method = RequestMethod.GET)public String listIdName(Product pro, HttpServletRequest request, HttpServletResponse response) throws Exception {request.setAttribute("message", "Hello World>>> 多参数" + pro.getId() + "___" + pro.getName() + " by http://blog.csdn.net/unix21/");return "/product/info";}@RequestMapping(value = "/listModelAndView")//@RequestMapping(value="/list",method=RequestMethod.GET)public ModelAndView listModelAndView() {//1、收集参数//2、绑定参数到命令对象//3、调用业务对象//4、选择下一个页面ModelAndView mv = new ModelAndView();//添加模型数据 可以是任意的POJO对象mv.addObject("message", "Hello World>>>ModelAndView方式 by http://blog.csdn.net/unix21/");//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面mv.setViewName("hello");return mv;}@RequestMapping(value = "/post", method = RequestMethod.POST)public String postData(Product pro, HttpServletRequest request, HttpServletResponse response) throws Exception {request.setAttribute("message", "Hello World>>> POST参数" + pro.getId() + "___" + pro.getName() + " by http://blog.csdn.net/unix21/");return "hello";}//将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。@ResponseBody@RequestMapping("/1.json")public void getJSON(HttpServletRequest req, HttpServletResponse res) throws Exception {Map<String, Object> map = new HashMap<String, Object>();Product p1 = new Product();p1.setId(123);p1.setName("abc");Product p2 = new Product();p2.setId(456);p2.setName("def");map.put("p1", p1);map.put("p2", p2);//org.codehaus.jackson.mapObjectMapper mapper = new ObjectMapper();PrintWriter pWriter = res.getWriter();pWriter.write(mapper.writeValueAsString(map));}/*@RequestMappingRequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。RequestMapping注解有六个属性,下面我们把她分成三类进行说明。1、 value, method;value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);method: 指定请求的method类型, GET、POST、PUT、DELETE等;2、 consumes,produces;consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;3、 params,headers;params: 指定request中必须包含某些参数值是,才让该方法处理。headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。*/
}
Product.java
package com.me.www;public class Product {private String name;private int id;/*** @return the name*/public String getName() {return name;}/*** @param name the name to set*/public void setName(String name) {this.name = name;}/*** @return the id*/public int getId() {return id;}/*** @param id the id to set*/public void setId(int id) {this.id = id;}
}
hello.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Hello World</title></head><body><h1>Spring MVC加载成功</h1>${message}</body>
</html>
例如:http://localhost:8080/www/hello/list/123/abc
Post数据
<html><head><title>POST数据提交</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><form action="http://localhost:8080/www/hello/post" method="post"><input type="text" name="id"/> <input type="text" name="name"/> <input type="submit"/></form>
</body>
</html>
输出json
post参数转码的另一种处理方法
@RequestMapping(value = "/post", method = RequestMethod.POST)public ModelAndView post(@RequestParam("username")String username) {username=StringUtil.encodeStr(username); ModelAndView mv = new ModelAndView();mv.addObject("username", username);mv.setViewName("post");return mv;
}
/*** ISO-8859-1转UTF-8 主要用于POST数据处理** @param str 需要转码的值*/public static String encodeStr(String str) {try {return new String(str.getBytes("ISO-8859-1"), "UTF-8");} catch (UnsupportedEncodingException e) {return null;}}
@RequestBody
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) { // implementation omitted
}
/
参考:
SpringMVC简单构造restful, 并返回json
@Scope("##") : spring默认的Scope是单列模式(singleton),顾名思义,肯定是线程不安全的. 而@Scope("prototype")
可以保证每个请求都会创建一个新的实例, 还有几个参数: session request
@Scope("session")的意思就是,只要用户不退出,实例就一直存在,
request : 就是作用域换成了request
@Controller : 不多做解释 , 标注它为Controller
@RequestMapping :是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是 以该地址作为父路径。 比如现在访问getProducts方法的地址就是 :
http://localhost:8080/项目名/上面web.xml配置(api)/products/list/
@RequestMapping 用法详解之地址映射
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
1、 value, method;
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
2、 consumes,produces;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
3、 params,headers;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
@RequestParam @RequestBody @PathVariable 等参数绑定注解详解
Spring MVC 4相关推荐
- Java之Spring mvc详解(非原创)
文章大纲 一.Spring mvc介绍 二.Spring mvc代码实战 三.项目源码下载 四.参考文章 一.Spring mvc介绍 1. 什么是springmvc springmvc是spri ...
- spring mvc 关键接口 HandlerMapping HandlerAdapter
HandlerMapping Spring mvc 使用HandlerMapping来找到并保存url请求和处理函数间的mapping关系. 以DefaultAnnotationHandle ...
- spring mvc 控制器方法传递一些经验对象的数组
由于该项目必须提交一个表单,其中多个对象,更好的方法是直接通过在控制器方法参数的数组. 因为Spring mvc框架在反射生成控制方法的參数对象的时候会调用这个类的getDeclaredConstru ...
- java注解返回不同消息,Spring MVC Controller中的一个读入和返回都是JSON的方法如何获取javax.validation注解的异常信息...
Spring MVC Controller中的一个读入和返回都是JSON的方法怎么获取javax.validation注解的错误信息? 本帖最后由 LonelyCoder2012 于 2014-03- ...
- Spring MVC前后端的数据传输
本篇文章主要介绍了Spring MVC中如何在前后端传输数据. 后端 ➡ 前端 在Spring MVC中这主要通过Model将数据从后端传送到前端,一般的写法为: @RequestMapping(va ...
- 番外:Spring MVC环境搭建和Mybatis配置避坑篇
2019独角兽企业重金招聘Python工程师标准>>> web.xml引入对spring mvc的支持: spring-mvc配置spring-mvc: spring-mybatis ...
- spring mvc velocity 配置备忘
2019独角兽企业重金招聘Python工程师标准>>> Spring里面最重要的概念是IOC和AOP,还有两项很重要的模块是事务和MVC,对于IOC和AOP,我们要深究其源码实现,对 ...
- Spring MVC配置文件的三个常用配置详解
2019独角兽企业重金招聘Python工程师标准>>> Spring MVC项目中通常会有二个配置文件,sprng-servlet.xml和applicationContext.xm ...
- Spring MVC框架有哪些优点
Spring MVC是Spring提供的一个实现了Web MVC设计模式的轻量级Web框架.它与Struts2框架一样,都属于MVC框架,但其使用和性能等方面比Struts2更加优异. Spring ...
最新文章
- 最热开源无服务器函数:五大Fission架构参考
- POJ - 2400 Supervisor, Supervisee(KM+打印方案)
- STL中empty()函数的误用
- 我们的目标是安全有效支持业务的信息处理技术平台
- 机器学习实战——Logistic回归
- 计算机网络 简单网络管理协议 SNMP
- 淘宝天猫店铺装修问题与技巧性经验汇总
- OSChina 周六乱弹 —— 泡面就要泡着吃……
- everything无法搜索刚插入的硬盘中的文件
- 李清照最经典的10首诗词
- 中国最美丽的地方排行榜国家地理
- VSCode的LeetCode插件中国区账号密码登录错误
- 路漫漫远修兮-centos7 oracle 11g 静默安装教程
- java gif转jpg_Java gif图片转换为jpg格式
- JAVA经典算法面试40题及答案
- ios 界面开发_iOS开发新手指南:界面-第一部分
- SQL(MySql)菜鸟教程知识
- 用反证法证明有无穷多个素数
- zxing生成二维码去白边
- vue set设置html根字体,vue-quill-editor安装及使用:自定义工具栏和自定义中文字体,把字体写在html的style中...
热门文章
- 10000+ gif表情包不是梦,get这一篇文就够了!!!小哥哥快到碗里来,再也不怕斗图没有表情包了
- LabVIEW纹理分析(基础篇—9)
- 什么是self-attention、Multi-Head Attention、Transformer
- AI视频行为分析系统项目复盘——技术篇3:tensorRT技术梳理
- 【MediaPipe】(2) AI视觉,人体姿态关键点实时跟踪,附python完整代码
- java 读取流的字符编码格式_如何使用Java代码获取文件、文件流或字符串的编码方式...
- Node.js实现服务器端生成Excel文件(xls格式、xlsx格式文件)并弹出下载文件
- Python基础学习1(Python的Windows和Linux的安装及简单学习)
- python多进程详解
- 树状数组的理解(前缀和 and 差分)