1.@RequestMapping 用法
SpringMVC中,@RequestMapping用来处理请求,比如XXX.do
- @RequestMapping("/aaa")
- public class ccccontroller{
-
- @RequestMapping("/bbb")
-
- public String xxx()
- {
-
- return;
- }
- }
2:接收带参数的请求,接收用户请求参数 值
请求1: /test/start.do?name=zhangsan
请求2: /test/start/zhangsan.do
在请求2中 将参数作为请求URL传递,感觉用的不习惯
采用 URL模板
@RequestMapping("/start/{name}")//这个name 随便 啥都可以
- public String start(@PathVariable("name") string name){
- return ;
- }
包含多个 @RequestMapping ("/start/{name}/{age}")
3不同请求方法,用不同处理方法 get post
@RequestMapping (value="/start" ,method=RequestMethod.GET)//处理post 就换成 POST
另外,如果Servlet想要做到/test/start/zhangsan.do这种请求的话
需要 URL 重写才能做到,或者用 /start/* 作为 Servlet 请求控制器,在其中进行截取和判断。
第二种方法:自己写一个 URL 重写的 Filter
第三种方法:使用现成的 urlrewriter 工具
第四种方法:使用 Web 服务器的 URL 重写功能
Servlet中用Filter重写示例
web.xml中:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns=" http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <servlet>
- <servlet-name>Action</servlet-name>
- <servlet-class>com.bao.servlet.Action</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>Action</servlet-name>
- <url-pattern>/Action</url-pattern>
- </servlet-mapping>
-
- <filter>
- <filter-name>action_name</filter-name>
- <filter-class>com.bao.filter.ActionNameFilter</filter-class>
- <init-param>
- <param-name>pattern</param-name>
- <param-value>/action/[^/]+</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>action_name</filter-name>
- <url-pattern>/action/*</url-pattern>
- </filter-mapping>
- </web-app>
Filter中:
- private Matcher matcher;
-
- Matcher 不是线程安全的,所以这样写是错误的。改正一下:
-
- package com.bao.filter;
-
- import java.io.IOException;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
-
- public class ActionNameFilter implements Filter {
-
- private Pattern pattern;
-
- public void init(FilterConfig config) throws ServletException {
- String p = config.getInitParameter("pattern");
- pattern= Pattern.compile(p);
- }
-
- public void doFilter(ServletRequest req, ServletResponse res,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest)req;
- String context = request.getContextPath();
- String uri = request.getRequestURI();
-
- String path = uri.substring(context.length());
- if(pattern.matcher(path).matches()) {
-
- int idx = uri.lastIndexOf("/");
- String name = uri.substring(idx + 1);
- request.getRequestDispatcher("/Action?username=" + name).forward(req, res);
- } else {
-
- chain.doFilter(req, res);
- }
- }
-
- public void destroy() {
-
- }
- }