springMVC环境搭建
1.在myeclipse上建立web projectproject选择加入mavenproject add maven support
2.选择建立web.xml文件,名字随意
3.选择standard Maven JEEproject structure
4.点击取消两个环境依赖
5.之后形成例如以下文件夹(由于我这个文件夹是git文件夹所以有一些版本号控制信息)
会有报错信息是由于没有jsp和servlet的jar包
6.增加jsp和servlet的jar包
<span style="white-space:pre"> </span><!-- jstl begin--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <type>jar</type> </dependency> <!-- jstl end--> <!-- servlet,jsp begin--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- servlet,jsp end-->
报错信息解决
7.添加springmvc的jar包和日志包
<!-- springmvc begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>4.0.8.RELEASE</version> </dependency> <!-- springmvc end --> <!-- LOGGING begin --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- common-logging 实际调用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.7</version> </dependency> <!-- java.util.logging 实际调用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>1.7.7</version> </dependency> <!-- LOGGING end -->
8.web.xml中添加springMVC的配置和监听
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>springmvc</display-name> <!-- Context ConfigLocation --> <listener> <!-- 监听器的作用就是启动Web容器时,自己主动装配ApplicationContext的配置信息 --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 载入spring相关的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:/spring/spring-context*.xml </param-value> </context-param> <listener> <!-- 使Spring支持request与session的scope,如 --> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- 解决乱码 过滤器 --> <filter> <filter-name>encodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- SpringMVC 载入配置文件 --> <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/spring-mvc*.xml</param-value> </init-param> <!-- 设置启动顺序 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 日志配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/properties/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 配置错误信息 --> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> </web-app>
9.添加工具类jar包
<span style="white-space:pre"> </span><!-- jackson json begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>2.2.3</version> </dependency> <!-- jackson json end --> <!-- GENERAL UTILS begin --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.1</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- google java lib --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency> <!-- JSON begin --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160212</version> </dependency> <!-- JSON end -->
10.添加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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <description>Spring MVC Configuration</description> <!-- 载入配置属性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:/properties/config.properties" /> <!-- 使用Annotation自己主动注冊Bean,仅仅扫描@Controller --> <context:component-scan base-package="com" use-default-filters="false"><!-- base-package 假设多个,用“,”分隔 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 定义视图文件解析 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="${web.view.prefix}"/> <property name="suffix" value="${web.view.suffix}"/> </bean> <!-- 默认的注解映射的支持,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping --> <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"> <mvc:message-converters register-defaults="true"> <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> <!-- 把ByteArray加在Json前面 ,先处理下载文件,不是下载的文件之后用json拦截 --> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <!-- 将Jackson2HttpMessageConverter的默认格式化输出为false --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list><value>application/json;charset=UTF-8</value></list> </property> <property name="prettyPrint" value="false"/> <property name="objectMapper"> <bean class="com.utils.JsonMapper"></bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- REST中依据URL后缀自己主动判定Content-Type及对应的View --> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="mediaTypes" > <map> <entry key="xml" value="application/xml"/> <entry key="json" value="application/json"/> </map> </property> <property name="ignoreAcceptHeader" value="true"/> <property name="favorPathExtension" value="true"/> </bean> <!-- 静态资源映射 --> <mvc:annotation-driven /> <!-- 静态资源映射 --> <mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/> <!-- 定义无Controller的path<->view直接映射 --> <mvc:view-controller path="/" view-name="redirect:${web.view.index}"/> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Throwable">error/500</prop> </props> </property> </bean> <!-- 支持Shiro对Controller的方法级AOP安全控制 end --> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="${web.maxUploadSize}" /> </bean> </beans>
spring-context.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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="true"> </beans>
log4j
# This is the configuring for logging displayed in the Application Server log4j.rootCategory=error,stdout,logfile log4j.logger.com=info #log4j.logger.org.hibernate=info log4j.logger.org.springframework=info #stdout configure log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH\:mm\:ss}]%-5p %c(line\:%L) %x-%m%n #logfile configure log4j.appender.logfile=org.apache.log4j.RollingFileAppender #log4j.appender.logfile.File=${catalina.base}/logs/i-test.log log4j.appender.logfile.File=quartz.log log4j.appender.logfile.MaxFileSize=1024kb log4j.appender.logfile.MaxBackupIndex=10 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern= [%d{yyyy-MM-dd HH\:mm\:ss}]%-5p %c(line\:%L) %x-%m%n
config.properties
#============================# #===== SpringMVC sttings =====# #============================# #索引页路径 web.view.index=/ #视图文件存放路径 web.view.prefix=/WEB-INF/views/ web.view.suffix=.jsp #最大文件上传限制,单位字节. 10M=10*1024*1024(B)=10485760 bytes,需同步改动:ckfinder.xml web.maxUploadSize=10485760
11.添加自己主动转换工具类
/** * Copyright © 2015-2016 <a href="http://www.cyou-inc.com">peace</a> All rights reserved. */ package com.utils; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.util.JSONPObject; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * 简单封装Jackson。实现JSON String<->Java Object的Mapper. * 封装不同的输出风格, 使用不同的builder函数创建实例. * @author ThinkGem * @version 2013-11-15 */ public class JsonMapper extends ObjectMapper { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(JsonMapper.class); private static JsonMapper mapper; public JsonMapper() { this(Include.NON_EMPTY); } public JsonMapper(Include include) { // 设置输出时包括属性的风格 if (include != null) { this.setSerializationInclusion(include); } // 同意单引號、同意不带引號的字段名称 this.enableSimple(); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 空值处理为空串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){ @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(""); } }); // 进行HTML解码。this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>(){ @Override public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(StringEscapeUtils.unescapeHtml4(value)); } })); // 设置时区 this.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT+8:00") } /** * 创建仅仅输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用. */ public static JsonMapper getInstance() { if (mapper == null){ mapper = new JsonMapper().enableSimple(); } return mapper; } /** * 创建仅仅输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式。建议在内部接口中使用。 */ public static JsonMapper nonDefaultMapper() { if (mapper == null){ mapper = new JsonMapper(Include.NON_DEFAULT); } return mapper; } /** * Object能够是POJO,也能够是Collection或数组。
* 假设对象为Null, 返回"null". * 假设集合为空集合, 返回"[]". */ public String toJson(Object object) { try { return this.writeValueAsString(object); } catch (IOException e) { logger.warn("write to json string error:" + object, e); return null; } } /** * 反序列化POJO或简单Collection如List<String>. * * 假设JSON字符串为Null或"null"字符串, 返回Null. * 假设JSON字符串为"[]", 返回空集合. * * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType) * @see #fromJson(String, JavaType) */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return this.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数. * @see #createCollectionType(Class, Class...) */ @SuppressWarnings("unchecked") public <T> T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) this.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 構造泛型的Collection Type如: * ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class) * HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class) */ public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return this.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * 當JSON裡仅仅含有Bean的部分屬性時,更新一個已存在Bean,仅仅覆蓋該部分的屬性. */ @SuppressWarnings("unchecked") public <T> T update(String jsonString, T object) { try { return (T) this.readerForUpdating(object).readValue(jsonString); } catch (JsonProcessingException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } catch (IOException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } return null; } /** * 輸出JSONP格式數據. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * 設定是否使用Enum的toString函數來讀寫Enum, * 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. * 注意本函數一定要在Mapper創建後, 全部的讀寫動作之前調用. */ public JsonMapper enableEnumUseToString() { this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); return this; } /** * 支持使用Jaxb的Annotation。使得POJO上的annotation不用与Jackson耦合。 * 默认会先查找jaxb的annotation,假设找不到再找jackson的。
*/ public JsonMapper enableJaxbAnnotation() { JaxbAnnotationModule module = new JaxbAnnotationModule(); this.registerModule(module); return this; } /** * 同意单引號 * 同意不带引號的字段名称 */ public JsonMapper enableSimple() { this.configure(Feature.ALLOW_SINGLE_QUOTES, true); this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return this; } /** * 取出Mapper做进一步的设置或使用其它序列化API. */ public ObjectMapper getMapper() { return this; } /** * 对象转换为JSON字符串 * @param object * @return */ public static String toJsonString(Object object){ return JsonMapper.getInstance().toJson(object); } /** * JSON字符串转换为对象 * @param jsonString * @param clazz * @return */ public static Object fromJsonString(String jsonString, Class<?> clazz){ return JsonMapper.getInstance().fromJson(jsonString, clazz); } /** * 測试 */ public static void main(String[] args) { List<Map<String, Object>> list = Lists.newArrayList(); Map<String, Object> map = Maps.newHashMap(); map.put("id", 1); map.put("pId", -1); map.put("name", "根节点"); list.add(map); map = Maps.newHashMap(); map.put("id", 2); map.put("pId", 1); map.put("name", "你好"); map.put("open", true); list.add(map); String json = JsonMapper.getInstance().toJson(list); System.out.println(json); } }
12.測试工具
package com.entity; public class User { private String id; private String username; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.web; import java.util.UUID; 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.ResponseBody; import com.entity.User; @Controller public class LoginController { /** * 正常測试跳转 */ @RequestMapping({"/login","/"}) public String login(Model model){ model.addAttribute("message", "OK"); return "login"; } /** * 自己主动封装json */ @ResponseBody @RequestMapping("/json") public User json(){ User user = new User(); user.setId(UUID.randomUUID().toString().replace("-", "")); user.setUsername("username"); user.setPassword("password"); return user; } /** * restfull请求封装 */ @RequestMapping("/restfull/{content}") public String restfull(@PathVariable("content")String content,Model model){ model.addAttribute("message", content); return "login"; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> ${message }<br> </body> </html>