Java spring MVC - Student database. Not able to edit the student document - java

I have created a java spring MVC web application for student management, Iam able to add the student . But when i click on edit student it shows HTTP 400 - The request sent by the client was syntactically incorrect.
Controller :
package com.akhil.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.RequestParam;
importorg.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;
import com.akhil.model.Student;
import com.akhil.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping("/")
public String setupForm(ModelMap model){
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(#ModelAttribute Student student, BindingResult result, #RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
studentService.add(student);
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/editstudent", method=RequestMethod.GET)
public String editstudent(#ModelAttribute Student student, BindingResult result, #RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
studentService.edit(student.getStudentId());
map.put("student",studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
}
View:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!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>Student Management</title>
</head>
<body>
<h1>Students Data</h1>
<form:form action="student.do" method="POST" commandName="student">
<table>
<tr>
<td><form:label path="studentId">Student ID:</form:label></td>
<td><form:input path="studentId" value="${Student.studentID}" /> </td>
</tr>
<tr>
<td>First name</td>
<td><form:input path="firstname" value="${Student.firstname}"/></td>
</tr>
<tr>
<td>Last name</td>
<td><form:input path="lastname" value="${Student.lastname}" /></td>
</tr>
<tr>
<td>Year Level</td>
<td><form:input path="yearLevel" value="${Student.yearLevel}" /> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
</td>
</tr>
</table>
</form:form>
<br>
<table border="1">
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Year level</th>
</tr>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.studentId}</td>
<td>${student.firstname}</td>
<td>${student.lastname}</td>
<td>${student.yearLevel}</td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>CRUDWebAppMavenized</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<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>/</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>

#RequestMapping(value="/editstudent", method=RequestMethod.GET)
public String editstudent(#ModelAttribute Student student,BindingResult result, #RequestParam String action, Map<String, Object> map)
this approach is wrong you cant get a studentObject from a GET Request,
since you are trying to edit the object i suggest using a POST request remove the #modelAttribute annotation inside the method parameter
this annotation forms an object from the fields inside the form.
BindingResult collects errors if it cant form an object from the incoming request.
since you are not submitting a form you dont need any of them.
but you can fetch the student object from the database using the id you are getting from the url
public String editstudent(#RequestParam("id") int id, Model model){
student studentobj = studentservice.get(id);//assuming that this loads the object from database;
model.addAttribute("student",studentobj);
return "student";
}
and now you can represent the student details inside the student.jsp
then have a form to edit those details.

Related

Spring: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I tried following a tutorial for Spring but I can't get my app working on Tomcat. Every link I try is a 404 with the following error:
The origin server did not find a current representation for the target
resource or is not willing to disclose that one exists.
I tried every possible combination of url. Here's my code. Even by copy-pasting the tutorial it doesn't work.
StudentController.java
package com.learningspring;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student(){
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent( #ModelAttribute("SpringWeb") Student student, ModelMap model){
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
web.xml
<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>Spring MVC Form Handling</display-name>
<servlet>
<servlet-name>StudentSpring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StudentSpring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
StudentSpring-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.learningspring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
student.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Spring MVC Form</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="post" action="/HelloWeb/addStudent">
<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><form:label path="id">ID</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page isELIgnored = "false" %>
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>

HTTP Status 500 - Servlet.init() for servlet spring-dispatcher threw exception_(spring-dispatcher-servlet is good)

I am creating a sample website for College last time when i ran the code it was running fine but when i ran it after some time I got this Error
"HTTP Status 500 - Servlet.init() for servlet spring-dispatcher threw exception"
Error Messages -
type Exception report
message Servlet.init() for servlet spring-dispatcher threw exception
description The server encountered an internal error that prevented it
from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet
spring-dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:748)
Following are the classes which i am working on
spring-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.newseries.hecontroller" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
studentAdmissionController -
package com.newseries.hecontroller;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.text.DateFormat;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class studentAdmissionController {
#InitBinder
public void initBinder(WebDataBinder binder) {
//binder.setDisallowedFields(new String[] {"mobileNumber"});
SimpleDateFormat sdf = new SimpleDateFormat("yyyy****MM**dd");
binder.registerCustomEditor(Date.class, "newDate", new CustomDateEditor(sdf, false));
//binder.registerCustomEditor(String.class, "firstName", new StudentNameEditor());
}
#RequestMapping(value="/admissionForm.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
#ModelAttribute
public void addcommonmethod(Model model) {
model.addAttribute("headermessage", "SIT college of Engineering India");
}
#RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#ModelAttribute("student1") Student student1, BindingResult result) {
if(result.hasErrors()) {
ModelAndView model1 = new ModelAndView("AdmissionForm");
return model1;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
return model;
}
}
AdmissionForm.jsp -
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h1>${headermessage}</h1>
<h2>College Admission Courses</h2>
<form:errors path="student1.*"/>
<form action="/FirstSpringMVCApplication02/submitAdmissionForm.html"
method="post">
<table>
<tr> <td>Student's FirstName : </td> <td> <input type="text" name="firstName" /> </td> </tr>
<tr> <td>Student's LastName : </td> <td> <input type="text" name="lastName" /> </td> </tr>
<tr> <td>Student's Hobby : </td> <td> <input type="text" name="studentHobby" /> </td> </tr>
<tr> <td>Student's MobileNumber : </td> <td> <input type="text" name="mobileNumber" /> </td> </tr>
<tr> <td>Student DOB : </td> <td> <input type="text" name="newDate" /> </td> </tr>
<tr> <td>Student skillSet : </td> <td> <select name="studentSkills" multiple>
<option value="CoreJava">Core Java</option>
<option value="SpringMVC">SpringMVC</option>
<option value="SpringIOC">SpringIOC</option>
<option value="SpringAOP">SpringAOP</option>
<option value="SpringDAO">SpringDAO</option>
<option value="SpringBoot">SpringBoot</option>
<option value="Multithreading">Multithreading</option>
<option value="Collection">Collection</option>
<option value="Oops">Oops</option>
<option value="Hibernate">Hibernate</option>
</select></td> </tr>
</table>
<table>
<tr>
<td>Student's Address :</td>
</tr>
<tr>
<td>Country: <input type="text" name="studentAddress.country" /></td>
<td>City : <input type="text" name="studentAddress.city" /></td>
<td>Street : <input type="text" name="studentAddress.city" /></td>
<td>pinCode: <input type="text" name="studentAddress.pinCode" /></td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</body>
</html>
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstSpringMVCApplication02</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
AdmisssionSuccess.jsp -
<html>
<body>
<h1>${headermessage}</h1>
<h2>Congrats!! The Engineering college has processed the
application Successfully</h2>
<h3>Details submitted by you are: :</h3>
<table>
<tr>
<td>Student_FirstName : </td>
<td>${student1.firstName}</td>
</tr>
<tr>
<td>Student_LastName : </td>
<td>${student1.lastName}</td>
</tr>
<tr>
<td>Students_Hobby : </td>
<td>${student1.studentHobby}</td>
</tr>
<tr>
<td>Student's_MobileNumber : </td>
<td>${student1.mobileNumber}</td>
</tr>
<tr>
<td>Student's_DOB : </td>
<td>${student1.newDate}</td>
</tr>
<tr>
<td>Student's_skills : </td>
<td>${student1.studentSkills}</td>
</tr>
<tr>
<td>Student's Address : </td>
<td>country : ${student1.studentAddress.country}
city : ${student1.studentAddress.city}
street : ${student1.studentAddress.street}
pincode : ${student1.studentAddress.pinCode}</td>
</tr>
</table>
</body>
</html>
add this param into web.xml file
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-dispatcher-servlet.xml</param-value>
</context-param>

Java set servlet request into jsp page

I have to load some values from servlet to jsp page
My "order_processing.jsp" JSP Page code is given below
<%#page import="test.abc.io.User_Objects"%>
<%# page import="java.util.Date" %>
<%# 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>Order Processing</title>
</head>
<body>
<form name="OrderProcessing" action="order_processing" method="post" onsubmit="return validateForm();">
<table align="center">
<tr align="center">
<td colspan="2">
<img src="images/otn_logo.jpg"/>
</td>
</tr>
<tr>
<td>First Name :</td>
<td><input type="text" id="txtFirstname" name="txtFirstname" value="${reqObj.firstname}" /></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input type="text" id="txtLastname" name="txtLastname" value="${reqObj.lastname}" /></td>
</tr>
<tr>
<td>Communication Email :</td>
<td><input type="text" id="txtCommunicationEmail" name="txtCommunicationEmail" value="${reqObj.commEmail}" />
<label style="color: red;">*</label></td>
</tr>
<tr align="left">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
My User_Objects code
public class User_Objects {
public String firstname;
public String lastname;
public String commEmail;
}
My "OrderProcessing" code
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OrderProcessing extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
User_Objects fillObj = new User_Objects();
fillObj.firstname = "Test";
fillObj.lastname = "User1";
fillObj.commEmail = "tuser01#xyz.com";
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/order_processing.jsp");
view.forward(request, response);
} catch (Exception e) {
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("into OrderProcessing java");
}
}
My web.xml code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>OrderProcessing</display-name>
<welcome-file-list>
<welcome-file>order_processing.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>order_processing</servlet-name>
<servlet-class>test.abc.io.OrderProcessing</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>order_processing</servlet-name>
<url-pattern>/order_processing</url-pattern>
</servlet-mapping>
</web-app>
When i debug this project and click on Submit button its gives the following error:
SEVERE: Servlet.service() for servlet jsp threw exception
javax.el.PropertyNotFoundException: Property 'firstname' not found on type test.abc.io.User_Objects
and I also want to do some task on "order_processing.jsp" page load.
but when i run this project, my order_processing.jsp page display successfully but on that case my doGet method of OrderProcessing.java did not call.
I am using JAVA with Eclipse Mars.
The object "User_Objects" is no java bean:
firstname, lastName and commEMail are fields and not properties.
Try to add a getter / setter for firstName, lastName and commEMail

Java servlet not redirecting properly

I have two pages jsp pages First one is AppLogin.jsp and other one is Login.jsp
I want that when i click on Submit button of AppLogin.jsp page, i want redirect to Login.jsp page with password value
and check this value on page load of Login.jsp page.
For this i did following code
but the below code did not work.
I don't want to use Session and append value on url.
AppLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>App Login</title>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>Application Name</td>
<td><input type="text" value="" name="txtApplication" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" value="" name="txtUsername" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" value="" name="txtPassword" /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, ClientProtocolException {
try {
String password = req.getParameter("txtPassword");
req.setAttribute("crendential",password);
RequestDispatcher rd = req.getRequestDispatcher("Login.jsp");
rd.forward(req,res);
}
catch (Exception e) {
System.out.println("LoginServletException>>>>>>>>>>" + e);
}
}
}
Login.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="saveServlet" method="post">
<table>
<tr>
<td>Application :</td>
<td><input type="text" value="" name="txtApplication" /></td>
</tr>
<tr>
<td>Username :</td>
<td><input type="text" value="" name="txtUsername" /></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="text" value="" name="txtPassword" /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
try {
String crendential = (String) req.getAttribute("crendential");
System.out.println("crendential>>>>>>>>>>" + crendential);
}
catch (Exception e) {
System.out.println("LoginServletException>>>>>>>>>>" + e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String crendential = (String) req.getAttribute("crendential");
System.out.println("crendential>>>>>>>>>>" + crendential);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>xyz</display-name>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>xyz.io.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>xyz.io.SaveServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/Login.jsp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>AppLogin.jsp</welcome-file>
</welcome-file-list>
</web-app>
I am using Java with Eclipse Mars.
Login.jsp has a request attribute "credentials." To pass this value to the saveServlet there would be two possibilities:
Store the credentials instead as session attribute
Pass the credentials on in Login.jsp, say as hidden form input field.
<input type="hidden" name="credentials" value="${credentials}">
Correction:
I did miss the somewhat hard to digest web.xml with its servlet mappings.
In general how it often is done
A servlet mapping:
xyz.io.DisplayLoginServlet
/login
xyz.io.ProcessLoginServlet
/authorize
DisplayLoginServlet
doGet
prepares the form data (request attributes)
forwards to some displayLogin.jsp
doPost
validates the form, possibly redisplays the form with error messages (doGet)
otherwise when successfully done,
set session attributes
and redirect to the home page.
displayLogin.jsp
(posts to the same servlet)
And so on.
The mapped servlet URLs do not relate to JSPs.
The servlet is the entry point, the controller. It prepares the data model, puts them in the request attributes, and forwards to some JSP, the view. The servlet can on successfull login use an other JSP for instance.
Here we redirect after a successfull post. That is the brower is told to get the redirected page as answer. The effect is that the user cannot reload the page and effectively re-post the HTML form.
I think making a clean distinction will already help.

Apache Tomcat:Path Error

Hı,I have JSP and Web_Service.java.Web_Service.java is just a java class.It has a methods which are called by JSP.JSP file has a two button and two textbox.And when ı enter a number and click button,ıt call java class to do something on number.
This is my JSP class Web_Client.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form
action='http://localhost:8080/WebService/services/Web_Service/FahrenheitToCelsius'
method="post" target="_blank">
<table>
<tr>
<td>Fahrenheit to Celsius:</td>
<td><input type="text" size="30" name="Input"></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Convert"></td>
</tr>
</table>
</form>
<form
action='http://localhost:8080/WebService/services/Web_Service/CelsiusToFahrenheit'
method="post" target="_blank">
<table>
<tr>
<td>Celsius to Fahrenheit:</td>
<td><input type="text" size="30" name="Input"></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Convert"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is my web service class which is in package mypack:Web_Service.java: package mypacket;
/**
* Web Service
* Temp Converter
*
*#version 1.0 Release 1
*#author mert
*
**/
public class Web_Service{
public String FahrenheitToCelsius(String Input) {
if (!Input.isEmpty() && isNumber(Input)) {
double result = 0;
result = Double.parseDouble(Input);
result = (((result) - 32) / 9) * 5;
Input = Double.toString(result);
return Input;
} else {
return "ERROR! Please enter the input number...";
}
}
public String CelsiusToFahrenheit(String Input) {
if (!Input.isEmpty() && isNumber(Input)) {
double result = 0;
result = Double.parseDouble(Input);
result = (((result) * 9) / 5) + 32;
Input = Double.toString(result);
return Input;
} else {
return "ERROR! Please enter the input number...";
}
}
The following code is my 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>Bitirme_Proje_New</display-name>
<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>/axis2-web/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>Apache-Axis Servlet</display-name>
<servlet-name>AxisServlet</servlet-name>
<servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Apache-Axis Admin Servlet Web Admin</display-name>
<servlet-name>AxisAdminServlet</servlet-name>
<servlet-class>org.apache.axis2.transport.http.AxisAdminServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AxisAdminServlet</servlet-name>
<url-pattern>/axis2-admin/*</url-pattern>
</servlet-mapping>
</web-app>
When I run the project, the JSP works: Buttons and textbox appears. But when I enter a number ın a textbox and click button, I get this error:
HTTP Status 404 -
/WebService/services/Web_Service/FahrenheitToCelsius
type Status report
message /WebService/services/Web_Service/FahrenheitToCelsius
description The requested resource is not available.
Apache Tomcat/6.0.37
Why does Apache Tomcat say "The requested resource is not available"? What can I do for this error?
There is a incorrect web service call.
You have to set up some page for action property of form. The page can to do web service call.
I propose Spring MVC rest service with JSON for your: http://www.javacodegeeks.com/2013/04/spring-mvc-easy-rest-based-json-services-with-responsebody.html

Categories

Resources