help in implementing show details view - spring-mvc

hi
Trying to build my own spring application,I made a page to input name and age.Clicking on Submit button should take me to another page that displays the user input.I decided not to use any database.As the first step ,I decided to create a controller with a method to show the form view.After I get this right,I would implement the other methods..
package personinfo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import personinfo.form.PersonInfo;
#Controller
public class PersonInfoController {
#RequestMapping(value ="/addPerson" )
public ModelAndView showAddPersonForm(){
return new ModelAndView("addperson", "personInfoEntries", new PersonInfo());
}
#RequestMapping(value ="/addPerson" ,method =RequestMethod.POST)
public String addPersonInfo(#ModelAttribute("person")PersonInfo perInfo){
String name = perInfo.getName();
int age = perInfo.getAge();
System.out.println("Name:" + name +"Age:"+ age);
return "showperson";//how to pass name and age
}
...
}
form backing object is personinfo.form.PersonInfo class
package personinfo.form;
public class PersonInfo {
private String name;
private int age;
public PersonInfo(){
}
public PersonInfo(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
/WEB-INF/jsp/addperson.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Person</title>
</head>
<body>
<h2>Add Person</h2>
<form:form action="addPerson.html" commandName="personInfoEntries">
<table>
<tr>
<td>
<form:label path="name">Name</form:label>
</td>
<td>
<form:input path="name"/>
</td>
</tr>
<tr>
<td>
<form:label path="age">Age</form:label>
</td>
<td>
<form:input path="age"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Person"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
the perinfo/WebContent/index.jsp is
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>index</title>
</head>
<body>
<jsp:forward page="addPerson.html"></jsp:forward>
</body>
</html>
/perinfo/WebContent/WEB-INF/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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>personinfo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
finally the /perinfo/WebContent/WEB-INF/dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:annotation-config />
<context:component-scan base-package="personinfo.controller" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp">
<property name="contentType" value="text/html; charset=utf-8" />
</bean>
</beans>
As chris pointed out,I added the #Controller to controller class and to the servlet.xml .
Now I am able to see the form.When I click on the submit button ,the showperson.jsp is displayed.So far so good.
When the addPersonInfo() method in PersonInfoController is executed I would like to pass the name and age values to showperson.jsp .How can I do this? I am returning a 'showperson' view name string.How can I add the arguments to it?And I couldn't work out how to implement a corresponding method to which this viewname is to be mapped.
Can someone please show me?Or do I need to modify the return types of addPersonInfo() method.
Please help.
thanks,
mark

I suggest you read this tutorial I wrote
Spring Security 3 - MVC Integration Tutorial (Part 1)
so that you can compare what items you're missing with your application.
Just by glancing at your code:
public class PersonInfoController {
#RequestMapping(value ="/addPerson" )
public String showAddPersonForm(){
System.out.println("showing AddPersonForm");
return "addperson";
}
...
}
I notice you're missing:
#Controller
#RequestMapping("/mycustommapping")
Normally I would write your code like this:
#Controller
#RequestMapping("/main")
public class PersonInfoController {
#RequestMapping(value ="/addPerson" )
public String showAddPersonForm(){
System.out.println("showing AddPersonForm");
return "addperson";
}
...
}
So now the URL should be /main/addPerson
Also in your dispatcher-servlet.xml, you don't have a
<context:annotation-config />

To answer your follow-up question,
When the addPersonInfo() method in
PersonInfoController is executed I
would like to pass the name and age
values to showperson.jsp .How can I do
this? I am returning a 'showperson'
view name string.How can I add the
arguments to it?And I couldn't work
out how to implement a corresponding
method to which this viewname is to be
mapped.
You need to add the name and age values to the model and pass that to the view. You do it inside addPerson().
#RequestMapping(value ="/addPerson" ,method =RequestMethod.POST)
public String addPersonInfo(#ModelAttribute("person") PersonInfo perInfo, Model model) {
String name = perInfo.getName();
int age = perInfo.getAge();
// Add name reference to Model
model.addAttribute("name", name);
// Add age reference to Model
model.addAttribute("age", age);
return "showperson";
}
Then in your JSP page, you should at least have something like this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<h1>Person</h1><table>
<p>name: ${id} </p>
<p>age: ${id} </p>
</body>
</html>
Check my other tutorials on the link I provided. There's plenty of examples like that

Related

responses with characteristics not acceptable according to the request "accept" headers

I am using Spring MVC. trying to send list of POJO objects to the jsp page, but I m getting the following line error at web browser:
Please help me.
Error Message
HTTP Status 406 -
The resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
"accept" headers.
Code Snap Shot :
1. Controller
#RequestMapping(value="displayUsers", method=RequestMethod.GET)
public #ResponseBody ModelAndView showUsers(HttpServletRequest request){
ModelAndView objModel=new ModelAndView();
UserDAO objUserDAO=DAOFactory.getInstanceOfUser();
// fetching list of all the users
List<User> listOfUser=objUserDAO.listOfUser();
objModel.addObject("listOfUser", listOfUser );
objModel.setViewName("showuser");
return objModel;
}
2. User DAO:
public List<User> listOfUser(){
SessionFactory factory=HibernateUtils.getInstance();
Session session=factory.openSession();
String hqlQuery="From User u";
Query query=session.createQuery(hqlQuery);
List<User> list=query.list();
return list;
}
3. Link to call showUser.jsp from register.jsp
Show Users
4. showuser.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<%# include file="genericinclude.jsp"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
</head>
<body>
<h2 align="center"><u>User List</u></h2>
<form name="showUserPage" method="post">
<table align="center" border="0">
<c:forEach var="userList" items="${listOfUser}">
<tr>
<td>${userList.userId }</td>
<td>${userList.firstName }</td>
<td>${userList.lastName}</td>
<td>${userList.userGender }</td>
<td>${userList.roll }</td>
<td>${userList.userMobile1 }</td>
<td>${userList.userMobile2 }</td>
<td>${userList.userEmail }</td>
<td> Edit /
<font color="red">Delete</font>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
5. dispatcher-servlet.xml
<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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com.marse.*"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Just remove the annotation '#ResponseBody' from the Controller method
#RequestMapping(value="displayUsers", method=RequestMethod.GET)
public ModelAndView showUsers(HttpServletRequest request){
// code...
}

how to read form data in spring?

Neither BindingResult nor plain target object for bean name 'command' available as request attribute
this is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form action="loginform" method="post">
<form:input type="text" path="name" id="userName" />
<form:input type="password" path="pass" id="password" />
<form:button value="submit"></form:button>
</form:form>
</body>
</html>
this is my Bean
package com.ews.usman.controller;
public class loginBean {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
this is my Controller
package com.ews.usman.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginFormController {
#RequestMapping(value="/loginform", method=RequestMethod.POST)
public ModelAndView formReader(#ModelAttribute("loginBean") loginBean
loginbean, BindingResult result){
ModelAndView model = new ModelAndView();
model.addObject("name", loginbean.getName());
model.addObject("pass", loginbean.getPass());
model.setViewName("result");
return model;
}
}
this is my Servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up
static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.ews.usman" />
<bean name="/loginform"
class="com.ews.usman.controller.LoginFormController"></bean>
</beans:beans>
this is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and
Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-
value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>`
You need to add a modelAttribute with a proper name to your form, otherwise the form backing bean name will default to 'command' hence you get your error
<form:form action="loginform" modelAttribute="loginBean" method="post">

HTTP Status 404 Servlet-The requested resource is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am making one simple program to take few fields as input and then after clicking on confirm button confirm.jsp will appear.
I have created Controller.java servlet to identify the button clicked and then open the jsp.
Controller.java is stored in directory WEB-INF/classes/ch2/servletController and submit.jsp,register.jsp,confirm.jsp are stored in /ch2/servletController directory.
Whenever i click on confirm button, i get below error. WebApplication is the name of my project. I am using netBeans IDE.
HTTP Status 404 - /WebApplication/ch2/servletController/Controller
type Status report
message /WebApplication/ch2/servletController/Controller
description The requested resource is not available.
Please find below web.xml,servlet and all the jsp files..
register.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Register</title>
</head>
<body>
<form method="get" action="Controller">
<p><b>E-store</b></p>
<br>
<br>
<p>Enter First Name: <input type="text" name="FirstName" value="${param.FirstName}"></p>
<p>Enter Last Name: <input type="text" name="LastName" value="${param.LastName}"></p>
<p>Enter Mail-id: <input type="text" name="MailId" value="${param.MailId}"></p>
<p>Enter PhoneNo: <input type="text" name="PhoneNo" value="${param.PhoneNo}"></p>
<p><input type="submit" name="confirmButton" value="confirm"></p>
</form>
</body>
</html>
confirm.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Confirm Details</title>
</head>
<body>
<form method="get" action="Controller" >
<p><b>E-store</b></p>
<br>
<br>
<p>First Name: ${param.FirstName}<input type="hidden" name="FirstName" value="${param.FirstName}"></input></p>
<p>Last Name: ${param.LastName}<input type="hidden" name="LastName" value="${param.LastName}"></input></p>
<p>Mail-id: ${param.MailId}<input type="hidden" name="MailId" value="${param.MailId}"></input></p>
<p>PhoneNo: ${param.PhoneNo}<input type="hidden" name="PhoneNo" value="${param.PhoneNo}"></input></p>
<input type="submit" name="EditButton" value="Edit">
<input type="submit" name="Submitbutton" value="Submit">
</form>
</body>
</html>
submit.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Confirm Details</title>
</head>
<body>
<form>
<p><b>E-store</b></p>
<br>
<br>
<p>Thank You for the registration. Your details have been submitted as follows-</p>
<p>First Name: ${param.FirstName}<input type="hidden" name="FirstName" value="${param.FirstName}"></input></p>
<p>Last Name: ${param.LastName}<input type="hidden" name="LastName" value="${param.LastName}"></input></p>
<p>Mail-id: ${param.MailId}<input type="hidden" name="MailId" value="${param.MailId}"></input></p>
<p>PhoneNo: ${param.PhoneNo}<input type="hidden" name="PhoneNo" value="${param.PhoneNo}"></input></p>
</form>
</body>
</html>
Controller.java
package ch2.servletController;
import java.io.IOException;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class Controller extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
String address=null;
if(request.getParameter("confirmButton")!= null)
{
address="confirm.jsp";
}
else if(request.getParameter("EditButton")!= null)
{
address="register.jsp";
}
else if(request.getParameter("Submitbutton")!=null)
{
address="submit.jsp";
}
RequestDispatcher Dispatcher=request.getRequestDispatcher(address);
Dispatcher.forward(request, response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>FirstController</servlet-name>
<servlet-class>ch2.servletController.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstController</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>First JSP</title>
</head>
<body>
<form>
<p><b>Welcome to E-store</b></p>
<br>
<br>
<p>Click to Register</p>
</form>
</body>
</html>
I'd be grateful if anyone can help me to solve this problem.
Many Thanks in Advance.
I had to change the location of register.jsp to web directory where index.jsp is located and it worked for me.

Why is the program showing a 404 error.. The HTML page when clicked

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>FirstProject</display-name>
<servlet>
<servlet-name>ServletClass1</servlet-name>
<servlet-class>com.test.ServletClass1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletClass1</servlet-name>
<url-pattern>/first.*</url-pattern>
</servlet-mapping>
<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>
</web-app>
first.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Page</title>
</head>
<body>
<form name="f1" action="first" method="get">
<input type="text" name=t/>
<button value="Click" type="submit"></button>
</form>
</body>
</html>
ServletClass1.java
package com.test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletClass1 extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String msg = request.getParameter("t");
out.println("the msg is"+msg);
}
}
Your <form action> URL needs to match the <url-pattern> of the servlet mapping. Right now it doesn't. Fix your servlet mapping <url-pattern> as follows:
<url-pattern>/first</url-pattern>
See also:
Our servlets wiki page - Contains some Hello World examples
Unrelated to the concrete problem, please make sure that you aren't reading heavily outdated resources/books/tutorials. Your web.xml is declared conform Servlet 2.4 which is almost 9 years old already. We're since 2.5 years already on Servlet 3.0.

Question about spring #ModelAttribute taking any arbitrary string

While taking lessons in spring3 I coded a sample from a tutorial. I created a controller as below
package my.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import my.spring.form.Contact;
#Controller
public class ContactController {
#RequestMapping(value ="/addContact",method =RequestMethod.POST)
public String addContact(#ModelAttribute("contact") Contact ct){
System.out.println("First Name:" + contact.getFirstname() + "Last Name:" + contact.getLastname());
return "redirect:contacts.htm";
}
#RequestMapping("/contacts")
public ModelAndView showContacts() {
System.out.println("showing contacts");
return new ModelAndView("contact", "userEntries", new Contact());
}
}
Then I decided to play around with it and modified the #ModelAttribute in method parameter from
public String addContact(#ModelAttribute("contact") Contact ct)
to
public String addContact(#ModelAttribute("somevalue") Contact ct)
Still I couldn't find any change in behaviour of the application. This was a bit of surprise for me. As I understood, the data from form is collected in a Contact object and using #ModelAttribute that object is bound to the parameter ct. This parameter is then used to process inside the method.
Is it that the actual string used inside #ModelAttribute( ) doesn't matter?
Here is the WEB-INF/jsp/contact.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Contact Manager</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form action="addContact.htm" commandName="userEntries">
<table>
<tr>
<td>
<form:label path="firstname">First Name</form:label>
</td>
<td>
<form:input path="firstname"/>
</td>
</tr>
<tr>
<td>
<form:label path="lastname">Last Name</form:label>
</td>
<td>
<form:input path="lastname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
and the spring servlet configuration
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="my.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Finally, the index.jsp forwards to contacts
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>my index</title>
</head>
<body>
<jsp:forward page="contacts.htm"></jsp:forward>
</body>
</html>
It will be used for mapping the model attribute to the form:
<form:form modelAttribute="myObject">
</form>
You will have to use
public String controllerMethod(#ModelAttribute("myObject") Object obj){
....
}
If you don't use the same value in both model attribute values you won't be able to see the error messages of the validation (when doing in the controller result.rejectValue and in the jsp <form:errors/> tag).
There are no differences to populate the values from the form in the object because you can use html tags instead of spring tags, and in the html tags you only have the name attribute to map the value.
In case you use #ModelAttribute in a method like below, you will insert in the model an attribute named "myObject" with value the object returned. This is another feauture of this annotation and it will be invoked before any method of the controller.
#ModelAttribute("myObject") Object obj
public Object method(){
...
return obj;
}

Resources