关键词搜索

源码搜索 ×
×

springmvc使用和经验总结(长沙师说网络科技有限公司)

发布2015-08-19浏览3820次

详情内容

springmvc

先分析下代码,快速学习,先要把配置文件写好,

给上2个类具体看看

 

  1. package com.shishuo.studio.action;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.ModelMap;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import com.shishuo.studio.constant.SystemConstant;
  11. import com.shishuo.studio.entity.Category;
  12. import com.shishuo.studio.entity.vo.CourseVo;
  13. import com.shishuo.studio.entity.vo.PageVo;
  14. import com.shishuo.studio.exception.CategoryNotFoundException;
  15. import com.shishuo.studio.exception.notfound.StorageNotFoundException;
  16. import com.shishuo.studio.service.CategoryService;
  17. import com.shishuo.studio.service.UserService;
  18. /**
  19. * @author Herbert
  20. *
  21. */
  22. @Controller
  23. @RequestMapping("/category")
  24. public class CategoryAction extends BaseAction {
  25. protected final Logger logger = Logger.getLogger(this.getClass());
  26. @Autowired
  27. protected CategoryService categoryService;
  28. @Autowired
  29. protected UserService userService;
  30. /**
  31. * 首页
  32. *
  33. * @param modelMap
  34. * @return
  35. */
  36. @RequestMapping(value = "/{categoryId}.htm", method = RequestMethod.GET)
  37. public String category(@PathVariable long categoryId, ModelMap modelMap,
  38. @RequestParam(value = "p", defaultValue = "1") int p) {
  39. try {
  40. // 获得数据
  41. Category category = categoryService.getCategoryById(categoryId);
  42. // 获取当前目录下的所有课程
  43. PageVo<CourseVo> coursePageVo = courseService
  44. .getCoursePageByIdForUser(categoryId, p, 24);
  45. // 增加属性
  46. modelMap.addAttribute("category", category);
  47. modelMap.put("coursePageVo", coursePageVo);
  48. return "category";
  49. } catch (CategoryNotFoundException e) {
  50. return SystemConstant.PAGE_404;
  51. } catch (StorageNotFoundException e) {
  52. // TODO Auto-generated catch block
  53. return SystemConstant.PAGE_404;
  54. }
  55. }
  56. }

 

  1. package com.shishuo.studio.action;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.ModelMap;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import com.shishuo.studio.action.auth.AuthBaseAction;
  8. @Controller
  9. @RequestMapping("/about")
  10. public class AboutAction extends AuthBaseAction {
  11. /**
  12. * 跳转到关于我们页面
  13. *
  14. * @param modelMap
  15. * @param request
  16. * @return
  17. */
  18. @RequestMapping(value = "/about.htm", method = RequestMethod.GET)
  19. public String about(ModelMap modelMap, HttpServletRequest request) {
  20. return "/about/about";
  21. }
  22. /**
  23. * 跳转到服务协议页面
  24. *
  25. * @param modelMap
  26. * @param request
  27. * @return
  28. */
  29. @RequestMapping(value = "/service.htm", method = RequestMethod.GET)
  30. public String service(ModelMap modelMap, HttpServletRequest request) {
  31. return "/about/service";
  32. }
  33. /**
  34. * 跳转到投诉举报页面
  35. *
  36. * @param modelMap
  37. * @param request
  38. * @return
  39. */
  40. @RequestMapping(value = "/complain.htm", method = RequestMethod.GET)
  41. public String complain(ModelMap modelMap, HttpServletRequest request) {
  42. return "/about/complain";
  43. }
  44. /**
  45. * 跳转到版权声明页面
  46. *
  47. * @param modelMap
  48. * @param request
  49. * @return
  50. */
  51. @RequestMapping(value = "/copyright.htm", method = RequestMethod.GET)
  52. public String copyright(ModelMap modelMap, HttpServletRequest request) {
  53. return "/about/copyright";
  54. }
  55. /**
  56. * 跳转到联系我们页面
  57. *
  58. * @param modelMap
  59. * @param request
  60. * @return
  61. */
  62. @RequestMapping(value = "/connect.htm", method = RequestMethod.GET)
  63. public String connect(ModelMap modelMap, HttpServletRequest request) {
  64. return "/about/connect";
  65. }
  66. }

 

