springmvc使用和經(jīng)驗總結(jié)(長沙師說網(wǎng)絡(luò)科技有限公司)
springmvc
先分析下代碼,快速學(xué)習(xí),先要把配置文件寫好,
給上2個類具體看看
package com.shishuo.studio.action;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.RequestParam;
import com.shishuo.studio.constant.SystemConstant;
import com.shishuo.studio.entity.Category;
import com.shishuo.studio.entity.vo.CourseVo;
import com.shishuo.studio.entity.vo.PageVo;
import com.shishuo.studio.exception.CategoryNotFoundException;
import com.shishuo.studio.exception.notfound.StorageNotFoundException;
import com.shishuo.studio.service.CategoryService;
import com.shishuo.studio.service.UserService;
/**
* @author Herbert
*
*/
@Controller
@RequestMapping("/category")
public class CategoryAction extends BaseAction {
protected final Logger logger = Logger.getLogger(this.getClass());
@Autowired
protected CategoryService categoryService;
@Autowired
protected UserService userService;
/**
* 首頁
*
* @param modelMap
* @return
*/
@RequestMapping(value = "/{categoryId}.htm", method = RequestMethod.GET)
public String category(@PathVariable long categoryId, ModelMap modelMap,
@RequestParam(value = "p", defaultValue = "1") int p) {
try {
// 獲得數(shù)據(jù)
Category category = categoryService.getCategoryById(categoryId);
// 獲取當(dāng)前目錄下的所有課程
PageVo<CourseVo> coursePageVo = courseService
.getCoursePageByIdForUser(categoryId, p, 24);
// 增加屬性
modelMap.addAttribute("category", category);
modelMap.put("coursePageVo", coursePageVo);
return "category";
} catch (CategoryNotFoundException e) {
return SystemConstant.PAGE_404;
} catch (StorageNotFoundException e) {
// TODO Auto-generated catch block
return SystemConstant.PAGE_404;
}
}
}
package com.shishuo.studio.action;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shishuo.studio.action.auth.AuthBaseAction;
@Controller
@RequestMapping("/about")
public class AboutAction extends AuthBaseAction {
/**
* 跳轉(zhuǎn)到關(guān)于我們頁面
*
* @param modelMap
* @param request
* @return
*/
@RequestMapping(value = "/about.htm", method = RequestMethod.GET)
public String about(ModelMap modelMap, HttpServletRequest request) {
return "/about/about";
}
/**
* 跳轉(zhuǎn)到服務(wù)協(xié)議頁面
*
* @param modelMap
* @param request
* @return
*/
@RequestMapping(value = "/service.htm", method = RequestMethod.GET)
public String service(ModelMap modelMap, HttpServletRequest request) {
return "/about/service";
}
/**
* 跳轉(zhuǎn)到投訴舉報頁面
*
* @param modelMap
* @param request
* @return
*/
@RequestMapping(value = "/complain.htm", method = RequestMethod.GET)
public String complain(ModelMap modelMap, HttpServletRequest request) {
return "/about/complain";
}
/**
* 跳轉(zhuǎn)到版權(quán)聲明頁面
*
* @param modelMap
* @param request
* @return
*/
@RequestMapping(value = "/copyright.htm", method = RequestMethod.GET)
public String copyright(ModelMap modelMap, HttpServletRequest request) {
return "/about/copyright";
}
/**
* 跳轉(zhuǎn)到聯(lián)系我們頁面
*
* @param modelMap
* @param request
* @return
*/
@RequestMapping(value = "/connect.htm", method = RequestMethod.GET)
public String connect(ModelMap modelMap, HttpServletRequest request) {
return "/about/connect";
}
}
return "system/comment/comment";后面不需要東西
return "redirect:/admin/comment/page.htm";一般當(dāng)我改變一個狀態(tài)的時候 我需要還是顯示在當(dāng)前頁面 就需要再進(jìn)入Action 相當(dāng)于再到數(shù)據(jù)庫訪問一次把 我改變的數(shù)據(jù)同個pageVo 顯示到頁面
spring的注解學(xué)習(xí)
@RequestParam("description") String description,
@PathVariable
請求路徑上有個id的變量值,可以通過@PathVariable來獲取 @RequestMapping(value = "/page/{id}", method = RequestMethod.GET)
@autowired 自動配置 不需要寫getter() setter()方法
@Deprecated 過時
@Repository 用在接口前面的類 比如ibits接口類的最前面
@ResponseBody當(dāng)控制器返回頁面不是字符串的時候 比如返回一個json對象用這個注解
@Controller控制器 加在控制器類的最前面
@RequestMapping("/admin/file")
放在類前面是這個路徑下
@RequestMapping(value = "/index.htm", method = RequestMethod.GET)如果這個注解放在方法的前面 表示上面那個路徑的基礎(chǔ)下然后再是這個路勁
@RequestParam(value = "fileId", defaultValue = "1")當(dāng)url傳入?yún)?shù)的時候就可以拿到值
比如@RequestMapping(value = "/update.htm", method = RequestMethod.GET)
public String update(
@RequestParam(value = "fileId", defaultValue = "1") long fileId,
ModelMap modelMap) throws Exception {}
相關(guān)配置文件如下
復(fù)制spring相關(guān)jar包到web-inf/lib里面
然后在web.xml加入
相當(dāng)于springmvc的servlet
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
然后在application.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 自動掃描的包名 -->
<context:component-scan base-package="com.shishuo.studio"></context:component-scan>
<mvc:annotation-driven />
<task:annotation-driven />
<tx:annotation-driven />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.shishuo.studio.filter.GlobalInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/auth/**" />
<bean class="com.shishuo.studio.filter.AuthInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/auth/studio/**" />
<bean class="com.shishuo.studio.filter.StudioInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 在XML配置文件中加入外部屬性文件,當(dāng)然也可以指定外部文件的編碼 -->
<bean id="propertyConfigurer" class="com.shishuo.studio.util.PropertyUtils">
<property name="locations">
<list>
<value>classpath:shishuo.studio.properties</value> <!-- 指定外部文件的編碼 -->
</list>
</property>
</bean>
<!-- FreeMarker的配置 -->
<bean id="freeMarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl" /><!--
指定路徑 -->
<property name="defaultEncoding" value="UTF-8" /><!-- 指定編碼格式 -->
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">10</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="classic_compatible">true</prop>
</props>
</property>
</bean>
<!-- 配置 FreeMarker視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
<property name="cache" value="false" />
<property name="prefix" value="/" />
<property name="suffix" value=".ftl" /><!--可為空,方便實現(xiàn)自已的依據(jù)擴(kuò)展名來選擇視圖解釋類的邏輯 -->
<property name="contentType" value="text/html;charset=utf-8" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
</bean>
</beans>
@Component,@Service,@Controller,@Repository注解的類,并把這些類納入進(jìn)spring容器中管理。它的作用和在xml文件中使用bean節(jié)點配置組件時一樣的。
@Component Component是Spring管理組件的通用形式,而@repository,@Service,@Controller是它的細(xì)化。分別表示更加具體的用例(分別對應(yīng)持久化層,服務(wù)層和表現(xiàn)層)
B、按照Class路徑掃描
XML風(fēng)格的配置方式,我們會在配置文件中配置大量的bean,這樣但項目足夠大時,那么這個配置文件將過于龐大而不便管理。而應(yīng)用@注釋的配置方式,我們在類中用@Component等注釋類,并讓容器按照Classpath自動掃描管理它們。要實現(xiàn)以上功能我們需要這樣定義。
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="org.example" />
</beans>
在使用組件掃描時,AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor也將隱式包含進(jìn)來,也就是說它支持@Autowired等,不需要我們?nèi)缬?lt;context:annotation-config/>再做聲明了。。
自動掃描包名的配置 <context:component-scan base-package="com.shishuo"></context>
當(dāng)我們用spring mvc 前端控制器的時候需要配置
<!-- spring mvc 基于注解在方法上 控制映射 配置 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<!-- 在XML配置文件中加入外部屬性文件,當(dāng)然也可以指定外部文件的編碼 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:shishuocms.properties</value> <!-- 指定外部文件的編碼 -->
</list>
</property>
</bean>
<!-- 配置 FreeMarker視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
<property name="cache" value="false" />
<property name="prefix" value="/" />
<property name="suffix" value=".ftl" /><!--可為空,方便實現(xiàn)自已的依據(jù)擴(kuò)展名來選擇視圖解釋類的邏輯 -->
<property name="contentType" value="text/html;charset=utf-8" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
</bean>
<!--創(chuàng)建數(shù)據(jù)映射器,數(shù)據(jù)映射器必須為接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
<property name="basePackage" value="com.shishuo.cms.dao" />
</bean>
spring mvc 攔截器
攔截器在application.xml配置
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.shishuo.cms.filter.GlobalInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
怎么使用RequestMapping的參數(shù) 主要有RequestParam Pathvariable(這個注解是獲取url里面的參數(shù))
5.1.1、常見應(yīng)用場景
1、日志記錄:記錄請求信息的日志,以便進(jìn)行信息監(jiān)控、信息統(tǒng)計、計算PV(Page View)等。
2、權(quán)限檢查:如登錄檢測,進(jìn)入處理器檢測檢測是否登錄,如果沒有直接返回到登錄頁面;
3、性能監(jiān)控:有時候系統(tǒng)在某段時間莫名其妙的慢,可以通過攔截器在進(jìn)入處理器之前記錄開始時間,在處理完后記錄結(jié)束時間,從而得到該請求的處理時間(如果有反向代理,如apache可以自動記錄);
4、通用行為:讀取cookie得到用戶信息并將用戶對象放入請求,從而方便后續(xù)流程使用,還有如提取Locale、Theme信息等,只要是多個處理器都需要的即可使用攔截器實現(xiàn)。
5、OpenSessionInView:如Hibernate,在進(jìn)入處理器打開Session,在完成后關(guān)閉Session。
…………本質(zhì)也是AOP(面向切面編程),也就是說符合橫切關(guān)注點的所有功能都可以放入攔截器實現(xiàn)。
MySQL server version for the right syntax to use near where userId=28 at line 1
這個錯誤是在寫修改語句的時候 where 前面多加了一個逗號
syntax error 是語法錯誤
Could not resolve view with name 'auth/teacher/skill/update' in servlet with是自己沒有加@Responsebody 用spring mvc 的時候返回是json 一定要記得寫@Responsebody
當(dāng)需要上傳一個form里面包含 文件 或者視屏的時候 一定要記得在form表單后面添加 enctype="multipart/form-data" enctype="multipart/form-data"
@RequestParam @RequestBody @PathVariable 等參數(shù)綁定注解詳解
分類: spring 2012-09-21 16:22 11494人閱讀 評論(4) 收藏 舉報
目錄(?)[+]
引言:
接上一篇文章,對@RequestMapping進(jìn)行地址映射講解之后,該篇主要講解request 數(shù)據(jù)到handler method 參數(shù)數(shù)據(jù)的綁定所用到的注解和什么情形下使用;
簡介:
handler method 參數(shù)綁定常用的注解,我們根據(jù)他們處理的Request的不同內(nèi)容部分分為四類:(主要講解常用類型)
A、處理requet uri 部分(這里指uri template中variable,不含queryString部分)的注解: @PathVariable;
B、處理request header部分的注解: @RequestHeader, @CookieValue;
C、處理request body部分的注解:@RequestParam, @RequestBody;
D、處理attribute類型是注解: @SessionAttributes, @ModelAttribute;
作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)