Spring里面最重要的概念是IOC和AOP,还有两项很重要的模块是事务和MVC,对于IOC和AOP,我们要深究其源码实现,对于事务,我们务必理解。对于MVC,Spring MVC提供的功能很多、很先进,但我们一般只要用其中的一小部分就可以满足我们的开发需求,另外,我们并不建议你排斥Struts2,因为它也是经过无数公司验证过的优秀的框架。本文给出spring mvc简单配置和部分代码举例。
WEB-INF/web.xml
- <?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"
- metadata-complete="true">
- <display-name>ixhong-admin-web</display-name>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-context.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <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>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>characterEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <servlet>
- <servlet-name>spring-mvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring-velocity.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>spring-mvc</servlet-name>
- <url-pattern>*.xyz</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>/index.html</welcome-file>
- </welcome-file-list>
- <error-page>
- <error-code>404</error-code>
- <location>/404_error.html</location>
- </error-page>
- </web-app>
WEB-INF/velocity-tools.xml
- <toolbox>
- <tool>
- <key>stringUtils</key>
- <scope>application</scope>
- <class>org.apache.commons.lang.StringUtils</class>
- </tool>
- <tool>
- <key>dateFormatUtils</key>
- <scope>application</scope>
- <class>org.apache.commons.lang.time.DateFormatUtils</class>
- </tool>
- <tool>
- <key>escapeUtils</key>
- <scope>application</scope>
- <class>org.apache.commons.lang.StringEscapeUtils</class>
- </tool>
- </toolbox>
spring-velocity.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- 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-3.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd"
- default-autowire="byName">
- <!-- -->
- <mvc:annotation-driven>
- <mvc:message-converters>
- <bean class="org.springframework.http.converter.StringHttpMessageConverter">
- <property name = "supportedMediaTypes">
- <list>
- <value>text/plain;charset=UTF-8</value>
- <value>text/html;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <context:component-scan base-package="com.architectj.admin.web.controller"/>
- <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
- <property name="resourceLoaderPath" value="/WEB-INF/vm"/>
- <property name="configLocation" value="classpath:velocity.properties"/>
- </bean>
- <!-- 上传数据大小 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="maxUploadSize" value="5242880"/><!-- 最大5M -->
- </bean>
- <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
- </bean>
- <bean id="exceptionResolver" class="com.architectj.admin.web.ExceptionHandler"/>
- <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
- <property name="suffix" value=".vm"/>
- <property name="layoutUrl" value="layout/default.vm"/>
- <!-- 使用springMacro、使用servlet的对象 -->
- <property name="exposeSpringMacroHelpers" value="true"/>
- <property name="exposeRequestAttributes" value="true"/>
- <property name="exposeSessionAttributes" value="true"/>
- <property name="contentType" value="text/html;charset=UTF-8"/>
- <!-- spring的日期格式化 -->
- <property name="dateToolAttribute" value="dateTool"/>
- <property name="toolboxConfigLocation" value="/WEB-INF/velocity-tools.xml"/>
- <property name="attributesMap">
- <map>
- </map>
- </property>
- </bean>
- <mvc:interceptors>
- <mvc:interceptor>
- <mvc:mapping path="/user/**" />
- <mvc:mapping path="/teacher/**"/>
- <bean class="com.architectj.admin.web.interceptor.LoginInterceptor" />
- </mvc:interceptor>
- <mvc:interceptor>
- <mvc:mapping path="/user/**" />
- <mvc:mapping path="/teacher/**"/>
- <bean class="com.architectj.admin.web.interceptor.SecurityInterceptor" />
- </mvc:interceptor>
- <mvc:interceptor>
- <mvc:mapping path="/user/**"/>
- <mvc:mapping path="/teacher/**"/>
- <bean class="com.architectj.admin.web.interceptor.PermissionInterceptor"/>
- </mvc:interceptor>
- </mvc:interceptors>
- </beans>
velocity.properties
- #encoding
- input.encoding=UTF-8
- output.encoding=UTF-8
- contentType=text/html;charset=UTF-8
- #autoreload when vm changed
- resource.loader=file
- file.resource.loader.class=org.apache.velocity.runtime.resource.loader.FileResourceLoader
- file.resource.loader.cache=false
- file.resource.loader.modificationCheckInterval=1
- velocimacro.library.autoreload=true
- velocimacro.library=macro.vm
macro.vm
- #macro(pagination $targetUrl $queryResult)
- <div id="kkpager"></div>
- <script type="text/javascript" src="/lib/kkpager.min.js"></script>
- <script type="text/javascript">
- //init
- $(function(){
- //生成分页
- //有些参数是可选的,比如lang,若不传有默认值
- kkpager.generPageHtml({
- //当前页码
- pno : $!{query.currentPage},
- //总页码
- total : $!{queryResult.totalPage},
- //总数据条数
- totalRecords : $!{queryResult.amount},
- //链接前部
- hrefFormer : '$targetUrl',
- //链接尾部
- hrefLatter : '',
- getLink : function(n){
- if (n == 1){
- return this.hrefFormer;
- }
- return this.hrefFormer + "&page="+n;
- }
- });
- });
- </script>
- #end
LoginInterceptor
- public class LoginInterceptor implements HandlerInterceptor{
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- // 解析cookie得到source
- UserDO user = this.decoder(source);
- LoginContext context = new LoginContext();
- context.setUser(user);
- LoginContextHolder.set(context);
- return true;
- }
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
- if(modelAndView != null) {
- modelAndView.addObject("xxx",LoginContextHolder.getLoginUser());
- }
- }
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- LoginContextHolder.clear();
- }
- protected UserDO decoder(String content){
- // ...
- return user;
- }
- }
SecurityInterceptor
- public class SecurityInterceptor implements HandlerInterceptor{
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- LoginContext loginContext = LoginContextHolder.get();
- if(loginContext != null && loginContext.getUser() != null) {
- return true;
- }
- response.sendRedirect("/login.xyz");//登陆
- return false;
- }
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
- }
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- }
- }
Controller
- @Controller
- public class IndexController extends BaseController{
- @Autowired
- private AdminService adminService;
- @RequestMapping("/login")
- public ModelAndView login(HttpServletRequest request,HttpServletResponse response) {
- ModelAndView mav = new ModelAndView();
- if (LoginContextHolder.getLoginUser() != null){
- mav.setViewName("redirect:/yyy/list.xyz");
- }
- return mav;
- }
- @RequestMapping(value = "xxxxxx", method = {RequestMethod.POST, RequestMethod.GET})
- @ResponseBody
- public String loginAction(@RequestParam("name") String name, @RequestParam("password") String password,
- @RequestParam("code") String code,
- HttpServletRequest request,HttpServletResponse response) {
- if(LoginContextHolder.getLoginUser() != null){
- Result result = new Result();
- result.setSuccess(true);
- return ResultHelper.renderAsJson(result);
- }
- //验证码校验
- // ...
- Result result = this.adminService.login(name.trim(), password);
- // ...
- return ResultHelper.renderAsJson(result);
- }
- }
附:velocity注释是 ## 注释掉的东西不会再html源码里显示,而<!--会显示,模版引擎/编译器会做忽略的事情,HTML的注释不会忽略
原文链接:[http://wely.iteye.com/blog/2278604]