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>
<?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>
<?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 等参数绑定注解详解
相关文章:

SQL Server 2008高可用性系列:数据库快照
SQL Server 2008高可用性系列:数据库快照http://database.51cto.com 2010-09-13 14:45 我爱菊花 博客园 我要评论(0)摘要:我们今天要讨论的话题是数据库快照。在SQL Server 2008高可用性中,快照是一项很重要的内容,可以提供至…

PostgreSQL 9.3 beta2 stream replication primary standby switchover bug?
[更新]已有patch. 请参见.PostgreSQL 9.1,9.2,9.3 clean switchover Primary and Standby Patch. http://blog.163.com/digoal126/blog/static/16387704020136197354054/打补丁前的测试 : PostgreSQL 9.3 beta2 无法完成正常的主备角色切换.Primary : psql checkpont; pg_cont…

Apache commons-io
添加引用 <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency>按行写: public static void writeFileLineByApacheIO(String fileContent) throws…

Oracle Exadata 简介
随着企业业务的发展,大型数据仓库越来越多,其规模也在迅速扩大,平均每两年规模增大3倍。大型数据仓库要求以最高的磁盘读取速度扫描几十、几百或几千个磁盘,只有磁盘和服务器之间的管道带宽增加10倍或更多才能满足此要求ÿ…
推荐系统的价值观
作者丨gongyouliu来源丨大数据与人工智能(ID: ai-big-data)推荐系统作为满足人类不确定性需求的一种有效工具,是具有极大价值的,这种价值既体现在提升用户体验上,又体现在获取商业利润上。对绝大多数公司来说ÿ…

PostgreSQL md5 auth method introduce, with random salt protect
在上一篇BLOG中介绍了不要在pg_hba.conf中使用password认证方法, 除非你的客户端和数据库服务器之间的网络是绝对安全的.http://blog.163.com/digoal126/blog/static/1638770402013423102431541/MD5方法,认证过程 : Encrypting Passwords Across A Network The MD5 authenticat…
常用Maven收集以及Maven技巧
1.完整的Maven的pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apach…
大促下的智能运维挑战:阿里如何抗住“双11猫晚”?
作者 | 阿里文娱技术专家子霖出品 | AI科技大本营(ID:rgznai100)2019 双 11 猫晚在全球近 190 个国家和地区播出,海外重保是首要任务,如何提升海外用户观看猫晚的体验?本文将详解双 11 猫晚国际化的技术挑战和技术策略…

这次真的是下定决心了
这次我想是真的,真的。 上上周买了一本书 数据结构 c版 看到这本书的重点 线性表第三节,看不下去了,由于我模板学的不怎么样,数据结构c版大部分涉及了c 的模板,而且我觉得这本书上的代码有些漏洞。上上周买书的第三天…

