spring mvc 笔记

来源:互联网 发布:it服务工程师培训 编辑:程序博客网 时间:2024/06/05 19:41

需要jar包(不一定是完整的)


这么多jar包肯定记不住,能记住的就是web包, core包, beans包,其他的可以启动下tomcat, 如果少了什么包,启动时一定会包缺了哪个,到时一个个加就ok了


首先配web.xml

    <servlet>        <servlet-name>spring</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>spring</servlet-name>        <url-pattern>*.html</url-pattern>    </servlet-mapping>
DispatcherServlet默认会找/WEB-INF/servletname-servlet.xml

所以新建spring-servlet.xml

<?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:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"></beans>

根据url请求找到对应的controller

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="index.html">index</prop><prop key="login.html">login</prop></props></property></bean>

<bean id="index" class="com.test.controller.IndexController"></bean><!--<bean id="login" class="org.springframework.web.servlet.mvc.ParameterizableViewController"><property name="viewName" value="login"/></bean>--><bean id="login" class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
如果仅仅转发到jsp, 不需要自己写controller, 可以用第二个和第三个bean中的class来处理

ParameterizableViewController:需要自己设置viewName

UrlFilenameViewController:根据url的来自动寻找viewName


对于返回的视图:

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/WEB-INF/view/"/><property name="suffix" value=".jsp"/></bean>

实现的IndexController

public class IndexController implements Controller{@Overridepublic ModelAndView handleRequest(HttpServletRequest arg0,HttpServletResponse arg1) throws Exception {ModelAndView mav = new ModelAndView("index");mav.addObject("name", "spring");return mav;}}


一个简单的用户登陆

@RequestMapping(value = "/doLogin", method = RequestMethod.POST)public String doLogin(@RequestParam("username") String username,@RequestParam("password") String password) {if ("admin".equals(username) && "admin".equals(password)) {return "list";} else {return "login";}}
<form action="doLogin.htm" method="post">username: <input type="text" name="username"/><br/>password: <input type="password" name="password"/><br/><input type="submit" value="login"/></form>




原创粉丝点击