您的位置:首页 > 编程语言 > Java开发

spring mvc 框架

2016-04-12 09:22 525 查看
注:原创作者具有文章的所有权利,转载注明

1 Spring MVC简介

1.1. Spring3MVC VS Struts2

l 官方的下载网址是:http://www.springsource.org/download

l 我们用Struts2时采用的传统的配置文件的方式,并没有使用传说中的0配置.Spring3mvc可以认为已经100%零配置了

l Spring会比Struts快,在Struts中默认配置了很多缺省的拦截器,在给开发者提供便利的同时,失去了灵活性和人执行效率.

l Spring mvc是基于方法的设计, 而Sturts是基于类,每次发一次请求都会实例一个action,每个action都会被注入属性,而spring基于方法,粒度更细,可控制更强

l 设计思想上:Struts更加符合oop的编程思想,Spring是在在Servlet上扩展,使用AOP实现。

l Intercepter的实现机制:Struts有以自己的interceptor机制,Spring mvc用的是独立的AOP方式. 需要的自己配置,比较麻烦当性能较优,灵活性高

l 提供强大的约定大于配置的契约式编程支持

2 环境与入门案例

2.1使用示例

2.1.1创建项目并导入相关jar包

mvc、aop、core相关包

2.1.2创建配置文件

新建spring-mvc.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
">
</beans>

2.1.3 配置前端过滤器

org.springframework.web.servlet.DispatcherServlet,继承HttpServlet,需要在Web.xml文件中定义

<?xml
version="1.0"encoding="UTF-8"?>
<web-app
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>

2.1.4创建控制器

创建控制器FirstAction.java,实现Controller接口

// action实现Controller接口,并实现handleRequest方法(类似struts的execute方法,默认执行),与JSP内置对象偶合

public
class
UserController implements Controller {
@Override
public
ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");

System.out.println(username);
System.out.println(pwd);
//封装数据的方式,都是采用的request域
//方式一:
// request.setAttribute("userName",
username);
// return new ModelAndView("main.jsp");
//方式二:
// HashMap<String,String> map = new HashMap<String, String>();
// map.put("userName", username);
// return new ModelAndView("main.jsp",map);
//方式三:
returnnew ModelAndView("/main.jsp","userName",
username);
}
}

2.1.5修改配置文件,添加控制器信息

修改spring-mvc.xm.文件

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
">
<!--
1。配置action,实现controler接口
2。配置映射处理器,用来处理请求与action的映射,可以不用写id,
3。配置视图解析器:完成ModelAndView的解析
缺点:
1。与JSP偶合
2。只支持属性的注入,不支持封闭后对象注入
-->

<!-- 声明bean的name,因为使用了BeanNameUrlHandlerMapping,所以不是定义id,用户调用的URL将通过bean的name匹配
-->
<!—- 默认调用BeanNameUrlHandlerMapping-->
<bean
name="/first.action"
class="cn.itcast.action.FirstAction"
/>
<!-- 声明 BeanNameUrlHandlerMapping,使用名称映射。默认使用-->
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 支持servletjsp视图解析,可进行进一步处理,此步可省略,
-->
<!-- InternalResourceViewResolver支持servletjsp视图解析,没有配置时,默认使用它,此步可省略,
-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 可以加前缀或后缀 -->
<!--
<propertyname="prefix" value="/jsp/"/>
<propertyname="suffix" value=".jsp"/>

-->
</bean>

2.1.6创建结果展现页面

新建目录jsp及目录下新建first.jsp,用来展现访问结果。

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
这是/jsp/first.jsp页面.<br/>
<!-- 获取并展现控制层传递过来的值 -->
直接通过request传递的值:${requestScope.rUserName}<br/>通过Map传递的值:${requestScope.mUserName}
</body>
</html>

2.1.7编写测试(访问)页面

编写index.jsp用来访问控制器

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
<a
href="first.action?userName=zcf&pwd=admin">firstMVC</a>
</body>
</html>

2.2流程分析

3 URL处理器

3.1BeanNameUrlHandlerMapping

BeanNameUrlHandlerMapping:它将收到的HTTP请求映射到bean的名称(这些bean需要在web应用上下文中定义)

<!-- 声明bean的name,因为使用了BeanNameUrlHandlerMapping,所以不是定义id,用户调用的URL将通过bean的name匹配
-->
<bean
name="/first.action"class="cn.itcast.action.FirstAction"
/>
<!--
声明 BeanNameUrlHandlerMapping,使用名称映射
-->
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"
/>

3.2SimpleUrlHandlerMapping

SimpleUrlHandlerMapping:它将收到的HTTP请求映射到bean的ID(这些bean需要在web应用上下文中定义)

<!-- 配置URL与ACTION对象ID进行映射
,<propkey="second.action">second</prop>,其中key匹配url信息,value为action的ID

-->
<bean
id="first"
class="cn.itcast.action.FirstAction"/>

<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property
name="mappings">
<props>
<prop
key="first.action">first</prop>
</props>
</property>
</bean>

4 视图解析器

4.1 UrlBasedViewResolver