子弹实例化的代码
using UnityEngine; using System.Collections;public class fire : MonoBehaviour {public float rate 0.2f;public GameObject bullet;private void Start(){OnFire();}//实例化子弹public void Fire(){GameObject.Instantiate(bullet, transform.position, Quaternion.iden…
Shiro源码学习之一
一.最基本的使用 1.Maven依赖 <dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.4</version></dependency><dependency> <groupId>org.slf4j</groupId> …

传百度要与阿里、腾讯争夺在线办公市场?“百度Hi”开放520人同时在线音视频会议
在线办公市场持续火热。4月20日,百度旗下在线办公平台“百度Hi”再升级,正式发布业内大规模的520人音视频会议,并支持多入口快速入会,加码在线办公。另有消息称,4月底,百度在线办公平台将发布重磅升级&…

SQL 2008 安装资料及下载地址
SQL Server 2008 序列号: Developer: PTTFM-X467G-P7RH2-3Q6CG-4DMYB Enterprise: JD8Y6-HQG69-P9H84-XDTPG-34MBB 服务器设置SQL Server 代理 NT AUTHORITY\SYSTEMSQL Server Database Engine NT AUTHORITY\NETWORK SERVICE SQL Server Browser 默认 SQL Ser…

Objective-C非正式协议与正式协议
为什么80%的码农都做不了架构师?>>> 类别与类扩展的区别: ①类别中只能增加方法; ②是的,你没看错,类扩展不仅可以增加方法,还可以增加实例变量(或者合成属性)ÿ…
Shiro源码学习之二
接上一篇 Shiro源码学习之一 3.subject.login 进入login public void login(AuthenticationToken token) throws AuthenticationException {clearRunAsIdentitiesInternal();Subject subject securityManager.login(this, token);PrincipalCollection principals;String hos…

Widgets 整理
1.滑动条 http://www.newnaw.com/pub/sl/031.html <--!grid中的内容--> <Grid x:Name"slidergrid" HorizontalAlignment"Left" VerticalAlignment"Center" Background"Azure" Margin"20"> <StackPane…
黑客用上机器学习你慌不慌?这 7 种窃取数据的新手段快来认识一下!
作者 | IrrfanAk译者 | 天道酬勤、Carol 责编 | Carol出品 | AI科技大本营(ID:rgznai100)机器学习以分析大型数据集和模式识别的能力而闻名。它基本上属于人工智能的一个子集。而机器学习使用的算法,是利用了先前的数据集和统计分析来做出假设…

ServletResponse-中文名的下载
2019独角兽企业重金招聘Python工程师标准>>> package com.httpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.se…
Linux环境编译安装OpenJDK
Centos6.5 AMD64位机器 Java的源码是C,C和Java实现的,所以还需要有一个安装好的java建议选OracleJDK参考文末 安装OracleJDK Linux环境安装卸载JDK以及安装Tomcat和发布Java的web程序 安装依赖 | Install dependence # yum -y install gcc gcc-c alsa-lib alsa-…
最快69秒逆向DRAM地址映射,百度设计的这款逆向工具如何做到快速可靠?
来源 | 百度安全实验室出品 | AI科技大本营(ID:rgznai100)导读:近日,国际顶级设计自动化大会DAC大会公布DAC 2020会议议程和论文名单,由百度安全发表的《DRAMDig: AKnowledge-assisted Tool to Uncover DRAM Address M…

国外厂商在行业客户上输单的原因
这两天听一个朋友聊天发泄,他在一家总代J公司工作,代理业内排行第一的国外厂商C公司的产品,他负责D行业在南方某几个省的销售业务,工作中需要与C公司的销售紧密配合。经过接近一年的工作,他拿到一些项目,但…

[android] 从gallery获取图片
效果就是点击按钮,打开系统图库应用,可以选择一张里面的图片展示出来 设置隐式意图 获取Intent对象,通过new出来 调用Intent对象的setAction()方法,设置动作,参数:Intent.ACTION_PICK 调用Intent对象的setT…
调试JDK源码-HashSet实现原理
调试JDK源码-一步一步看HashMap怎么Hash和扩容 调试JDK源码-ConcurrentHashMap实现原理 调试JDK源码-HashSet实现原理 调试JDK源码-调试JDK源码-Hashtable实现原理以及线程安全的原因 代码 Set<String> snew HashSet<String>();s.add("http://blog.csdn.ne…
Python 炫技操作:海象运算符的三种用法
作者 | 明哥来源 | Python编程时光(ID:Cool-Python)Python 版本发展非常快,如今最新的版本已经是 Pyhton 3.9,即便如此,有很多人甚至还停留在 3.6 或者 3.7,连 3.8 还没用上。很多 Python 3.8 的特性还没来…

2010.10.30 OA 项目组一周工作报告
本周基本上实现了上周的目标,但和计划相比有落后。 进度:55 本周提交了3.0任务评估的第一个版本,一共为1003小时,客户收到该评估后,对3.0任务进行了调整,将部分任务移到2011.2版本中,同时添加了…

继承log4.net的类
using System; using System.Diagnostics;[assembly: log4net.Config.XmlConfigurator(Watch true)] namespace Hbl.Core {public static class Log{/// <summary>/// 一般错误/// </summary>/// <param name"message">消息</param>public …
调试JDK源码-Hashtable实现原理以及线程安全的原因
调试JDK源码-一步一步看HashMap怎么Hash和扩容 调试JDK源码-ConcurrentHashMap实现原理 调试JDK源码-HashSet实现原理 调试JDK源码-调试JDK源码-Hashtable实现原理以及线程安全的原因 Hashtable是线程安全的,我们从源码来分析 代码很简单 Hashtable<String, …

源代码查看工具 Source Navigator 使用心得
在ubuntu 10.04下试用了Source Navigator,有条件还是装Source insight吧,不是一个级别的,非常不方便。 Source Navigator 是Red Hat出品的一款查看源代码的工具,非常好用,与Windows下的Source Insight有一敌。但是它的…
那个分分钟处理10亿节点图计算的Plato,现在怎么样了?
受访者 | 于东海记者 | 夕颜出品 | CSDN(ID:CSDNnews)「AI 技术生态论」 人物访谈栏目是 CSDN 发起的百万人学 AI 倡议下的重要组成部分。通过对 AI 生态顶级大咖、创业者、行业 KOL 的访谈,反映其对于行业的思考、未来趋势的判断、技术的实践…

android TextView里边实现图文混配效果
做的游戏攻略中的图文载入已经用TextView实现。但看到网易新闻里的内容。点击图片能够调到一个新的Activity ,感觉也像Textview 实现的,但不知道怎么弄,想想能够通过动态载入Textview和ImageView 布局实现,但当量大的时候回事很复…