SSM框架整合

配置文件

web.xml配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- 配置Spring字符编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加载的配置文件
spring-dao.xml,spring-service.xml,spring-web.xml
Mybatis - > spring -> springmvc
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>

spring配置

springMVC配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解模式 -->
<mvc:annotation-driven validator="validator"/>
<!-- <mvc:annotation-driven /> -->
<!-- 2.静态资源默认servlet配置
(1)加入对静态资源的处理:js,gif,png
(2)允许使用"/"做整体映射
-->
<mvc:default-servlet-handler/>
<!--2.获取使用下面的:配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 -->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/fonts/**" location="/fonts/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<!-- 3.配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

spring-dao配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!-- 加载数据库资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30" />
<property name="minPoolSize" value="10" />
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false" />
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000" />
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2" />
</bean>

<!-- 配置sqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 扫描entity包 使用别名 -->
<property name="typeAliasesPackage" value="com.gao.entity" />
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>

<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.gao.dao" />
</bean>
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="com.gao.service"/>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

mybatis配置

1
2
3
4
5
6
7
8
9
10
11
<!-- 配置全局属性 -->
<settings>
<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true" />

<!-- 使用列别名替换列名 默认:true -->
<setting name="useColumnLabel" value="true" />

<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>

mybatis配置

建议使用注解方式:

1
2
3
4
5
@Mapper
public interface UserMapper {
@Select("select * from `user` where username=#{name} and status=0")
public User query(String name);
}

代码

编写Controller代码

1
2
3
4
5
6
7
8
9
@Controller
@RequestMapping("/mvc")
public class mvcController {

@RequestMapping("/hello")
public String hello(){
return "hello";
}
}

常用注解

@Controller
负责注册一个bean 到spring 上下文中
@RequestMapping
注解为控制器指定可以处理哪些 URL 请求
@ResponseBody
返回json
@ModelAttribute
在方法定义上使用@ModelAttribute注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法
在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中
@RequestParam 
在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法
@RequestParam(value="name",defaultValue="Guest")//修饰在方法参数里面
@PathVariable
绑定 URL 占位符到入参

1
2
3
4
5
6
@RequestMapping("/path/{language}/{id}")
public String documentView(Model model,
@PathVariable(value = "language") String language,
@PathVariable(value = "id") Long id
) {
}

@ExceptionHandler
注解到方法上,出现异常时会执行该方法

@ControllerAdvice
使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常
@Configuration
把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
@Component
组件
@EnableScheduling
启动定时任务

传递参数

1
2
3
4
5
6
7
8
9
@RequestMapping("/show")	
public String showPerson(Map<String,Object> map){
Person p =new Person();
map.put("p", p);
p.setAge(20);
p.setName("jayjay");
return "show";
}
//前台可在Request域中取到"p"
  1. Model model这个放在方法里面的参数,然后就可以model.addAttibute(“key”,value);页面可以获取到
    Model model, Map model2, ModelMap model3都是同一个对象

  2. request传统方式

    1
    2
    3
    public String view(HttpServletRequest req,HttpSession session){

    }

使用redirect方式处理请求

1
2
3
4
5
//redirect 
@RequestMapping("/redirect")
public String redirect(){
return "redirect:hello";
}

异常的处理

1
2
3
4
5
6
7
8
@ExceptionHandler(value = UnauthorizedException.class) // 处理访问方法时权限不足问题
public String handle(Exception e) {
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
System.out.println("in testExceptionHandler");
return mv;
}
//ModelAndView 跳转加设置参数

自定义拦截器

创建一个MyInterceptor类,并实现HandlerInterceptor接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
建一个MyInterceptor类,并实现HandlerInterceptor接口
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, //先執行,
Object arg2) throws Exception {
System.out.println("preHandle");
return true;
}

  1. 编写拦截器类实现接口HandlerInterceptor,重写方法afterCompletion,postHandler,
    preHandler(执行时三种方法的执行步骤为,controller方法前执行preHandler,执行controller方法后执行postHandler、afterCompletion)
    
  2. 将拦截器注册到springMVC框架中(springmvc配置文件):
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <mvc:interceptors>
    <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.gao.interceptor.LoginInterceptor"></bean>
    </mvc:interceptor>
    <mvc:interceptor>
    <mvc:mapping path="/news/del"/>
    <bean class="com.gao.interceptor.LimitInterceptor"></bean>
    </mvc:interceptor>
    </mvc:interceptors>

数据效验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 配置校验器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 校验器,使用hibernate校验器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下面的ValidationMessages.properties文件 -->
<property name="validationMessageSource" ref="messageSource"/>
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件名 -->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessage</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8"/>
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120"/>
</bean>
<!--注入-->
<mvc:annotation-driven validator="validator"/>

实体类

1
2
3
4
   @Size(min=3,max=10,message="{errors.title}")
private String tTitle;
@NotNull(message="{errors.content}")
private String tContent;

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@Validated News news,BindingResult br,Model model){
//@validated 是@valid一次封装
if(br.hasErrors()){
List<ObjectError> errors = br.getAllErrors();
model.addAttribute("errors", errors);
//errors.get(0).getDefaultMessage();
FieldError name = br.getFieldError("tTitle");
System.out.println(name.getDefaultMessage());
return "addnews";
}

}

文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 文件上传的配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>

<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到WebContent目录下的error.jsp页面 -->
<prop
key="org.springframework.web.multipart.MaxUploadSizeExceededException">404</prop>
</props>
</property>
</bean>

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@RequestMapping(value="/upload")
public String upload(@RequestParam MultipartFile[] myfile,HttpServletRequest request) throws Exception{
for (MultipartFile multipartFile : myfile) {
if(multipartFile.isEmpty()){
System.out.println("文件未上传");
}else{
String fileName = multipartFile.getOriginalFilename();
String path1 = request.getSession().getServletContext().getRealPath("image")+File.separator;

String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileName;
System.out.println(path);
File localFile = new File(path);
multipartFile.transferTo(localFile);
}
}
return "";
}

@RequestMapping("/download")
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) throws Exception{
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
String path = request.getSession().getServletContext().getRealPath
("image")+File.separator;
InputStream inputStream = new FileInputStream(new File(path
+ fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}

// 这里主要关闭。
os.close();

inputStream.close();
return null;
}

lightquant wechat
欢迎您订阅灯塔量化公众号!