return "system/comment/comment";后面不需要东西

return "redirect:/admin/comment/page.htm";一般当我改变一个状态的时候 我需要还是显示在当前页面 就需要再进入Action 相当于再到数据库访问一次把 我改变的数据同个pageVo 显示到页面

 

spring的注解学习
@RequestParam("description") String description,
@PathVariable
请求路径上有个id的变量值,可以通过@PathVariable来获取  @RequestMapping(value = "/page/{id}", method = RequestMethod.GET) 
@autowired 自动配置 不需要写getter() setter()方法
@Deprecated  过时
@Repository 用在接口前面的类 比如ibits接口类的最前面
@ResponseBody当控制器返回页面不是字符串的时候 比如返回一个json对象用这个注解
@Controller控制器 加在控制器类的最前面
@RequestMapping("/admin/file")
放在类前面是这个路径下
@RequestMapping(value = "/index.htm", method = RequestMethod.GET)如果这个注解放在方法的前面 表示上面那个路径的基础下然后再是这个路劲
@RequestParam(value = "fileId", defaultValue = "1")当url传入参数的时候就可以拿到值
比如@RequestMapping(value = "/update.htm", method = RequestMethod.GET)
public String update(
@RequestParam(value = "fileId", defaultValue = "1") long fileId,
ModelMap modelMap) throws Exception {}

 
相关配置文件如下
复制spring相关jar包到web-inf/lib里面
然后在web.xml加入
相当于springmvc的servlet
  1. <servlet>
  2. <servlet-name>spring</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <init-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>classpath:applicationContext.xml</param-value>
  7. </init-param>
  8. <load-on-startup>1</load-on-startup>
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>spring</servlet-name>
  12. <url-pattern>*.htm</url-pattern>
  13. </servlet-mapping>
  14. <servlet-mapping>
  15. <servlet-name>spring</servlet-name>
  16. <url-pattern>*.json</url-pattern>
  17. </servlet-mapping>
