java框架学习——SpringMVC常用方法使用详细

上篇博客中详细介绍了搭建环境的步骤,本篇博客基于上篇博客的基础上实现一些常用的方法。(依赖包也使用上篇博客中的依赖),并创建本次需要的文件。
项目结构创建完成后如下图:
在这里插入图片描述
一.编写实体类和控制器以及utils中的代码
1.实体类代码
①Account.java中代码如下:

package cn.lut.domain;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author Roy
 * @date 2020/7/30 11:10
 */
public class Account implements Serializable {
    private String username;
    private String password;
    private Double money;
//绑定集合类型
    private List<User> list;
    private Map<String,User> map;

    @Override
    public String toString() {
        return "Account{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", money=" + money +
                ", list=" + list +
                ", map=" + map +
                '}';
    }

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }

    public Map<String, User> getMap() {
        return map;
    }

    public void setMap(Map<String, User> map) {
        this.map = map;
    }
    //引用类型的封装
    //private User user;

   /* public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
*/

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Double getMoney() {
        return money;
    }
    public void setMoney(Double money) {
        this.money = money;
    }
}

②User.java中的代码如下:

package cn.lut.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private String uname;
    private Integer age;
    private Date date;

    @Override
    public String toString() {
        return "User{" +
                "uname='" + uname + '\'' +
                ", age=" + age +
                ", date=" + date +
                '}';
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

2.编写控制器controller中的代码
基本方法详细介绍

@RequestParam注解的使用把请求中指定的参数给控制器中的形参赋值
@RequestBody注解用于获取请求体内容直接使用得到的是key=value&key=value...结构的数据,get请求方式不适用
@PathVariable注解用于绑定url中的占位符请求url中/delete/{id}这个{id}就是url占位符。
@RequestHeader用于获取请求消息头一般不怎么用。
@CookieValue用于把指定cookie名称的值传入控制器方法参数
@ModelAttribute出现在方法上表示当前方法会在控制器的方法执行之前,先执行,它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。出现在参数上,获取指定的数据给参数赋值
@SessionAttribute用于多次执行控制器方法间的参数共享

①AnnoController.java中的代码如下:

package cn.lut.controller;

import cn.lut.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/anno")
@SessionAttributes(value = {"msg"})//把msg存入到session域中
public class AnnoController {
    @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam(name="name") String username){
        System.out.println("Execute");
        System.out.println(username);
        return "success";
    }
    /*获取到请求体的内容*/
    @RequestMapping("/testRequestBody")
    public String testRequestBody(@RequestBody String body){
        System.out.println("Execute");
        System.out.println(body);
        return "success";
    }
/*PathVariable注解*/
    @RequestMapping(value = "/testPathVariable/{sid}",method = RequestMethod.POST)
    public String testPathVariable(@PathVariable(name = "sid")String id){
        System.out.println("Execute");
        System.out.println(id);
        return "success";
    }
    //获取请求头的值
    @RequestMapping(value = "/testRequestHeader")
    public String testRequestHeader(@RequestHeader(value = "Accept")String header){
        System.out.println("Execute");
        System.out.println(header);
        return "success";
    }
    //获取cookie的值
    @RequestMapping(value = "/testCookieValue")
    public String testCookieValue(@CookieValue(value = "JSESSIONID")String cookieValue){
        System.out.println("Execute");
        System.out.println(cookieValue);
        return "success";
    }
   // SessionAttributes的注解
   @RequestMapping(value = "/testSessionAttributes")
   public String testSessionAttributes(Model model){
       System.out.println("Execute");
       model.addAttribute("msg","Hello");
       return "success";
   }
   //获取msg值
    @RequestMapping(value = "/testSessionAttributes")
    public String getSessionAttributes(ModelMap modelMap){
        System.out.println("Execute");
       String msg=(String) modelMap.get("msg");
        System.out.println(msg);
        return "success";
    }
    //清楚msg值
    @RequestMapping(value = "/testSessionAttributes")
    public String delSessionAttributes(SessionStatus status){
        System.out.println("Execute");
        status.setComplete();
        return "success";
    }
    //ModelAttribute
    @RequestMapping(value = "/testModelAttribute")
    public String testModelAttribute(@ModelAttribute("abc") User user){
        System.out.println("Execute");
        System.out.println(user);
        return "success";
    }
    //该方法先执行无返回值
    @ModelAttribute
    public void showUser(String uname, Map<String,User>map){
        System.out.println("showUserExecuting....");
        User user=new User();
        user.setUname(uname);
        user.setAge(23);
        user.setDate(new Date());
        map.put("abc",user);

    }
    /*//该方法先执行有返回值
@ModelAttribute
    public User showUser(String uname){
        System.out.println("showUserExecuting....");
        User user=new User();
        user.setUname(uname);
        user.setAge(23);
        user.setDate(new Date());
        return user;
    }*/
}

请求映射,path请求路径
 RequestMapping注解作用:建立请求URL和处理请求方法之间的对应关系
属性:value:用于指定请求的URL和path属性的作用是一样的
method:指定请求的方式@RequestMapping(method = {RequestMethod.POST,RequestMethod.GET})
 params:用于指定限制请求参数的条件,支持简单的表达式,要求请求的参数key和value必须和配置一样。params = {"username"}
header:用于限制请求消息头的条件headers = {"Accept"}

②Hello.java中的代码如下:

package cn.lut.controller;

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

/**
 * @author Roy
 * @date 2020/7/29 16:52
 * 控制器类
 */
