springmvc中的@RequestParam注解以及@Scope注解,重定向与转发,视图解析器与中文乱码,异常处理

一、springMVC中常用注解

1.   @Controller注解:




2.   @RequestMapping注解:

 

3.   @Scope注解:

 

4.   @AutoWired注解:实现依赖注入

5.   @RequestParam注解:

 

二、springMVC获取参数信息

三、springMVC之重定向与转发

1.   传统servlet实现重定向与转发

 

2.   springMVC实现重定向

3.   springMVC实现转发

 

 

一、视图解析器:视图解析器对重定向无效,只对转发有效

 

 

二、中文乱码问题


建立一个过滤器解决乱码问题

三、springMVC带数据给jsp页面

第一种方式:通过reqeust域

第二种方式:通过Model带数据(默认存放到request域中)

第三种方式:通过Map集合带数据

 

四、统一异常处理(*):



下面是项目的目录:


/**
 * Project Name:dt48_springMVC2
 * File Name:LoginController.java
 * Package Name:cn.java.controller.admin
 * Date:下午5:40:22
 * Copyright (c) 2017, bluemobi All Rights Reserved.
 *
*/

package cn.java.controller.admin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Description: <br/>
 * Date: 下午5:40:22 <br/>
 * 
 * @author dingP
 * @version
 * @see
 */
@Controller
public class LoginController {
    @RequestMapping(value = "test9")
    public void test9() {
        int i = 10 / 0;
    }

}

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * Description: 能够处理当前工程的所有controler错误<br/>
 * Date: 下午5:42:24 <br/>
 * 
 * @author dingP
 * @version
 * @see
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    // 异常处理注解
    @ExceptionHandler(Exception.class)
    public String exceptHand(Exception ex) {
        // ex.printStackTrace();
        System.out.println("哈哈,恭喜您出错了");
        return "front/error.jsp";
    }

    // 异常处理注解
    // @ExceptionHandler(ArithmeticException.class)
    // public void exceptHand2(Exception ex) {
    // System.out.println("哈哈,恭喜您出错了===============");
    //
    // }
}
package cn.java.controller.front;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.java.entity.User;

/**
 * Description: <br/>
 * Date: 下午2:16:57 <br/>
 * 
 * @author dingP
 * @version
 * @see
 */
@Controller//被这个注释后就变成了一个servlet类
@Scope("prototype")//多例,这是修饰类的
public class HomeController {
    @RequestMapping(value = "test1")
    public void test1(User user) {
        System.out.println("test1...........");
        System.out.println(user);
    }
    //@RequestParam是传递参数的.
   //@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。defaultValue = "张三"表明当用户不给值的时候默认为张三,required = false表示不用必须给user穿一个值
    @RequestMapping(value = "test2")
    public void test2(@RequestParam(name = "user", defaultValue = "张三", required = false) String username,
            @RequestParam(name = "pwd", required = true) String password, @RequestParam(name = "nianlin") Integer age) {
        System.out.println("username=" + username);
        System.out.println("password=" + password);
        System.out.println("age=" + age);
    }

    @RequestMapping(value = "submitYijian")
    public void submitYijian(@RequestParam(required = true) String content,
            @RequestParam(required = false) String phoneNum, @RequestParam(required = false) String email) {

    }
/**
 * 传统的servlet的重定向与转发
 * @param user
 * @param pwd
 * @param request
 * @param response
 * @throws Exception
 */
    @RequestMapping(value = "test3")
    public void test3(String user, String pwd, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if ("admin".equals(user) && "123".equals(pwd)) {// 登录成功
        	/**下面的这个方法是传统的servlet
        	 *  request.getRequestDispatcher("/pages/front/success.jsp").forward(request,response);
        	 */
           
            String basePath = request.getContextPath();/// dt48_springMVC2的
            response.sendRedirect("basePath/pages/front/success.jsp");
        } else {// 失败
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }
    
    /**
     * springmvc实现重定向,注意,在springmvc中,servlet类中,返回值是String的,不是重定向就是转发。
     * @param user
     * @param pwd
     * @return
     */

    @RequestMapping(value = "test4")
    public String test4(String user, String pwd) {
        if ("admin".equals(user) && "123".equals(pwd)) {// 登录成功
            return "redirect:/pages/front/success.jsp";//加上这个redirect:表示重定向
        } else {// 失败
            // return "forward:/pages/front/fail.jsp";
            return "/pages/front/fail.jsp";//默认为转发
        }
    }
   /**
    * springmvc转发,注意,在springmvc中,servlet类中,返回值是String的,不是重定向就是转发。
    * @return
    */
    @RequestMapping(value = "test5")
    public String test5() {
        return "redirect:/pages/front/success.jsp";// --->/pages/front//pages/front/success.jsp.jsp
    }

    /**
     * 注意,在springmvc中,servlet类中,返回值是String的,不是重定向就是转发。
     * @param user
     * @param pwd
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "test6")
    public String test6(String user, String pwd, HttpServletRequest request, Model model) {
        System.out.println("user=" + user);
        System.out.println("pwd=" + pwd);
        // request.setAttribute("user", user);
        // model.addAttribute("username", user);
        if ("admin".equals(user) && "123".equals(pwd)) {// 登录成功
        	/**
        	 * 在springmvc中配置了视图解析器,
        	 * <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		               <!-- 配置前缀 -->
		                 <property name="prefix" value="/pages/"></property>
		              <!-- 配置后缀 -->
		             <property name="suffix" value=""></property>
               	</bean>
               	所以在这里只需要写几个固定的位置就可以了
        	 */
            return "front/success.jsp";
        } else {// 失败
            return "front/fail.jsp";
        }
    }