<!-- 支持servletjsp视图解析1,可进行进一步处理,此步可省略,
-->

<beanclass="org.springframework.web.servlet.view.UrlBasedViewResolver">
<!-- viewClass不同的配置,支持解析jstl的相关资源-->
<propertyname="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!--
<propertyname="prefix" value="/jsp/"/>
<propertyname="suffix" value=".jsp"/>

-->
</bean>

4.2 InternalResourceViewResolver

作为UrlBasedViewResolver的子类,它支持页面jstl处理.

<!-- 支持servletjsp视图解析,可进行进一步处理,此步可省略,
-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 可以加前缀或后缀 -->

<property
name="prefix"value="/jsp/"/>
<property
name="suffix"value=".jsp"/>

</bean>

4.3 forward:前缀

forward使用转发方式:不能省略后缀,配置不起作用

return newModelAndView("forward:/jsp/first.jsp",map);
//控制器采用注解,方法在返回字符串时,可以使用:
return"forward:/jsp/first.jsp";

4.4 Redirect:前缀

redirect重定向方式:参数传递以在域名之后的形式:
http://localhost:8080/spring-mvc/main.jsp?userName=fdas
取值方式:${param.userName}

return newModelAndView("redirect:/jsp/first.jsp",map);

//控制器采用注解,方法在返回字符串时,可以使用

return"redirect:/jsp/first.jsp";

5 控制器

5.1 controller接口

在spring mvc中控制对象要实现此接口,并且必须实现handRequest方法。此控制器在接收到DispatcherServlet分配置 的请求时,执行handRequest方法,并 返回ModelAndView实例。

