<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里面配置下面代码, <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" /> <!-- 在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>我们试图模板用的是freemarker,所以后缀名是以.ftl结束,如果是用的jsp,那这个配置文件里面的
<property name="suffix" value=".ftl" />valeu改为.jsp然后我再给出类给大家看见
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 { // 获得数据 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 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 { /** * 跳转到关于我们页面 * * @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"; } }
下面是使用springmvc的经验:
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 mvc请所有的请求都提交给在web.xml中配置的DispatcherServlet,由它查询一个或多个HandlerMapping,找到处理请求的Controller,并且将请求提交给这个类。
Controller进行业务逻辑处理后,会返回一个ModelAndView
Dispathcher查询一个或多个 ViewResolver视图解析器,找到ModelAndView对象指定的视图对象 ,视图对象负责渲染返回给客户端。
<filter> <filter-name>ActionContextCleanUp</filter-name> <filter-class>com.opensymphony.webwork.dispatcher.ActionContextCleanUp</filter-class> </filter> <!-- 若有其他相关的filter 需要加在这个地方--> <!--配置struts2过滤器--> <filter> <filter-name>webwork</filter-name> <filter-class>com.opensymphony.webwork.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>ActionContextCleanUp</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>webwork</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>编写action请求处理类.可以继承struts2的 ActionSupport也可以不继承,(不过一般为了方便获取 request,response以及session 最好自己编写一个类继承ActionSupport,并在类中获取request等,让请求处理类继承这个类),然后根据页面和struts.xml配置决定请求的处理方法.
<s:form action="login.action" method="post"> <s:textfield key="username" name="user.username"/> <s:password key="password" name="user.password" /> <s:submit key="submit" /> </s:form>strust.xml中
<action name="login" class="cc.dynasoft.action.LoginAction"> <result name="success">/welcome.jspresult> <result name="error">/login.jspresult> </action>这时请求会交由LoginAction的默认方法execute来处理,在LoginAaction中有user对象及其set方法,页面属性会自动注入到此user对象中,返回字符串[success],匹配struts.xml此action内的result值确定调转的展示页面
例2:
-----页面
<s:form action="submit.action"> <s:textfield name="msg"label="输入内容"/> <s:submit name="save"value="保存"align="left"method="save"/> <s:submit name="print"value="打印"align="left"method="print"/> </s:form>
struts.xml
-----struts.xml: <action name="submit" class="action.MoreSubmitAction"> <result name="save">/result.jsp</result> <result name="print">/result.jsp</result> </action>由页面submit的method方法来指定对应的处理方法,方法返回字符串.继而确定调转展示页面
<form method="post" action="Kinder_add.php" <input type="text" name="kinder.name"> <input type="text"name="kinder.zip"> <input type="submit" value="提交"> </form>
<action name="*_*" method="{2}" class="ostar.lg.action.{1}Action"> <result name="success">/default.jsp</result> </action>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<action path="/stock" parameter="method" name="stocklogForm" type="com.xuanmu.struts.action.stock.StockAction" scope="request"> <forward name="LIST" path="/productsList.jsp" /> </action>当截取到请求为stock时就由StockAaction处理.[继承DispactureAction的话分发到parameter值对应的方法中去], 该方法返回由字符串封装[LIST]的ActionForward对象,然后再struts-config.xml中的匹配 ,决定返回呈现的页面