/**
 * 注意,在springmvc中,servlet类中,返回值是String的,不是重定向就是转发。
 * @param map
 * @return
 */
    @RequestMapping(value = "test7")
    public String test7(Map<String, Object> map) {
        map.put("aaa", "王二麻子");
        return "front/success.jsp";
    }

    @RequestMapping(value = "test8")
    public void test8() {
        int i = 10 / 0;
    }

}
package cn.java.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Description: 能够解决当前工程下的所有乱码问题<br/>
 * Date: 下午4:27:06 <br/>
 * 
 * @author dingP
 * @version
 * @see
 */
public class EncodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest reqeust, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        reqeust.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        chain.doFilter(reqeust, response);
    }

}
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

	<!-- 配置包扫描 -->
	<context:component-scan base-package="cn.java.controller.*"></context:component-scan>
	
	<!-- 配置mvc特有的注解驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- 视图解析器 ,只对转发有效-->
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置前缀 -->
		<property name="prefix" value="/pages/"></property>
		<!-- 配置后缀 -->
		<property name="suffix" value=""></property>
	</bean>
	
</beans>
error.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath %>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>错误处理页面</title>
</head>
<body>
	<img src="<%=basePath %>/resources/images/error.gif">
</body>
</html>
fail.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath %>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>new jsp</title>
</head>
<body>
	<!-- 通过request域来保存数据 -->
	通过request域来保存数据:${requestScope.user }
	<hr>
	<!-- 通过Model封装数据 -->
	通过Model封装数据:${requestScope.username }
</body>
</html>
success.jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath %>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>登录成功</title>
</head>
<body>
	<h1 style="color:red">登录成功</h1>
	<!-- 通过request域来保存数据 -->
	通过request域来保存数据:${requestScope.user }
	<hr>
	<!-- 通过Model封装数据 ,注意的是保存在model中的数据默认保存在request域中-->
	通过Model封装数据:${requestScope.username }
	<hr>
	通过Map集合封装数据:${requestScope.aaa }
</body>
</html>

web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>dt48_springMVC2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置过滤器,放在最前面。 -->
  <filter>
  	<filter-name>encodingFilter</filter-name>
  	<!-- <filter-class>cn.java.filters.EncodingFilter</filter-class> -->
  	<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>
  
   
  <!--配置springMVC的核心控制器类:DispatcherServlet  -->
  <servlet>
  	<servlet-name>dispatcherServlet</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 与springmvc建立联系 -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  	
  </servlet>
  <servlet-mapping>
  	<servlet-name>dispatcherServlet</servlet-name>

index.xml:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/";
%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath %>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>new jsp</title>
</head>
<body>
	<%-- <form action="<%=basePath %>/test1.htm" method="post">
		<p>用户名:<input type="text" name="username"></p>
		<p>密 码<input type="password" name="password"></p>
		<p>年 龄:<input type="text" name="age"></p>
		<p><input type="submit" value="提交"></p>
	</form> --%>
	<form action="<%=basePath %>/test6.htm" method="post">
		<p>用户名:<input type="text" name="user"></p>
		<p>密 码<input type="password" name="pwd"></p>
		<!-- <p>年 龄:<input type="text" name="nianlin"></p> -->
		<p><input type="submit" value="提交"></p>
	</form>
</body>
</html>











  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值