public
class
FirstAction implements Controller {

@Override
public ModelAndView
handleRequest(HttpServletRequestrequest,
HttpServletResponse response) throws Exception {

...

}

5.2AbstractCommandController

可以将请求参数值自动设置到command对象中,便于后继的使用。

函数声明protectedModelAndView handle(HttpServletRequest request,

HttpServletResponseresponse, Object
command, BindException errors)

throwsException {

5.2.1添加student实体类

public
class
Student implements Serializable {
@Override
public String toString() {
return
"Student [stuId=" + stuId +
", stuName="+ stuName+
", stuPwd="
+ stuPwd +
", stuAge=" + stuAge+
"]";
}
/**
*
*/
private
staticfinallong
serialVersionUID = 1785249781500211272L;

private Integer
stuId;

private String
stuName;

private String
stuPwd;

private Integer
stuAge;

public Integer getStuId() {
return
stuId;
}
public
void
setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return
stuName;
}
public
void
setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuPwd() {
return
stuPwd;
}
public
void
setStuPwd(String stuPwd) {
this.stuPwd = stuPwd;
}
public Integer getStuAge() {
return
stuAge;
}
public
void
setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
}

5.2.2创建或修改控制器类

public
class
StudentAction extends
AbstractCommandController{

public StudentAction(){

//配置student对象可以注入
setCommandClass(Student.class);
}

@Override
protected ModelAndViewhandle(HttpServletRequest request,
HttpServletResponseresponse, Object student, BindException errors)
throws Exception {
// TODO Auto-generated methodstub
System.out.println("---接收数据---");
//方式1接收数据,只能每个属性都分开接书
StringstuName=request.getParameter("stuName");
StringstuPwd=request.getParameter("stuPwd");
System.out.println("方式1接收的数据为:"+stuName+","+stuPwd);

//方式2接收数据,实现对象属性注入
Student stu = (Student)stu;
System.out.println("方式2接收的数据为:"+stu);

System.out.println("---调用业务层,进行业务处理,略---");

//封装视图数据,有多种方式,这里列表方式一和方式二,可以任选一种:
//方式一,直接采用request对象封装
request.setAttribute("rStudent",stu);
//封装视图数据,方式二,直接采用Map封装,默认作用域是request,需要在return的时候作为参数传递。
Map<String ,Student >map=new HashMap<String, Student>();
map.put("mStudent",stu);

//默认为forward方式
return newModelAndView("/jsp/main.jsp",map);

}}

5.2.3添加或修改spring-mvc.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
">

<bean
id="student"class="cn.itcast.action.StudentAction"></bean>

<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property
name="mappings">
<props>
<prop
key="student.action">student</prop>
</props>
</property>
</bean>

</beans>

5.2.4添加跳转页面

/jsp/main.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>

<title>My JSP 'main.jsp' starting page</title>
</head>
<body>
这是/jsp/main.jsp页面.<br/>
<!-- 获取并展现控制层传递过来的值 -->
直接通过request传递的值:${requestScope.rStudent}<br/>通过Map传递的值:${requestScope.mStudent}
</body>
</html>

添加登陆测试页面

index.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
<a
href="student.action?stuName=zcf&stuPwd=admin">test student</a>
</body>
</html>

5.3MultiActionController

这种方式可以定义多个方法,方法名自定,但参数设置需要遵循:

(HttpServletRequest request,HttpServletResponse response, [,HttpSession session] [,MyObject]);

5.3.1准备工作

除action类以外,其它继续使用上一节代码

5.3.2添加StudentMultiAction.java类

public
class
StudentMultiAction extends MultiActionController {
public ModelAndView add(HttpServletRequestrequest,HttpServletResponse response,Student student){
System.out.println("add.student:"+student);
student.setStuName("rename");
return
new
ModelAndView("jsp/main","student",student);
}

//定义方法时,参数规则:(HttpServletRequestrequest, HttpServletResponse response, [,HttpSession session] [,MyObject]);
public ModelAndView update(HttpServletRequest request,HttpServletResponseresponse,Student student){
System.out.println("update.student:"+student);
student.setStuName("rename");
return
new
ModelAndView("jsp/main","student",student);
}

//定义方法时,参数规则:(HttpServletRequestrequest, HttpServletResponse response, [,HttpSession session] [,MyObject]);
public ModelAndView list(HttpServletRequest request,HttpServletResponseresponse,Student student){
System.out.println("list.student:"+student);
student.setStuName("updateName");
return
new
ModelAndView("jsp/main");
}
}

5.3.3修改spring-mvc.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd
">
<!-- 配置控制器,并指定通过methodNameResolver方法名调用相关方法处理相关逻辑-->
<bean id="studentMultiAction"class="cn.itcast.action.StudentMultiAction">
<propertyname="methodNameResolver" ref="parameterMethodNameResolver"></property>
</bean>
<!-- 定义通过方法名调用控制器相关方法的规则 -->
<bean id="parameterMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<!-- 在url中使用do=方法名方式识别相关方法,例如:studentMulti.action?do=add,将调用add方法;这里的do不是固定的,可以改为其它
-->
<property name="paramName"value="do" />
<!-- 如果没有指定方法名时,默认调用控制器的list方法 -->
<property name="defaultMethodName"value="list" />
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/studentMulti.action">studentMultiAction</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property
name="prefix"value="/WEB-INF/"
/>
<property
name="suffix"value=".jsp"
/>
</bean>
</beans>

5.3.4测试页面

index.jsp关键代码

<body>
<form
action="studentMulti.action?do=add"method="post">
<input
type="text"name="stuName"><br>
<input
type="password"
name="stuPwd"><br>
<input
type="submit"
value="student_add">
</form>

<a
href="studentMulti.action?do=update&stuPwd=testpwd&stuName=testName">调用修改方法</a>
<a
href="studentMulti.action?&stuPwd=testpwd&stuName=testName">调用默认方法</a>
</body>

5.3.5结果显示页面

/WEB-INF/jsp/main.jsp关键代码

<body>
this is WEB-INF/JSP main jsp<br>
studentName:${requestScope.student.stuName}<br>

</body>

6 基于注解的MVC实现

这种方式设计的参数可以对request,response,session域对象作为函数的参数的形式注入,servletContext用注解@@Resource的形式注入

6.1示例1

继续使用上一章节的代码(注意新建项目记得重新配置web.xml文件)

6.1.1修改spring-mvc.xml文件

添加DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter等相关信息。其中DefaultAnnotationHandlerMapping:支持通过url找到相关的action;

AnnotationMethodHandlerAdapter:支持通过url匹配action定义方法 ;

base-package:定义扫描的范围,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component@Controller@Service等这些注解的类,则把这些类注册为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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd ">
<!--
DefaultAnnotationHandlerMapping:支持通过url找到相关的action
AnnotationMethodHandlerAdapter:支持通过url匹配action定义方法
base-package:定义扫描的范围,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component@Controller@Service等这些注解的类,则把这些类注册为bean
-->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<context:component-scan base-package="*"></context:component-scan>
</beans>

6.1.2添加或修改控制类

加入@Controller,@RequestMapping注解信息
注解括号里的字符串不用加“/”也可以运行
注解的方式自动会将参数封装到request域中,若需要其他信息建议使用ModelMap 例如select方法

@Controller //用来声明控制器
@RequestMapping("/student")
public
class
StudentAction {
public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}
//访问可用student/save.action,save后边的action是根据web.xml配置来的

//如果要添加其它的数据到最后跳转过去的页面,可以在方法中添加ModelMap的参数,例如 : public String save(Student
student,ModelMap map){
//...,通过map再存放其它的数据
@RequestMapping(value="/save")
public ModelAndView save(Student student){
System.out.println("save方法注入的student对象:"+student);
System.out.println("---调用业务逻辑进行业务处理---");

//修改学生名字,跳转到下一页面时看能否显示修改后的名字
student.setStuName("rename");

//直接使用字符串,返回视图,进行结果展现等
return
new
ModelAndView("forward:/jsp/main.jsp");
}

//同一个action中可以定义多个方法,方法的返回类型也可以用String
@RequestMapping(value="/update")
public String update(Student student,ModelMap paramMap){
System.out.println("update方法已注入student对象:"+student);
System.out.println("---调用业务逻辑进行业务处理---");

paramMap.put("other","testOtherValue");
//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

6.1.3添加或修改跳转页面

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>

<title>My JSP 'main.jsp' starting page</title>
</head>
<body>
这是/jsp/main.jsp页面.<br/>
<!-- 获取并展现控制层传递过来的值 -->
默认通过request传递的值:${requestScope.student}<br/>
</body>
</html>

6.1.4添加或修改测试页面

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>
<a
href="student/save.action?stuName=zcf&stuPwd=admin">调用save方法</a>

<a
href="student/update.action?stuName=zcf&stuPwd=admin">调用update方法</a>

</body>
</html>

6.2示例2(基于annotation-driven的注解)

基于上面的示例,在spring3中可以进一步简化配置,取代上面的注解方式.
步骤如下
1.使用上面的action类,仍然给类及方法添加@Controller(类)、@RequestMapping(类及方法)注解
2.本文件顶部添加spring
mvc 命名空间的信息(可以参考org.springframework.web.servlet.config包)
3.添加下面注解驱动<mvc:annotation-driven>,取代了上面的DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter,并启动了json的注解
-->
修改内容如下:

6.2.1修改配置文件

修改spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
">

<!--
<beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<context:component-scanbase-package="*"></context:component-scan>
-->

<!--mvc:annotation-driven,取代了上面的DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
两个Bean的配置 -->
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="*"/>

</beans>

6.3 @SessionAttributes与model.addAttribute使用

Spring 2.0 定义了一个org.springframework.ui.ModelMap 类,它作为通用的模型数据承载对象,传递数据供视图所用。我们可以在请求处理方法中声明一个 ModelMap 类型的入参,Spring 会将本次请求模型对象引用通过该入参传递进来,这样就可以在请求处理方法内部访问模型对象了在默认情况下,ModelMap 中的属性作用域是 request 级别是,也就是说,当本次请求结束后,ModelMap 中的属性将销毁,但实际上有时候需要把ModelMap值存放于session中或有时候也可以从Session中获取对象的值注入到ModelMap中。

继续使用上一节代码

6.3.1 modelMap属性注入到Session

如果希望在多个请求中共享 ModelMap 中的属性,必须将其属性转存到 session 中,这样 ModelMap 的属性才可以被跨请求访问;

可以在定义类时使用@SessionAttributes("属性名")或@SessionAttributes({“attr1”,”attr2”})等方式将尝试从modelMap中寻找相同属性名相应的value.

修改StudentAction.java类,

@Controller
@RequestMapping("/student")
//下边如有多个属性可以用@SessionAttributes({“attr1”,”attr2”})。
@SessionAttributes("user")
public
class
StudentAction {
public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@RequestMapping(value="/save")
public String save(Student student,ModelMap map){
System.out.println("---调用业务逻辑进行业务处理---");

Student s2=new Student();
s2.setStuAge(11);
s2.setStuId(11111);
map.addAttribute("user",s2);//属性名必须与session一致
//map.addAttribute("stu",student);

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}

//同一个action中可以定义多个方法
@RequestMapping(value="/update")
public String update(Student student){
System.out.println("update方法已注入student对象:"+student);
System.out.println("---调用业务逻辑进行业务处理---");

paramMap.put("student",student);
//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

修改/jsp/main.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>

<title>My JSP 'main.jsp' starting page</title>
</head>
<body>
这是/jsp/main.jsp页面.<br/>
<!-- 获取并展现控制层传递过来的值 -->
默认直接通过request传递的值:${requestScope.student}<br/>
<!-- 默认直接通过session传递的值stu:${sessionScope.stu}<br/>
-->
默认直接通过session传递user值:${sessionScope.user}<br/>
<!--下边的代码给下一示例使用:调用update方法测试把session的值注入到map中,此时session已经有user相关信息-->
<a href="../student/update.action">session的值注入到map中</a>
</body>
</html>

6.3.2 session属性注入到ModelMap

在参数中使用@ModelAttribute("user"),可以获取@SessionAttributes("user")值

继续使用上节代码

修改StudentAction.java类,

定义类时继续使用@SessionAttributes("user"),并修改update方法,在参数中添加@ModelAttribute("user"):参数中的student的对象将由session中获取。

@Controller
@RequestMapping("/student")
//下边如有多个属性可以用 @SessionAttributes({“attr1”,”attr2”})。
@SessionAttributes("user")
public
class
StudentAction {
public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@RequestMapping(value="/save")
public String save(Student student,ModelMap map){
System.out.println("---调用业务逻辑进行业务处理---");

Student s2=new Student();
s2.setStuAge(11);
s2.setStuId(11111);
s2.setStuName("testname");
map.addAttribute("user", s2);
//map.addAttribute("stu",student);

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}

//同一个action中可以定义多个方法
@RequestMapping(value="/update")
public String update(@ModelAttribute("user")Student student){
System.out.println("update方法已注入student对象:"+student);
System.out.println("---调用业务逻辑进行业务处理---");

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

课堂练习:

1。完成spring mvc基于配置方式开发环境搭建,并完成测试功能

2。完成spring mvc注解方式环境搭建,并完成以下场景:

add.jsp:提供学生登陆信息输入,并可以提交登陆

StudentAction:完成信息输出(控制台),并校验信息(校验条件自己设定),符合条件,把相关信息保存到session,并进入主页(main.jsp),显示登陆人员的信息;不符合登陆条件,则返回登陆页面。

7综合示例(springmvc文件上传)

7.1 multipartResolver使用

spring-mvc.xml文件添加如下内容:

<!--文件上传使用,配置multipartResolver,id名为约定好的
-->
<bean
id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb
-->
<property
name="maxUploadSize"value="1024000"
/>
</bean>

7.2中文乱码处理

web.xml文件添加如下内容:

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

如果上边的方式设置后,仍然有乱码,请尝试修改tomcat安装目录下的

apache-tomcat安装目录\conf\server.xml文件,修改Connector元素内容,添加URIEncoding="UTF-8" ,修改后内容 如下:

<Connectorport="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>

7.3 properties文件信息注入

PropertiesFactoryBean:用来注入properties类型的配置文件信息

<!--PropertiesFactoryBean对properties文件可用,可以用来注入properties配置文件的信息
-->
<bean
id="uploadProperties"class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property
name="location"value="classpath:xxxxx.properties"></property>
</bean>

7.4文件上传示例

7.4.1导入包

继续使用上一章节代码,并导入文件上传需要的jar包:commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar

7.4.2修改student实体类,添加文件类型属性

public
class
Student implements Serializable {

private
staticfinallong
serialVersionUID = -5304386891883937131L;

private Integer
stuId;

private String
stuName;

private String
stuPwd;

private Integer
stuAge;

private MultipartFile[] files;

public MultipartFile[] getFiles() {
return files;
}

public voidsetFiles(MultipartFile[] files) {
this.files = files;
}

public Integer getStuId() {
return
stuId;
}

public
void
setStuId(Integer stuId) {
this.stuId = stuId;
}

public
StringgetStuName() {
returnstuName;
}

public
void
setStuName(String stuName) {
this.stuName = stuName;
}

public String getStuPwd() {
return
stuPwd;
}

public
void
setStuPwd(String stuPwd) {
this.stuPwd = stuPwd;
}

public Integer getStuAge() {
return
stuAge;
}

public
void
setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}

@Override
public String toString() {
return
"Student [stuId=" + stuId +
", stuName="+ stuName+
", stuPwd="
+ stuPwd +
",stuAge=" + stuAge +
"]";
}
}

7.4.3编写上传页面

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>

<form
action="student/save.action"method="post"
enctype="multipart/form-data">
姓名:<input
type="text"name="stuName"><br/>
密码<input
type="password"name="stuPwd"><br>
请选择文件:<br/><input
type="file"name="files"><br/>
<input
type="file"
name="files"><br/>
<input
type="submit"
value="文件上传测试">

</form>

</body>
</html>

7.4.4编写控制器

StudentAction.java

@Controller
@RequestMapping("/student")
public
class
StudentAction {

public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@RequestMapping("/save")
public String save(Student student) {
System.out.println("save方法已注入student对象:"+student);
MultipartFile[] files=student.getFiles();
for(MultipartFile file:files){
if(file.isEmpty()){
System.out.println("文件为空");
}else{
System.out.println("文件不为空!");
System.out.println("格式:" + file.getContentType());
System.out.println("原名:" + file.getOriginalFilename());
System.out.println("大小:" + file.getSize());
System.out.println("表单控件的名称" + file.getName());
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),newFile("e:/testupload/"+file.getOriginalFilename()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("---调用业务逻辑进行业务处理---");

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

7.4.5修改配置文件

添加文件处理器CommonsMultipartResolver配置

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
">

<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan
base-package="*"/>

<!--文件上传使用,配置multipartResolver,id名称为约定好的
-->
<bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置文件(每次上传的所有文件总大小)大小,单位为b,
1024000表示1000kb -->
<property name="maxUploadSize"value="1024000" />

</bean>

</beans>

7.4.6编写处理完后跳转的页面

main.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>main.jsp</title>

</head>

<body>
/jsp/main.jsp页面
student: ${requestScope.student}
</body>
</html>

7.4.7文件存放于tomcat目录下处理方式

l 在项目目录下新建upload文件夹

l 修改StudentAction.java。

@Controller
@RequestMapping("/student")
public
class
StudentAction {

public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@Resource
ServletContext application;

@RequestMapping("/save")
public String save(Student student) {
System.out.println("save方法已注入student对象:"+student);
MultipartFile[] files=student.getFiles();
System.out.println("真实路径:"+application.getRealPath("/"));
for(MultipartFile file:files){
if(file.isEmpty()){
System.out.println("文件为空");
}else{
System.out.println("文件不为空!");
System.out.println("格式:" + file.getContentType());
System.out.println("原名:" + file.getOriginalFilename());
System.out.println("大小:" + file.getSize());
System.out.println("表单控件的名称" + file.getName());

try {
FileUtils.copyInputStreamToFile(file.getInputStream(),newFile(application.getRealPath("/")+"upload/"+file.getOriginalFilename()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("---调用业务逻辑进行业务处理---");

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

其它代码同上一章节,可以在application.getRealPath("/")+"upload/"目录下查看到文件,例如 :

E:\Users\chufeng\Workspaces\MyEclipse10\itcast\.metadata\.me_tcat\webapps\fileuploadspring\upload查看到上传的文件。

7.5 文件上传优化

7.5.1编写文件上传工具类

FileUploadUtil.java

@Component(value="fileUploadUtils")
//普通的bean注入
public
class
FileUploadUtils {
/*
* 注入字符串,#{}为spel语言,其中uploadProperties,是xml配置文件中注入properties文件的bean
id,
* path为properties文件的其中一个key
,也可以通过下边的set方法注入
*/

@Value("#{uploadProperties.path}")

private String
path;
//privateString path="e:/testupload";

//path也可以通过set方法注入
// @Value("#{uploadProperties.path}")
// public void setPath(String path) {
// this.path = path;
// }

private String getExtName(MultipartFile file){
return FilenameUtils.getExtension(file.getOriginalFilename());
}

private String createNewName(MultipartFile file){
return UUID.randomUUID().toString()+"."+getExtName(file);
}

public String uploadFile(MultipartFile file){
try {
String newName=createNewName(file);
FileUtils.copyInputStreamToFile(file.getInputStream(),newFile(path,newName));
return newName;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw
new
RuntimeException(e);
}
}
}

7.5.2修改StudentAction.java

主要修改save方法,使用自已的文件上传工具类进行文件上传。

@Controller
@RequestMapping(value="/student")
public
class
StudentAction {

@Resource
private ServletContext
application;

@Resource
private FileUploadUtils fileUploadUtils;

public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@RequestMapping(value="/save")
public String save(Student student,Map<String, Student> paramMap) {
System.out.println("save方法已注入student对象:"+student);
MultipartFile[] files=student.getFiles();
for(MultipartFile file:files){
if(file.isEmpty()){
System.out.println("文件为空");
}else{
System.out.println("文件不为空!");

fileUploadUtils.uploadFile(file);
}
}
System.out.println("---调用业务逻辑进行业务处理---");

paramMap.put("student",student);

//直接使用字符串,返回视图,进行结果展现等
return
"forward:/jsp/main.jsp";
}
}

7.5.3添加upload.properties文件

配置文件上传后的存放目录

path=e\:\\testdir\\upload\\

7.5.4修改spring-mvc.xml配置文件

注入配置文件的信息

<!--PropertiesFactoryBean对properties文件可用,可以用来注入properties配置文件的信息
-->
<bean
id="uploadProperties"class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property
name="location"value="classpath:upload.properties"></property>
</bean>

8 综合示例(登陆)

在综合示例1上继续。

8.1拦截器使用

8.1.1编写拦截器类

LoginInterceptor.java,需要实现HandlerInterceptor接口

public
class
LoginInterceptor
implements
HandlerInterceptor {

@Override
public
void
afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2,Exception arg3)
throws Exception {
System.out.println("---访问请求资源后不管有没有异常都一定执行此方法---");
}

@Override
public
void
postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("---访问请求资源后,如果没有异常,将执行此方法---");

}

@Override
//Object对象封装了请求资源的信息(例如方法声明等)
public
boolean
preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("---访问请求资源前执行,如果此方法返回false,将不能访问请求资源---");
return
true
;
}
}

8.1.2配置文件中添加拦截器

<!-- 配置spring
mvc拦截器 -->
<mvc:interceptors>
<!-- 默认拦截DispatcherServlet指定的后缀(这里是.action)
-->
<bean
class="cn.itcast.interceptor.LoginInterceptor"/>
</mvc:interceptors>

8.3登陆示例

8.3.1编写及配置拦截器

添加拦截器类及拦截器配置信息,如上面。

8.3.2修改拦截器类preHandle方法

@Override
public
boolean
preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
// TODO Auto-generated methodstub
System.out.println("---访问请求资源前执行,如果此方法返回false,将不能访问请求资源---");
if(arg0.getSession().getAttribute("user")==null){
arg1.sendRedirect(arg0.getContextPath()+"/login.jsp");
return
false
;
}
return
true
;
}

8.3.3编写登陆页面

login.jsp,本页面已模仿了登陆

<%@page
import="cn.itcast.entity.Student"%>
<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>

<body>

<%
session.setAttribute("user",
new Student(1001,"zcf","admin",20));
%>
<!-- 这里正常应该跳到action再到页面 ,为了演示,这里简略-->

<a
href="index.jsp">已登陆,返回首页</a>

</body>
</html>

9 json交互

使用上面的源码,暂时去掉拦截器的登陆权限处理

9.1导入json包及jquery的js文件

9.2修改action文件

@Controller
@RequestMapping(value="/student")
public
class
StudentAction {

public StudentAction(){
System.out.println("---StudentAction构造方法被调用---");
}

@RequestMapping("/doAjax")
@ResponseBody //如果返回json格式,需要这个注解
public Object doAjax(Student student){

System.out.println("---doAjax.student:"+student);
student.setStuName("1001name");
return student;
}
}

9.3修改访问页面

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script
type="text/javascript"src="${pageContext.request.contextPath}/jquery-1.3.js"></script>
<script
type="text/javascript">
$(
function(){
$("#bt1").click(
function(){
$.post(
"student/doAjax.action",
{stuId:1001,stuName:"name1001",stuPwd:"pwd1001",stuAge:20},
function(json){alert(json.stuName+"||"+json.stuPwd);},
"json"
);
}
);
}
);

</script>

</head>

<body>
<button
id="bt1"
>testajax</button>

</body>
</html>

10 ssi整合示例

10.1 ssi整合

10.1.1创建项目

新建项目后规划好各层的包。

10.1.2导入包

10.1.3整合spring与mybatis

调整spring与mybatis配置文件

10.1.4创建、编写配置文件:

myBatis-config.xml文件

<?xml
version="1.0"encoding="UTF-8"
?>
<!DOCTYPE
configurationPUBLIC
"-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 通过别名简化对类的使用
<typeAliases>
<typeAlias type="cn.itcast.entity.Dept"alias="Dept" />
</typeAliases>

<mappers>
<mapper resource="cn/itcast/entity/DeptMapper.xml"/>
</mappers>
-->
</configuration>

applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

<!-- 配置数据源,记得去掉myBatis-config.xml的数据源相关配置 -->
<bean
id="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property
name="driverClass"value="com.mysql.jdbc.Driver"
/>
<property
name="jdbcUrl"value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8"/>
<property
name="user"value="root"
/>
<property
name="password"value="root"
/>
</bean>
<!-- 配置session工厂 -->
<bean
id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<property
name="dataSource"ref="dataSource"
/>
<property
name="configLocation"value="classpath:myBatis-config.xml"
/>
</bean>

<!-- 配置事务管理器,管理数据源事务处理-->
<bean
id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property
name="dataSource"ref="dataSource"
/>
</bean>
<!-- 配置事务通知 -->
<tx:advice
id="advice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 -->
<tx:method name="insert*"propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="update*"propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="delete*"propagation="REQUIRED" rollback-for="Exception"/>
<tx:method
name="*"propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面织入的范围,后边要把事务边界定在service层
-->
<aop:config>
<aop:advisor
advice-ref="advice"pointcut="execution(* cn.itcast.scm.dao.impl.*.*(..))"/>
</aop:config>
<!-- 配置SessionTemplate,已封装了繁琐的数据操作-->
<bean
id="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg
name="sqlSessionFactory"ref="sqlSessionFactory"/>

</bean>

<context:component-scanbase-package="*"/>

</beans>

10.1.5编写实体及sql映射文件

l 如没有建库表,先建库表,可参考如下sql:

drop databaseif
exists mybatis;
create databasemybatisCHARACTERSET UTF8;
use mybatis;

create table dept(
dept_id int
primarykey auto_increment,
dept_name varchar(50),
dept_address varchar(50)
);

insert intodept(dept_name,dept_address)
values('研发部一部','广州');
insert intodept(dept_name,dept_address)
values('研发部二部','广州');
insert intodept(dept_name,dept_address)
values('研发部三部','深圳');
select * from dept;

l 编写实体类

public
class
Dept implements Serializable {
private Integer
deptId;
private String
deptName;
private String
deptAddress;
public Integer getDeptId() {
return
deptId;
}
public
void
setDeptId(IntegerdeptId) {
this.deptId = deptId;
}
public String getDeptName() {
return
deptName;
}
public
void
setDeptName(String deptName) {
this.deptName = deptName;
}
public String getDeptAddress() {
return
deptAddress;
}
public
void
setDeptAddress(String deptAddress) {
this.deptAddress = deptAddress;
}
@Override
public String toString() {
return
"Dept [deptId=" + deptId +
", deptName="+ deptName
+ ", deptAddress=" +
deptAddress + "]";
}

}

l sql映射文件,并将相关信息映射到mybatis-config.xml文件。

<?xml
version="1.0"encoding="UTF-8"
?>
<!DOCTYPE
mapperPUBLIC
"-//mybatis.org//DTDMapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper
namespace="cn.itcast.entity.DeptMapper">
<resultMap
type="Dept"id="deptResultMap">
<id
property="deptId"column="dept_id"
/>
<result
property="deptName"column="dept_name"
/>
<result
property="deptAddress"column="dept_address"
/>
</resultMap>
<!-- id和命名空间用来定位SQL语句,parameterType表示参数的类型,resultMap返回类型
-->
<select
id="selectDept"parameterType="Integer"
resultMap="deptResultMap">
<!--参数的写法#{deptID} -->
select * from dept wheredept_id=#{deptID}
</select>

<insert
id="insertDept"parameterType="Dept">
insert into dept(dept_name,dept_address)values(#{deptName},#{deptAddress});
</insert>

</mapper>

myBatis-config.xml文件修改后为如下内容

<?xml
version="1.0"encoding="UTF-8"
?>
<!DOCTYPE
configurationPUBLIC
"-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 通过别名简化对类的使用 -->
<typeAliases>
<typeAlias type="cn.itcast.entity.Dept"alias="Dept" />
</typeAliases>
<mappers>
<mapper resource="cn/itcast/entity/DeptMapper.xml"/>
</mappers>
</configuration>

10.1.6编写Dao接口及实现

DeptDaoImpl.java

@Repository("deptDao")
public
class
DeptDaoImpl{

@Resource
private SqlSessionTemplate
sqlSessionTemplate;

/**
* 根据部门编号查询部门信息
* @param deptId
部门编号
* @return部门信息
*/
public Dept selectDept(Integer deptId){

Dept dept= sqlSessionTemplate.selectOne("cn.itcast.entity.DeptMapper.selectDept", deptId);

return dept;
}
/**
* 添加部门信息
* @param dept
部门信息
* @return添加成功的记录数
*/
public
int
insertDept(Dept dept){
System.out.println("------dao.dept:"+dept);
return
sqlSessionTemplate.insert("cn.itcast.entity.DeptMapper.insertDept", dept);

}
}

10.1.7测试spring与mybatis整合

public
class
TestDeptDao {

//@Resource //这里没法使用,后继版本有其它方式可以注入
static
private
DeptDaoImpl deptDao;
@BeforeClass
public
staticvoid
setUpBeforeClass()
throws
Exception {
ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
deptDao=(DeptDaoImpl) context.getBean("deptDao");
}

@AfterClass
public
staticvoid
tearDownAfterClass()
throws Exception {
}

@Test
public
void
testSelectDept() {
System.out.println(deptDao.selectDept(1));
}

@Test
public
void
testInsertDept() {
Dept dept=new Dept();
//dept.setDeptId(117);
dept.setDeptName("name117");
dept.setDeptAddress("address117");
System.out.println("受影响行数:"+deptDao.insertDept(dept));
}
}

10.1.8整合springmvc

修改web.xml文件,加入springmvc相关信息,编写 控制器类及相关jsp 文件

l spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">

<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan
base-package="*"/>
</beans>

l web.xml文件配置

<?xml
version="1.0"encoding="UTF-8"?>
<web-app
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

l 编写控制器类

@Controller
@RequestMapping(value="/dept")
public
class
DeptAction {
@Resource
private DeptDaoImpl
deptDao;

@RequestMapping(value="/insert")
public String insert(Dept dept){
System.out.println("---action.dept:"+dept);
deptDao.insertDept(dept);
return
"forward:/jsp/main.jsp";
}
}

l 缩写跳转页面

/jsp/main.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
</head>
<body>
this is main jsp
</body>
</html>

10.1.9测试ssi整合

缩写测试页面

index.jsp

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<html>
<head>
</head>
<body>
<form
action="dept/insert.action"method="post">
名称:<input
type="text"
name="deptName"><br>

地址:<input
type="text"
name="deptAddress"><br>
<input
type="submit"value="ok">
</form>
</body>
</html>

10.2优化

10.2.1中文乱码

中文乱码处理,在web.xml中配置过滤器(参考前面)

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

10.2.2添加业务层

1).添加业务层相关包、接口及实现

接口包:cn.itcast.service

实现类包:cn.itcast.service.impl

编写接口与实现类(实现类用@Service进行注解,dao接口结合下边的配置,通过@Autowired方式注入代理实例),略。

10.2.3添加dao层接口



10.2.4修改applicationContext.xml与spring-mvc.xml文件

添加如下内容:

<!-- 把事务边界定在service层 -->
<aop:config>
<aop:advisor
advice-ref="advice"pointcut="execution(* cn.itcast.scm.service.impl.*.*(..))"/>
</aop:config>
<!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。
-->
<context:component-scan
base-package="cn.itcast">
<context:exclude-filter
type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- 配置转换器,对于在basePackage设置的包(包括子包)下的接口类,如果在Mapper.xml文件中定义过,
将被转换成spring的BEAN,在调用的地方通过@Autowired方式将可以注入接口实例
这种代理扫描会叫接口转换成一个spring的代理bean,但名字未知,一般后面再实例化接口的类上若写注解(@component)将bean放入容器中会报错:bean冲突,-->
<bean
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property
name="sqlSessionFactory"ref="sqlSessionFactory"/>
<property
name="basePackage"value="cn.itcast.scm.dao"/>
</bean>

注:包下或者子孙包下的所有接口类的命名空间应与接口的全类名一致;

Sql语句的id应该与方法名一致;

spring-mvc.xml

<!-- 扫描所有的controller
但是不扫描service -->
<context:component-scan
base-package="cn.itcast">
<context:include-filter
type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter
type="annotation"
expression="org.springframework.stereotype.Service"/>
</context:component-scan>

10.2.4修改sql映射文件中命名空间

10.2.5修改各层的调用

控制器类通过业务层接口调用业务层,业务层再通过dao接口(可删除dao实现类,及测试类)获取代理对象执行相关SQL,进行数据的操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring mvc