发表于: 2018-04-20 23:51:13

1 634





day22



今天完成的事情:


紧接着昨天的学习。

对于某些场景,我们希望某些资源只能通过指定的方式访问(比如只能Get),可通过以下来实现。附:如果不通过method指定,默认Get和Post都可以访问。

 */
@Controller
@RequestMapping(value = "/User2")
public class HelloAction4 {

public HelloAction4() {
       System.out.println("HelloAction()::"+this.hashCode());
   }

// 用户登录限定只能接受get请求(或post)
@RequestMapping(method = RequestMethod.GET,value = "/login")
public String loginMethod(Model model, String username) throws Exception{
       System.out.println(""+username );
       model.addAttribute("message","登录成功了,是的,呵呵");
       return "success";
   }

//  method内部可以放数组,通过下面的形式,表示PostGet请求都可以处理
@RequestMapping(method = {RequestMethod.POST,RequestMethod.GET},value = {"/register"})
public String registerMethod(Model model, String username, int salary,String hiredate) throws Exception{
       System.out.println(""+username+":"+salary+":"+hiredate);
       model.addAttribute("message","没错又他妈注册成功了");
       return "success";
   }
}


如果以post形式登录会报错。


上面的Post请求是通过表单指定来实现的如下:

<form action="${pageContext.request.contextPath}/User2/login.action" method="post"></form>

因为如果不指定,默认访问的请求方式是Get。


也可以通过下面传入传统web参数,不过不提倡,网上说耦合了,什么叫耦合我都不知道。

注意,下面我把返回参数改为void了,还不报错,而且方法传入参数支持好多,真的挺灵活。下面由于我自己重定向了网址,所以不需要再返回路径以供核心控制器给您转发了,如果方法内同时存在你的转发或重定向和returne的转发,优先执行你的,如下图,如果return没有注释再把返回类型改为Stirng,最终还是会访问你的重定向页面。

@RequestMapping(method = {RequestMethod.POST,RequestMethod.GET},value = {"/register"})
public void registerMethod(
HttpServletRequest request, HttpServletResponse response ) throws Exception {

//获取用户名和薪水
   String username = request.getParameter("username");
   String salary = request.getParameter("salary");

   System.out.println("用户注册: " + username + ":" + salary);

   //绑定到域对象中
   request.getSession().setAttribute("username", username);
   request.getSession().setAttribute("salary", salary);

   //重定向到页面

   response.sendRedirect("/jsp/success.jsp");

    // returne “/success.jsp”

}


把信息放到域对象中,然后在jsp页面直接取出来,成功取出来了,这里只展示代码不展示结果了。

<html>
<head>
   <title>第一次用,请多指教</title>
</head>
<body>

   您已成功访问<br/>
   ${username}<br/>
   ${salary}<br/>

</body>
</html>




明天计划的事情:


1.学习使用springMvc的其他注解

2.学习C标签,学习jstl。

3.学习Json


遇到的问题:


找不到tomcant的jsp解析文件,以前用eclipse时这些文件在tomcat安装目录的项目路径下,现在用idea却找不到

The description below uses the variable name $CATALINA_HOME to refer to the directory into which you have installed Tomcat 5, 

and is the base directory against which most relative paths are resolved. However, if you have configured Tomcat 5 for multiple

 instances by setting a CATALINA_BASE directory, you should use $CATALINA_BASE instead of $CATALINA_HOME for each of these references.

根据文档说明,透明cat有CATALINA_HOME和CATALINA_BASE之分,CATALINA_HOME就是tomcat的安装路径,CATALINA_BASE

是工作目录,而项目解析文件就在工作目录的work路径下,也可以在每次日志打印的地方看到。

然后在这个路径下找到了jsp解析后的JAVA文件。




收获:

 

 了解了Springmvc的处理请求流程。

 

 

 

 



返回列表 返回列表
评论

    分享到