然后在application.xml里面配置
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.orghttps://cdn.jxasp.com:9143/image/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/tx
  9. http://www.springframework.org/schema/tx/spring-tx.xsd
  10. http://www.springframework.org/schema/aop
  11. http://www.springframework.org/schema/aop/spring-aop.xsd
  12. http://www.springframework.org/schema/mvc
  13. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  14. http://www.springframework.org/schema/context
  15. http://www.springframework.org/schema/context/spring-context.xsd
  16. http://www.springframework.org/schema/task
  17. http://www.springframework.org/schema/task/spring-task.xsd">
  18. <!-- 自动扫描的包名 -->
  19. <context:component-scan base-package="com.shishuo.studio"></context:component-scan>
  20. <mvc:annotation-driven />
  21. <task:annotation-driven />
  22. <tx:annotation-driven />
  23. <bean
  24. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  25. <bean
  26. class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  27. <mvc:interceptors>
  28. <mvc:interceptor>
  29. <mvc:mapping path="/**" />
  30. <bean class="com.shishuo.studio.filter.GlobalInterceptor"></bean>
  31. </mvc:interceptor>
  32. <mvc:interceptor>
  33. <mvc:mapping path="/auth/**" />
  34. <bean class="com.shishuo.studio.filter.AuthInterceptor"></bean>
  35. </mvc:interceptor>
  36. <mvc:interceptor>
  37. <mvc:mapping path="/auth/studio/**" />
  38. <bean class="com.shishuo.studio.filter.StudioInterceptor"></bean>
  39. </mvc:interceptor>
  40. </mvc:interceptors>
  41. <!-- 在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码 -->
  42. <bean id="propertyConfigurer" class="com.shishuo.studio.util.PropertyUtils">
  43. <property name="locations">
  44. <list>
  45. <value>classpath:shishuo.studio.properties</value> <!-- 指定外部文件的编码 -->
  46. </list>
  47. </property>
  48. </bean>
  49. <!-- FreeMarker的配置 -->
  50. <bean id="freeMarkerConfigurer"
  51. class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  52. <property name="templateLoaderPath" value="/WEB-INF/ftl" /><!--
  53. 指定路径 -->
  54. <property name="defaultEncoding" value="UTF-8" /><!-- 指定编码格式 -->
  55. <property name="freemarkerSettings">
  56. <props>
  57. <prop key="template_update_delay">10</prop>
  58. <prop key="defaultEncoding">UTF-8</prop>
  59. <prop key="url_escaping_charset">UTF-8</prop>
  60. <prop key="locale">zh_CN</prop>
  61. <prop key="boolean_format">true,false</prop>
  62. <prop key="time_format">HH:mm:ss</prop>
  63. <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
  64. <prop key="date_format">yyyy-MM-dd</prop>
  65. <prop key="number_format">#.##</prop>
  66. <prop key="whitespace_stripping">true</prop>
  67. <prop key="classic_compatible">true</prop>
  68. </props>
  69. </property>
  70. </bean>
  71. <!-- 配置 FreeMarker视图解析器 -->
  72. <bean id="viewResolver"
  73. class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
  74. <property name="viewClass"
  75. value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property>
  76. <property name="cache" value="false" />
  77. <property name="prefix" value="/" />
  78. <property name="suffix" value=".ftl" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
  79. <property name="contentType" value="text/html;charset=utf-8" />
  80. <property name="exposeRequestAttributes" value="true" />
  81. <property name="exposeSessionAttributes" value="true" />
  82. <property name="exposeSpringMacroHelpers" value="true" />
  83. </bean>
  84. </beans>

 

 

@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。
@Component  Component是Spring管理组件的通用形式,而@repository,@Service,@Controller是它的细化。分别表示更加具体的用例(分别对应持久化层,服务层和表现层)

 

 

B、按照Class路径扫描
XML风格的配置方式,我们会在配置文件中配置大量的bean,这样但项目足够大时,那么这个配置文件将过于庞大而不便管理。而应用@注释的配置方式,我们在类中用@Component等注释类,并让容器按照Classpath自动扫描管理它们。要实现以上功能我们需要这样定义。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.orghttps://cdn.jxasp.com:9143/image/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也将隐式包含进来,也就是说它支持@Autowired等,不需要我们如用<context:annotation-config/>再做声明了。。
自动扫描包名的配置 <context:component-scan base-package="com.shishuo"></context>


当我们用spring mvc 前端控制器的时候需要配置


<!-- spring mvc 基于注解在方法上 控制映射 配置 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>


<!-- 在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码 -->
<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" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
<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>


<!--创建数据映射器,数据映射器必须为接口 -->
<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的参数 主要有RequestParam Pathvariable(这个注解是获取url里面的参数)


5.1.1、常见应用场景
1、日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。
2、权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面;
3、性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);
4、通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个处理器都需要的即可使用拦截器实现。
5、OpenSessionInView:如Hibernate,在进入处理器打开Session,在完成后关闭Session。
…………本质也是AOP(面向切面编程),也就是说符合横切关注点的所有功能都可以放入拦截器实现。


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


当需要上传一个form里面包含 文件 或者视屏的时候 一定要记得在form表单后面添加 enctype="multipart/form-data" enctype="multipart/form-data"


 @RequestParam @RequestBody @PathVariable 等参数绑定注解详解
分类: spring 2012-09-21 16:22 11494人阅读 评论(4) 收藏 举报
目录(?)[+]
引言:
接上一篇文章,对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用;




简介:
handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)


A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解:   @PathVariable;
B、处理request header部分的注解:   @RequestHeader, @CookieValue;
C、处理request body部分的注解:@RequestParam,  @RequestBody;


D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载