SpringMVC编程<一>

来源:互联网 发布:mac需要清理软件 编辑:程序博客网 时间:2024/05/21 17:24

SpringMVC编程<一>

SpringMVC(类似于Struts)

必要的包:

这里写图片描述

需要在web.xml中配置一个servlet来搭建框架:

告诉过滤器我 ‘/sp ’路径下的都需要拦截

 <servlet >    <servlet-name>hncu</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <!-- servletname - servlet.xml -->    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>hncu</servlet-name>    <url-pattern>/sp/*</url-pattern>  </servlet-mapping>

还需要写一个配置文件:
这里写图片描述
hncu.xml:
将需要处理的bean配置进来

<?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"    xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd        ">    <bean   class="cn.hncu.v1.HelloController" name="/hello"></bean></beans>  

在Struts中是Action,而在springmvc中是Controller

ModelAndView使用演示:

public class HelloController implements Controller {    @Override    public ModelAndView handleRequest(HttpServletRequest request,            HttpServletResponse response) throws Exception {        System.out.println("hello Controller");        ModelAndView mv =new  ModelAndView();        View v=new RedirectView("/jsps/hello.jsp",true);//true:带项目名        mv.setView(v);        return mv;    }}

这样也就是Action中的默认方法。
方法调用路径前面加自己定义的 “/sp”

这里写图片描述

ModelAndView还可以指定导向的页面
这里写图片描述
要在src下写配置文件:
这里写图片描述
代码如下:
一个指定类型
一个写导向的页面

hncu.(class)=org.springframework.web.servlet.view.JstlViewhncu.url=/jsps/hello2.jsp

然后在hncu-servlet.xml中配置使用视图:

 <!-- 演示重定向不需要 资源绑定视图解析的核心类 -->    <bean class="cn.hncu.v1.HelloController" name="/hello"></bean>    <!-- 演示资源绑定视图解析的核心类 -->    <bean class="cn.hncu.v2.ControllerDemo1" name="/demo1"></bean>    <bean class="cn.hncu.v2.AbcHello3" name="/abc"></bean>     <!-- 没有指定view时,默认父View作为它的view -->    <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">        <!-- 资源绑定哪个视图 -->        <property name="basenames">            <list>            <!-- 默认查询classpath -->                <value>hncu</value>            </list>        </property>        <!-- 设置默认View,没指定的都会找到这配置文件中的hncu.(class)类型 -->        <property name="defaultParentView" value="hncu"></property>    </bean>

视图可以带参数

这里写图片描述
前端页面使用EL表达式拿

测试后发现ModelAndView用2个xml会404!!