@Controller
@RequestMapping(path = "/user")
public class HelloController {
    @RequestMapping(path="/hello")
    public String sayHello(){
        System.out.println("Hello SpringMVC");
        return "success";
    }
    @RequestMapping(path = "/testRequestMapping")
    public String testRequestMapping(){
        System.out.println("Test RequestMapping....");
        return "success";
    }
}

③ParamController.java中的代码如下:

package cn.lut.controller;

import cn.lut.domain.Account;
import cn.lut.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * @author Roy
 * @date 2020/7/30 10:56
 * 请求参数绑定
 */
@Controller
@RequestMapping(path = "/param")
public class ParamController {
    @RequestMapping("/testParam")
    public String testParam(String username){
        System.out.println("execute");
        System.out.println("username:"+username);
        return "success";
    }
//请求参数绑定把数据封装到javabean的类中
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("execute");
        System.out.println(account);
        return "success";
    }
    //自定义类型转换器
    @RequestMapping("/saveUser")
    public String saveUser(User user){
        System.out.println("execute");
        System.out.println(user);
        return "success";
    }
    //自定义原生API
    @RequestMapping("/saveServlet")
    public String saveServlet(HttpServletRequest request, HttpServletResponse response){
        System.out.println("execute");
        System.out.println(request);
        HttpSession session= request.getSession();
        System.out.println(session);
       ServletContext servletContext= session.getServletContext();
        System.out.println(servletContext);
        System.out.println(response);
        return "success";
    }
}

3.编写时间转换格式的代码
StringToDateConverter.java中的代码如下:

package cn.lut.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Roy
 * @date 2020/7/30 11:48
 * 把字符串转换成日期
 */
public class StringToDateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String s) {
        //判断
        if(s==null){
            throw new RuntimeException("请出入参数!");
        }
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        //把字符串转换成日期
        try {
        return df.parse((s));
        }catch (Exception e){
   throw new RuntimeException("参数出错!");
        }
    }
}

4.编写配置文件web.xml和springmvc.xml
①web.xml中的配置如下:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置前端控制器-->
<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--前端控制其加载配置文件-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--配置解决中文乱码的过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

②springmvc.xml中的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="cn.lut"></context:component-scan>
    <!--视图的解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置自定义的类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.lut.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>
    <!--开启注解springMVC的支持-->
    <mvc:annotation-driven conversion-service="conversionService"/>
</beans>

5.编写jsp页面
①首先在pages下新建success.jsp用于成功页面的显示


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Success</title>
</head>
<body>
<h3>成功跳转</h3>
${msg}
${sessionScope}
</body>
</html>

②index.jsp中的代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>入门程序</h3>
<%--<a href="hello">入门程序</a>--%>
<a href="user/testRequestMapping">RequestMapping注解</a>
</body>
</html>

③anno.jsp中的代码如下:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--常用的注解--%>
<a href="anno/testRequestParam?name=He">RequestParam</a>
<form action="anno/testRequestBody" method="post">
   name:<input type="text" name="username"/><br/>
   Age:<input type="text" name="age"/><br/>
    <input type="submit" value="提交"/>
</form>
<a href="anno/testPathVariable/10">testPathVariable</a><br/>
<a href="anno/testRequestHeader">testRequestHeader</a><br/>
<a href="anno/testCookieValue">testCookieValue</a><br/>
<form action="anno/testModelAttribute" method="post">
    name:<input type="text" name="uname"/><br/>
    Age:<input type="text" name="age"/><br/>
    <input type="submit" value="提交"/>
</form>
<a href="anno/testSessionAttributes">testSessionAttributes</a><br/>
<a href="anno/getSessionAttributes">getSessionAttributes</a><br/>
<a href="anno/delSessionAttributes">delSessionAttributes</a><br/>
</body>
</html>

④param.jsp中的代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--请求参数绑定--%>
<%--<a href="param/testParam?username=hehe">请求参数绑定</a>--%>
<%--把数据封装在Account类中
<form action="param/saveAccount" method="post">
    username:<input type="text" name="username"/><br/>
    password:<input type="text" name="password"/><br/>
    money:<input type="text" name="money"/><br/>
   &lt;%&ndash; Uname:<input type="text" name="user.uname"/><br/>
    UAge:<input type="text" name="user.age"/><br/>&ndash;%&gt;
    <input type="submit" value="提交"/>--%>

<%--把数据封装在Account类中,类中存在list和map集合--%>
<%--<form action="param/saveAccount" method="post">
    username:<input type="text" name="username"/><br/>
    password:<input type="text" name="password"/><br/>
    money:<input type="text" name="money"/><br/>
     Uname:<input type="text" name="list[0].uname"/><br/>
     UAge:<input type="text" name="list[0].age"/><br/>
    Uname:<input type="text" name="map['one'].uname"/><br/>
     UAge:<input type="text" name="map['one'].age"/><br/>
    <input type="submit" value="提交"/>--%>
<%--<form action="param/saveUser" method="post">
    &lt;%&ndash;自定义类型转换器&ndash;%&gt;
    Uname:<input type="text" name="uname"/><br/>
    UAge:<input type="text" name="age"/><br/>
    UBorn:<input type="text" name="date"/><br/>
    <input type="submit" value="提交"/>
</form>--%>
<a href="param/saveServlet">Servlet原生的API</a>
</body>
</html>

至此运行tomcat服务器就可以成功运行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值