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

本文主要是介绍springmvc使用和经验总结(长沙师说网络科技有限公司),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

springmvc

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

给上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());@Autowiredprotected CategoryService categoryService;@Autowiredprotected 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 {// 获得数据Category category = categoryService.getCategoryById(categoryId);// 获取当前目录下的所有课程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 blockreturn 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 {/*** 跳转到关于我们页面* * @param modelMap* @param request* @return*/@RequestMapping(value = "/about.htm", method = RequestMethod.GET)public String about(ModelMap modelMap, HttpServletRequest request) {return "/about/about";}/*** 跳转到服务协议页面* * @param modelMap* @param request* @return*/@RequestMapping(value = "/service.htm", method = RequestMethod.GET)public String service(ModelMap modelMap, HttpServletRequest request) {return "/about/service";}/*** 跳转到投诉举报页面* * @param modelMap* @param request* @return*/@RequestMapping(value = "/complain.htm", method = RequestMethod.GET)public String complain(ModelMap modelMap, HttpServletRequest request) {return "/about/complain";}/*** 跳转到版权声明页面* * @param modelMap* @param request* @return*/@RequestMapping(value = "/copyright.htm", method = RequestMethod.GET)public String copyright(ModelMap modelMap, HttpServletRequest request) {return "/about/copyright";}/*** 跳转到联系我们页面* * @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";一般当我改变一个状态的时候 我需要还是显示在当前页面 就需要再进入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
<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/beanshttp://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.xsdhttp://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 /><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /><beanclass="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配置文件中加入外部属性文件,当然也可以指定外部文件的编码 --><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" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --><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注解的类,并把这些类纳入进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.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也将隐式包含进来,也就是说它支持@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;

 

 

这篇关于springmvc使用和经验总结(长沙师说网络科技有限公司)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1013977

相关文章

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的