spring 的注解:
@Component 组件注解,代表一般组件 ( @Named 通用注解)
@Repository 持久化组件的注解
@Service 业务层注解
@Controller 控制层注解
@Scope("prototype") 作用域 ,默认是singleton
@PostConstruct 初始化回调注释
@PreDestroy 销毁回调
@Resource 自动注入
配置文件中的依赖注入(ref)
<bean id="c3p0DataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wjh"/>
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="c3p0DataSource"/>
</bean>
静态工厂和实例工厂
1.静态工厂
<bean id="userService" factory-method="getUserService" class="factory.StaticFactory" />
2.实例工厂
<bean id="beanFactory" class="factory.BeanFactory"/>
<bean id="userService" factory-method="getUserService" factory-bean="beanFactory"/>
指定依赖注入
@Autowired
public void setName( @Qualifier("name") String name){ //name不能可以省略
Logger logger = Logger.getLogger(this.getClass());
logger.warn(name);
}
@Autowired
public void setName( String name){
this.name = name;
}
<bean id="name" class="java.lang.String">
<constructor-arg value="王建杭"/>
</bean>
@Resource //也可以直接放在属性上面
public void setDao(DemoDao demoDao){
this.demoDao = demoDao;
}
@Resource(name="demoDao")
public void setDao(DemoDao demoDao){
this.demoDao = demoDao;
}
@Resource只支持单个项目,不支持聚合项目
构造方法注入
@Autowired
public Demo( @Qualifier("b") String a,@Qualifier("b") String b) {
System.out.println(a);
System.out.println(b);
}
自动注入,找demoDao的id
id是demoDao
@Repository
public class DemoDao {
id是demo
@Repository("demo")
public class DemoDao {
引入配置文件,动态配置属性
<!-- 引入外部文件 -->
<context:property-placeholder location="classpath:user.properties" />
user.properties
age=18
name=jack
User.java
@Value("${age}")
private Integer age;
@Value("${name}")
private String name;
工具类的使用
<util:list id="list">
<value>1</value>
<value>2</value>
<value>3</value>
</util:list>
@Value("#{@list}")
private List<Object> list;
spring-mvc四大组件
1.前端控制器(DispatcherServlet)
作用 :负责request对象和response对象的转发和响应。
2.处理映射器
匹配处理请求的类,交个给前端控制器。
3.处理器适配器
调用适当的处理器去执行请求
4.视图解析器
根据返回的页面名称为其拼接真实的路径
web.xml配置
<!-- springMVC servlet -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- spring mvc 乱码过滤器 -->
<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>*.html</url-pattern>
</filter-mapping>
spring-mvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!-- 包扫描器 -->
<context:component-scan base-package="spring"/>
<!-- 视图转发器 前缀是 /jsp/ 后缀是 .jsp -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 登陆检测,拦截器 ,过滤器的子类-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/article/*"/>
<mvc:exclude-mapping path="/user/*"/>
<bean class="interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 上传组件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240" />
<property name="resolveLazily" value="true" />
</bean>
<!-- 开启注解映射 -->
<mvc:annotation-driven/>
<!--
配置文件中配置 url映射,不建议使用
<bean id="helloController" class="spring.controller.HelloWorldController"/>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.html">helloController</prop>
</props>
</property>
</bean> -->
</beans>
spring mvc 加载多个配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext-*.xml,
classpath:applicationContext-*.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
控制器的配置
package spring.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")//这种方法忽略后缀
public class UserController { //控制器,/user是映射路径
@RequestMapping("/login") //此方法的映射路径是 /user/login
public void login(HttpServletResponse res) throws IOException{
res.getWriter().println("login~");
}
@RequestMapping("/login") //注入参数
public void login(@RequestParam("id") int id) throws IOException{
res.getWriter().println("login~");
}
}
//转发到/jsp/test.jsp
@RequestMapping(value="/test")
public String test(HttpServletRequest req){
return "test";
}
//重定向 到/jsp/test.jsp
@RequestMapping(value="/test2")
public String test2(){
return "redirect:test";
}
//接收一个model
@RequestMapping("/test2")
public String test2(Model model){
model.addAttribute("msg", "hello");
return "redirect:/user/test.do";
}
model内的数据以get方式提交过去
拦截器的配置
spring-mvc.xml 配置
<!-- 登陆检测,拦截器 ,过滤器的子类-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/article/*"/>
<mvc:exclude-mapping path="/user/*"/>
<bean class="interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
代码如下:
package interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest req,
HttpServletResponse res, Object handler, Exception ex)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res,
Object handler, ModelAndView mv) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
Object handler) throws Exception {
/* HttpSession session = req.getSession();
String loginId = (String) session.getAttribute("loginId");
if(loginId == null){
return false;
}
return true;*/
return true;
}
}
异常处理
@ExceptionHandler //异常处理的注解,如果在一个控制器中只针对这个控制器抛出的异常有效
public String doException(MaxUploadSizeExceededException ex,Model model){
model.addAttribute("message", "文件应该要小于"+ex.getMaxUploadSize()+"字节");
return "upload/upload";
}
多个异常的处理
@ExceptionHandler({MaxUploadSizeExceededException.class,NumberFormatException.class})
@ResponseBody
public String doException(Exception ex,Model model){
//model.addAttribute("message", "文件应该要小于"+ex.getMaxUploadSize()+"字节");
return ex.getClass().toString();
}
全局异常处理
package spring.global;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice //这个类中的ExceptionHandler会捕获所有控制器抛出的异常
public class GlobalHandler{
private Logger logger = Logger.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
public String doException(Exception ex){
logger.error(ex.getMessage(),ex);
return "error/exception";
}
}
@ControllerAdvice 注解
- 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。
- 注解了@Controller的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。
- @ControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上
- @ExceptionHandler:用于全局处理控制器里的异常。
- @InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
- @ModelAttribute:本来作用是绑定键值对到Model中,此处让全局的@RequestMapping都能获得在此处设置的键值对。
代码:
@ControllerAdvice
public class AdviceControlller {
private Logger logger = Logger.getLogger(this.getClass());
//异常处理
@ExceptionHandler(Exception.class)
public String doException(Exception ex){
logger.error(ex.getMessage(),ex);
return "error/exception";
}
//参数转换
@InitBinder
public void InitBinder (ServletRequestDataBinder binder){
binder.registerCustomEditor(
java.util.Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
@ModelAttribute 的使用
@ModelAttribute
public void populateModel(@RequestParam String abc, Model model) {
model.addAttribute("attributeName", abc);
}
@ModelAttribute("attributeName")
public String addAccount(@RequestParam String abc) {
return abc;
}
public String test1(@ModelAttribute("user") UserModel user)
log4j的整合
log4j.properties文件内容(在控制台打印输出的配置):
#log4j properties
log4j.rootLogger=all,console
log4j.appender.console.threshold=warn
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.immediateFlush=true
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}-[%p]-[%l]:%m%n
#log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}-[%c]-[%p]-[%l]:%m%n
在web.xml中:
<!-- log4j配置 , -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/props/log4j.properties</param-value>
</context-param>
<!-- 6秒扫描一次配置文件的改动,会导致log4j无法关闭[FileWatchdog]线程 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>6000</param-value>
</context-param>
<!-- log4j 监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
log4j的使用
Logger logger = Logger.getLogger(this.getClass());
logger.warn("log4j输出");
控制台打印示例:
2017-05-26 10:14:53-[WARN]-[spring.controller.GlobalController.do404(GlobalController.java:18)]:log4j输出
文件上传:
在springmvc.xml中
<!-- 上传组件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240" /> //最大1024个字节
<property name="resolveLazily" value="true" /> //懒汉式加载,可进行异常获取
</bean>
在程序中:
@RequestMapping("/upload")
public String upload(MultipartFile file, //当文件上传时 用数组接收即可 (MultipartFile[] file)
HttpServletRequest res,ModelMap model) throws IOException{
if(file == null){
model.addAttribute("message", "文件为空");
return "/upload/upload";
}
String path = res.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File uploadFile = new File(path,fileName);
file.transferTo(uploadFile);
model.addAttribute("fileName", fileName);
return "/upload/res";
}
当上传的文件大于配置的字节时,需要配置一个异常处理方法
@ExceptionHandler
public String doException(MaxUploadSizeExceededException ex,Model model){
model.addAttribute("message", "文件应该要小于"+ex.getMaxUploadSize()+"字节");
return "upload/upload";
}
404错误的处理的解决方法,配置一个通配的控制器
package spring.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("**")//通配控制器,匹配所有的匹配不上其他映射路径的路径(一个*代表一层路径,**代表多层路径)
public class AlllController {
@RequestMapping("")//默认匹配
public String do404(HttpServletRequest req,Model model){
model.addAttribute("url", req.getRequestURL());
Logger logger = Logger.getLogger(this.getClass());
logger.warn("log4j输出");
return "error/404";
}
}
定义一个异常:可以指定状态,前提是这个异常不能被捕获,这个需要被抛给服务器
@ResponseStatus(value=HttpStatus.NOT_FOUND,reason="demoException")
public class DemoException extends RuntimeException {
不转发jsp,直接输出字符串
@RequestMapping(value="/other",produces="text/html;charset=UTF-8")
@ResponseBody //浏览器收到"other"字符串
public String other(){
Logger logger = Logger.getLogger(this.getClass());
logger.warn("other");
return "other";
}
@RequestMapping(value="/other",produces="text/html;charset=UTF-8")
@ResponseBody //浏览器收到"other"字符串
public void other(){
Logger logger = Logger.getLogger(this.getClass());
logger.warn("other");
res.getWriter().print("abc");
}
关于json的配置和使用
需要2个jar包 :
- jackson-mapper-asl-1.9.13.jar
jackson-core-asl-1.9.13.jar
@RequestMapping(value="a" ,produces="application/json;charset=UTF-8") public @ResponseBody User a() { User user = new User(); user.setAge(11); user.setName("小红"); return user; }
produces:请求的是json,并且以json为后缀,浏览器以.html为后缀中会接收text/html类型
在web.xml中需要配置2个映射
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/server/*</url-pattern>
</servlet-mapping>
function send(){
$.ajax({
"url" : "server/hello/a.json",
"contentType":"application/json;charset=UTF-8",
"async" : true,
"type" : "POST",
"success" : function(result){
var name = result.name;
$("#msg").html("<font style='color:red'>"+name+"</font>")
}
});
}
springMVC4.2的不支持1.x的jackson的,会报HttpMediaTypeNotAcceptableException:Could not find acceptable representation
没有匹配类型,其实是使用了MappingJackson2HttpMessageConverter.class类,这个类支持2.x的jackson,只能使用3.2的spring
jackson 1.x jar包
- jackson-mapper-asl-1.9.13.jar
- jackson-core-asl-1.9.13.jar6
spring-mvc 4.2 可以使用下面的扩展包
jackson2.x用下面的包
- jackson-annotations-2.4.0.jar
- jackson-core-2.4.2.jar
- jackson-databind-2.4.2.jar
REST(RESTful)概念
可提高伸缩性,降低耦合度便于分布式处理程序
RESTful 规范:
http://localhost:8080/web/delUser/1234
http://localhost:8080/web/orders/2017/06/18434
- POST: Create Delete Update
- GET:Read
- PUT:Update Create
DELETE:Delete
/blog/1 http GET => 查询id=1的blog
- /blog/1 http DELETE => 查删除id=1的blog
- /blog/1 http PUT => 更新 id=1的blog
- /blog/add http POST => 新增blog
spring对REST的支持
- @RequestMapping 指定要处理请求的URI方法和HTTP的请求动作
- @PathVariable 将URI中请求模板中的变量映射到处理方法的参数上
- 利用Ajax,可以在浏览器中发送PUT和Delete的请求
在控制器中
@RequestMapping("/rest/{id}")
public @ResponseBody String rest(@PathVariable int id){
logger.info(id);
return "rest";
}
指定方法和指定path参数名
@RequestMapping(value="/rest/{id}",method=RequestMethod.GET)
public @ResponseBody String rest(@PathVariable("id") int i){
logger.info(i);
return "rest";
}
静态资源的访问控制
<!-- 静态资源访问 -->
<mvc:resources location="/jsp/" mapping="/jsp/*"/>
<mvc:resources location="/image/" mapping="/image/*"/>
<mvc:resources location="/css/" mapping="/css/*"/>
<mvc:resources location="/js/" mapping="/js/*"/>
<!--默认的资源访问控制-->
<!-- <mvc:default-servlet-handler/> -->
自动封装javaBean
@RequestMapping("/addUser")
public @ResponseBody String addUser(User user){
//logger.info(user);
if(user != null)
return user.toString();
return "user is null";
}
<form action="demo/addUser" method="post">
<input type="text" name="email" value="293@qq.com" >
<input type="text" name="password" value="123">
<input type="text" name="nickname" value="jack">
<input type="submit" value="注册" >
</form>
多个javaBean封装
@RequestMapping("/addUser")
public @ResponseBody String addUser(User user,UserInfo info){
//logger.info(user);
if(user == null)
return "user is null";
if(info == null)
return "info is null";
return user.toString()+"|"+info.toString();
}
<form action="demo/addUser" method="post">
<input type="text" name="email" value="293@qq.com" >
<input type="text" name="password" value="123">
<input type="text" name="nickname" value="jack">
<input type="text" name="age" value="18">
<input type="text" name="sex" value="man">
<input type="submit" value="注册" >
</form>
- html中提交的字段会自动封装成User实体对象,自动匹配属性,没有的值则为空
- 也可以直接注入User实体对象的引用,如:name=”type.name”就可以为user中的type对象的name进行注入
- 封装对象会被放入model中,转发到页面中可以直接使用之前提交过去的数据,如:
代码如下:
<input type="text" name="email" value="${user.email}" >//user不可省略
<input type="text" name="type.name" value="${user.type.name}" >
传递参数的类型转换
@InitBinder
public void InitBinder (ServletRequestDataBinder binder){
binder.registerCustomEditor(
java.util.Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
spring的测试方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationTest.xml")
public class Demo {
@Resource
private TestDao testDao;
@Test
public void demo1() {
testDao.print();
}
}