java ssm框架学习——SpringMVC--2

1.  JSON数据交互

1.1. 先导入json和Spring整合的jar包

1.2. Controller中接收json

1.2.1.1.         jsp中发送json写法
  function sendJson() {
$.ajax({
    type : "post",
    url : "${pageContext.request.contextPath }/receiveJson.action",
    contentType : "application/json;charset=utf-8",
    data : '{"username":"zhangsan","age":19}',
    success : function(data) {
        alert(data);
    }
});
}
1.2.1.2.         controller中接收json
@RequestMapping("/receiveJson")
public void receiveJson(@RequestBody User user) {
}

1.3. Controller中给客户端响应Json

@RequestMapping("/getJson")
public @ResponseBody User getJson() {
    User user = new User();
    user.setUsername("lisi");
    user.setSex("man");
    return user;
}

2.  文件上传

2.1.  配置虚拟目录

在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<ContextdocBase="F:\develop\upload\temp" path="/pic"reloadable="false"/>
访问http://localhost:8080/pic即可访问F:\develop\upload\temp下的图片。

2.2. 指定Tomcat放置图片的虚拟路径



2.3. 配置文件上传解析器

<!-- 文件上传 -->
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件的最大尺寸为5MB -->
    <property name="maxUploadSize">
        <value>5242880</value>
    </property>
</bean>

 

2.4. 接收上传文件,并将路径放置到对象中

@RequestMapping("/addUser")
public String addUser(User user, MultipartFile multipartFile) throws Exception, IOException {
    // 1--获取文件名称
    String filename = multipartFile.getOriginalFilename();
    // 2- 设置文件存储位置 c:/image
    String newName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
    // 3-将文件写到指定文件夹下
    multipartFile.transferTo(new File("c:/image", newName));
    // 4-将文件
    user.setPic(newName);
    userService.addUser(user);
    return "redirect:selectUser.action";
}

 

 

3.  文件下载

@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
    User userById = userService.selectUserById(16);
 
    File file = new File("c:/image", userById.getPic());
    byte[] body = null;
    InputStream is = new FileInputStream(file);
    body = new byte[is.available()];
    is.read(body);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment;filename=" + file.getName());
    HttpStatus statusCode = HttpStatus.OK;
    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
    return entity;
}

 

4.  数据回显

4.1. 普通回显

将数据放置到Request域中

4.2. 直接回显

@RequestMapping("/updateUser")
public String updateUser(User user) {
    if (user.getUsername() == null || user.getUsername() == "") {
        return "editUser";
    }
    userService.updateUser(user);
    return "redirect:selectUser.action";
}

4.3. 用ModelAttribute注解完成回显

@RequestMapping("/updateUser")
public String updateUser(@ModelAttribute("u") User user) {
    if (user.getUsername() == null || user.getUsername() == "") {
        return "editUser";
    }
    userService.updateUser(user);
    return "redirect:selectUser.action";
}

 

5.  类型转换器

5.1. 创建自定义类型转换器

public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String str) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return dateFormat.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}
}

 

5.2. springmvc文件中配置类型转换器

<!-- 配置注解的处理器映射器和适配器 -->
<!-- 默认支持参数绑定的组件:如json数据 -->
<mvc:annotation-driven conversion-service="conversionService" />
 
<!-- 配置自定以参数转换器 -->
<bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryB   ean">
    <property name="converters">
        <list>
            <bean class="com.example.project.controller.convert.DateConverter" />
        </list>
    </property>
</bean>

 

6.  拦截器

6.1. 为什么要配置拦截器

当需要使用权限控制时,可以对某些模块设置拦截器

6.2.  创建拦截器

public class MyIntercepter1 implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
        throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
    return true;
}
}

6.3. 配置拦截器

<!--拦截器 -->
<mvc:interceptors>
    <!--多个拦截器,顺序执行 -->
    <mvc:interceptor>
        <!--  针对 -->
        <mvc:mapping path="/**" />
        <bean class="com.jiyun.ssm.controller.intercepter.MyIntercepter1"></bean>
    </mvc:interceptor>
</mvc:interceptors>

6.4. 拦截器说明

preHandle

在执行contoller方法之前执行,return true 代表继续执行,否则拦截
* 返回true表示继续执行,返回false中止执行
* 这里可以加入登录校验、权限拦截等

postHandle

在执行controller方法之后,返回结果视图之前执行
这里可在返回用户前对模型数据进行加工处理,
比如这里加入公用信息以便页面显示

afterCompletion

在返回结果视图之后执行

* 这里可得到执行controller时的异常信息
* 这里可记录操作日志,资源清理等

拦截器链

配置多个拦截器,形成拦截器链

6.5.  登陆权限拦截器

6.5.1.1.         需求分析

1、有一个登录页面,需要写一个controller访问页面
2、登录页面有一提交表单的动作。需要在controller中处理。
a)    判断用户名密码是否正确
b)    如果正确 将session中写入用户信息
c)    返回登录成功,或者跳转到商品列表
3、拦截器。
a)    拦截用户请求,判断用户是否登录
b)    如果用户已经登录。放行
c)    如果用户未登录,跳转到登录页面。

6.5.1.2.         LoginIntercepter拦截器代码操作
// 1--获取用户操作的路径
String uri = request.getRequestURI();
// 判断用户是否是做和登陆相关的操作
if (uri.contains("/login")) {
    return true;
}
 
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user != null) {
    // 说明用户已经登陆
    return true;
}
// 转发到login界面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
 
return false;

 

7.  异常处理

7.1. 定义异常解析器

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception exception) {
        ModelAndView modelAndView = new ModelAndView();
        MyException e = null;
        if (exception instanceof MyException) {
            e = (MyException) exception;
        } else {
            e = new MyException("系统异常,耐心等待...");
        }
        modelAndView.addObject("errorMsg", e.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

7.2. springmvc.xml配置异常

<!--配置异常信息  -->
<bean class="com.jiyun.ssm.exception.MyExceptionResolver"></bean>

7.3. 定义自定义异常

public class MyException extends Exception {
    private String message;
 
    public MyException() {
    }
    public MyException(String message) {
        super(message);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

 

8.  Restful支持

8.1. 什么是Restful

Restful就是一个资源定位及资源操作的风格。

不是标准也不是协议,

只是一种风格,是对http协议的诠释

8.2. 通常的URL:

http://localhost:8080/ssm/queryItems.action?id=1

8.3.  Restful的URL写法:

http://localhost:8080/ssm/items/1

8.4. Restful使用方式

8.4.1.1.         修改web.xml中拦截action的方法为 *.action 为 /
*.action    代表拦截后缀名为.action结尾的
/   拦截所有但是不包括.jsp
/*  拦截所有包括.jsp
8.4.1.2.         设置静态资源不进行拦截

使用mvc标签单独文件类型配置

<mvc:resources location="/js/" mapping="/js/**"/>

使用mvc标签配置默认的处理器

<!-- 可以访问任意静态资源 -->
<mvc:default-servlet-handler/>
8.4.1.3.         Controller中写法

一个参数类型

@RequestMapping("/selectUserById/{id}")
public String selectUserById(@PathVariable Integer id, Model model) {
 
http://localhost:8080/Day03_SSM/selectUserById/2

一个参数,映射和参数名称不一致类型

@RequestMapping("/selectUserById/{xx}")
public String selectUserById(@PathVariable(value="xx") Integer id, Model model)

多参数类型

@RequestMapping("/selectUserById/{id}/{username}")
public String selectUserById(@PathVariable Integer id,@PathVariable String username, Model model)
http://localhost:8080/Day03_SSM/selectUserById/2/lisi

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值